package com.aps.controller.gantt;

import com.aps.common.util.R;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/api/files")
@Tag(name = "文件上传管理", description = "文件上传管理")
public class FileUploadController {

    // 从配置文件中获取文件存储目录
    @Value("${file.upload.dir:uploads}")
    private String uploadDir;
    
    private String absoluteUploadDir;

    @PostConstruct
    public void init() {
        // 获取上传目录的绝对路径
        absoluteUploadDir = Paths.get(uploadDir).toAbsolutePath().toString();
        // 确保上传目录存在
        File directory = new File(absoluteUploadDir);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            if (created) {
                log.info("创建上传目录: {}", absoluteUploadDir);
            } else {
                log.error("创建上传目录失败: {}", absoluteUploadDir);
            }
        } else {
            log.info("使用已存在的上传目录: {}", absoluteUploadDir);
        }
    }

    @PostMapping(value = "/upload/machines", consumes = "multipart/form-data")
    @Operation(summary = "上传machines.json文件", description = "上传machines.json文件")
    @RequestBody(description = "选择要上传的 machines.json 文件", required = true,
            content = @Content(mediaType = "multipart/form-data"))
    public R<String> uploadMachines(
        @Parameter(description = "选择要上传的 machines.json 文件") 
        @RequestParam("file") MultipartFile file) {
        return uploadFile(file, "machines.json");
    }

    @PostMapping(value = "/upload/orders", consumes = "multipart/form-data")
    @Operation(summary = "上传orders.json文件", description = "上传orders.json文件")
    @RequestBody(description = "选择要上传的 orders.json 文件", required = true,
            content = @Content(mediaType = "multipart/form-data"))
    public R<String> uploadOrders(
        @Parameter(description = "选择要上传的 orders.json 文件") 
        @RequestParam("file") MultipartFile file) {
        return uploadFile(file, "orders.json");
    }

    @PostMapping(value = "/upload/products", consumes = "multipart/form-data")
    @Operation(summary = "上传products.json文件", description = "上传products.json文件")
    @RequestBody(description = "选择要上传的 products.json 文件", required = true,
            content = @Content(mediaType = "multipart/form-data"))
    public R<String> uploadProducts(
        @Parameter(description = "选择要上传的 products.json 文件") 
        @RequestParam("file") MultipartFile file) {
        return uploadFile(file, "products.json");
    }

    private R<String> uploadFile(MultipartFile file, String expectedFileName) {
        if (file.isEmpty()) {
            return R.failed("上传文件不能为空");
        }

        // 检查文件名
        if (!file.getOriginalFilename().equals(expectedFileName)) {
            return R.failed("请上传正确的文件: " + expectedFileName);
        }

        try {
            // 保存文件到指定目录
            String filePath = Paths.get(absoluteUploadDir, expectedFileName).toString();
            file.transferTo(new File(filePath));
            
            log.info("文件上传成功: {}", filePath);
            return R.ok("文件上传成功: " + expectedFileName);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return R.failed("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取上传文件的路径
     * @param fileName 文件名
     * @return 文件路径
     */
    public String getUploadedFilePath(String fileName) {
        return Paths.get(absoluteUploadDir, fileName).toString();
    }
    
    /**
     * 检查文件是否存在
     * @param fileName 文件名
     * @return 是否存在
     */
    public boolean isFileUploaded(String fileName) {
        String filePath = Paths.get(absoluteUploadDir, fileName).toString();
        return new File(filePath).exists();
    }
}