package cn.iocoder.yudao.module.pms.controller.admin;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/rq/file")
@Slf4j
public class FileUploadController {

    @Value("${file.upload-path}")
    private String uploadPath;
    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    @PermitAll
    @TenantIgnore
    public CommonResult<Map<String, Object>> uploadFiles(
            @RequestParam("files") MultipartFile[] files, @RequestParam(value = "isFolder", defaultValue = "false") boolean isFolder,
            @RequestHeader("device-id") String deviceId, HttpServletRequest request) {

        // 创建根目录（如果不存在）
        File rootDir = new File(uploadPath);
        if (!rootDir.exists()) {
            rootDir.mkdirs();
        }

        List<Map<String, Object>> fileList = new ArrayList<>();
        Map<String, Object> folderStructure = new HashMap<>();

        try {
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue;
                }

                // 获取原始文件名（包含路径信息）
                String originalFilename = file.getOriginalFilename();
                if (StrUtil.isBlank(originalFilename)) {
                    continue;
                }

//                // 构建文件保存路径
                Path filePath = Paths.get(uploadPath, originalFilename);
//
//                // 创建父目录
                File parentDir = filePath.getParent().toFile();
                if (!parentDir.exists()) {
                    parentDir.mkdirs();
                }
//
//                // 保存文件
//                file.transferTo(filePath.toFile());

                // 记录文件信息
                Map<String, Object> fileInfo = new HashMap<>();
                fileInfo.put("name", FileUtil.getName(originalFilename));
                String filePaths = fileService.createFile(FileUtil.getName(originalFilename), deviceId+File.separator+originalFilename, IoUtil.readBytes(file.getInputStream()));

                fileInfo.put("path", originalFilename);
                fileInfo.put("filePath", filePaths);
                fileInfo.put("size", file.getSize());
                fileInfo.put("isFolder", false);
                fileList.add(fileInfo);

                // 构建文件夹结构
                buildFolderStructure(folderStructure, originalFilename);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("files", fileList);
            result.put("folderStructure", folderStructure);
            result.put("message", "上传成功");

            return CommonResult.success(result);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return CommonResult.error(new ErrorCode(122, e.getMessage()));
        }
    }

    /**
     * 构建文件夹层级结构
     */
    private void buildFolderStructure(Map<String, Object> structure, String filePath) {
        String[] pathParts = filePath.split("/");

        // 如果是文件，最后一部分是文件名
        boolean isFile = pathParts.length > 0 && FileUtil.isFile(filePath);
        int depth = isFile ? pathParts.length - 1 : pathParts.length;

//        Map<String, Object> currentLevel = structure;

        for (int i = 0; i < depth; i++) {
            String part = pathParts[i];
            boolean isLastFolder = i == depth - 1;

            if (!structure.containsKey(part)) {
                Map<String, Object> newLevel = new HashMap<>();
                newLevel.put("isFolder", true);
                newLevel.put("children", new HashMap<>());

                if (isLastFolder && isFile) {
                    // 如果是文件的父文件夹，添加文件信息
                    List<String> files = (List<String>) newLevel.getOrDefault("files", new ArrayList<>());
                    files.add(pathParts[pathParts.length - 1]);
                    newLevel.put("files", files);
                }

                structure.put(part, newLevel);
            } else {
                // 如果文件夹已存在，检查是否需要添加文件
                if (isLastFolder && isFile) {
                    Map<String, Object> existingLevel = (Map<String, Object>) structure.get(part);
                    List<String> files = (List<String>) existingLevel.getOrDefault("files", new ArrayList<>());
                    files.add(pathParts[pathParts.length - 1]);
                    existingLevel.put("files", files);
                }
            }

            // 进入下一级
            structure = (Map<String, Object>) ((Map<String, Object>) structure.get(part)).get("children");
        }
    }
}
