package com.loan.system.controller.wechat;

import com.loan.system.config.FileUploadConfig;
import com.loan.system.domain.entity.Document;
import com.loan.system.domain.enums.ExceptionEnum;
import com.loan.system.domain.pojo.Result;
import com.loan.system.domain.vo.DocumentVO;
import com.loan.system.service.DocumentService;
import com.loan.system.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/wechat/file")
@Api(tags = "文件处理接口")
public class UploadController {
    @Autowired
    private DocumentService fileService;
    @Autowired
    private FileUploadConfig config;

    /** 上传文件（支持任意类型，只要在白名单内） */
    @PostMapping("/upload/{caseId}/{type}")
    @ApiOperation("文件上传")//若合同不是统一提交，则合同1，合同2，合同3
    public Result uploadFile(@PathVariable("caseId") Long caseId,@PathVariable("type") String fileType,@RequestParam("file") MultipartFile[] files) throws IOException{
        fileService.deleteFileByCaseIdAndDictType(caseId,fileType);
        //删除本地文件
        deleteFile(caseId,fileType);

        List<DocumentVO> fileList = new ArrayList<>();
        for (int i=0 ; i < files.length ; i++){
            MultipartFile file =files[i];

            if (file.isEmpty())
                return ResultUtil.error(ExceptionEnum.FILE_IS_EMPTY);

            String originalName = file.getOriginalFilename();
            String ext = FilenameUtils.getExtension(originalName).toLowerCase(Locale.ROOT);

            // 从配置中读取允许的扩展名
            Set<String> allowed = config.getAllowedExtensions();
            if (!allowed.contains(ext)) {
                ResultUtil.error(ExceptionEnum.FILE_UPLOAD_TYPE_NOT_DEFINED);
            }

            String newFileName = null;
            // 生成新的文件名
            if(i == 0)
                newFileName = String.format("%d-%s-%s.%s", caseId, fileType, originalName, ext);
            else
                newFileName = String.format("%d-%s-%s(%d).%s", caseId, fileType, originalName, i, ext);

            // 创建目录
            File uploadDir = new File(config.getUploadDir(), caseId + "/" + fileType);
            if (!uploadDir.exists() && !uploadDir.mkdirs()) {
                return ResultUtil.error(ExceptionEnum.DIRECTORY_CREATE_ERROR);
            }

            // 使用NIO复制流，稳定性更好
            File destFile = new File(uploadDir, newFileName);
            try (InputStream in = file.getInputStream()) {
                Files.copy(in, destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }

            Document document = new Document();
            document.setCaseId(caseId);
            document.setFileName(newFileName);
            document.setOriginName(originalName);
            document.setFilePath(destFile.getPath());
            document.setFileSize(file.getSize());
            document.setDocType(ext);
            document.setDictType(fileType);
            document.setIsDelete( false);
            document.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            document.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            fileList.add(fileService.uploadFile(document));
        }

        return ResultUtil.success("上传成功", fileList);
    }


    /** 下载文件 */
    @GetMapping("/download/{fileName}")
    @ApiOperation("文件下载")
    public void downloadFile(@PathVariable String fileName, HttpServletResponse response)throws  IOException{
        File file = new File(config.getUploadDir(), fileName);
        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
            return;
        }

        response.setContentType(Files.probeContentType(file.toPath()));
        response.setHeader("Content-Disposition",
                "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

        try (InputStream in = new FileInputStream(file);
             OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[8192];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        }
    }

    /** 删除文件 */
    @DeleteMapping("/delete/{caseId}/{type}")
    @ApiOperation("文件删除")
    public Result deleteFileByFileName(@RequestParam String fileName ,@PathVariable Long caseId, @PathVariable String fileType) {
        String newUploadDir = config.getUploadDir() + caseId + "/" + fileType;
        File file = new File(newUploadDir, fileName);

        if (!file.exists())
            return ResultUtil.error(ExceptionEnum.FILE_NOT_EXIST);

        boolean isDelete = file.delete();
        if (!isDelete)
            return ResultUtil.error(ExceptionEnum.FILE_DELETE_ERROR);

        return ResultUtil.success("文件删除成功");
    }

    /** 删除文件 */
    private void deleteFile(Long caseId, String fileType) {
        // 构造待删除文件所在的目录路径
        File uploadDir = new File(config.getUploadDir(), caseId + "/" + fileType);

        if (!uploadDir.exists()) {
            return; // 目录不存在，直接返回
        }

        // 获取目录下所有文件
        File[] files = uploadDir.listFiles();
        if (files == null || files.length == 0) {
            return; // 没有文件需要删除
        }

        boolean allDeleted = true;
        for (File file : files) {
            if (!file.delete()) { // 尝试删除每个文件
                allDeleted = false; // 如果有文件未能成功删除，则标记为false
                break;
            }
        }

//        if (allDeleted) {
//            // 尝试删除空目录
//            if (!uploadDir.delete()) {
//                // 如果删除目录失败，可以记录日志或采取其他措施
//                System.out.println("Failed to delete empty directory: " + uploadDir.getAbsolutePath());
//            }
//        } else {
//            // 如果有文件未能成功删除，可以记录日志或采取其他措施
//            System.out.println("Failed to delete some files in directory: " + uploadDir.getAbsolutePath());
//        }
    }


//    @PostMapping("save/{caseId}/{type}")
//    public Result saveFile(@PathVariable("caseId") Long caseId,@PathVariable("type") String type,@RequestParam String fileName){
//        return ResultUtil.success();
//    }
}
