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.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
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.Path;
import java.nio.file.Paths;
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 MultipartFile file,@RequestParam Map<String , String>  isDelete) throws IOException{
        Iterator<Map.Entry<String, String>> iterator = isDelete.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println(entry.getKey());
            Long id = Long.parseLong(entry.getKey());
            System.out.println(entry.getValue());
            Integer value = Integer.parseInt(entry.getValue());
            Document document = fileService.findById(id);
            if (ObjectUtils.isEmpty( document))
                break;

            if( value!= 0 ){
                fileService.deleteFileById(id);
                //删除本地文件
               deleteFile1(document.getFilePath());
            }
        }

        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 = String.format("%d-%s-%s.%s", caseId, fileType, UUID.randomUUID(), ext);;
        // 生成新的文件名

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

        // 使用NIO复制流，稳定性更好
        File destFile = new File(uploadDir, newFileName);
        try (InputStream in = file.getInputStream()) {
            System.out.println(destFile.toPath());
            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")));
        DocumentVO documentVO = fileService.uploadFile(document);

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

    private void deleteFile1(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return;
        }

        try {
            Path path = Paths.get(filePath);
            boolean deleted = Files.deleteIfExists(path);
            if (deleted) {
                System.out.println("文件删除成功: " + filePath);
            } else {
                System.out.println("文件不存在或已被删除: " + filePath);
            }
        } catch (IOException e) {
            System.err.println("删除文件时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }


    /** 下载文件 */
    @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()) {
            System.out.println("Directory does not exist: " + uploadDir.getAbsolutePath());
            return; // 目录不存在，直接返回
        }

        // 获取目录下所有文件
        File[] files = uploadDir.listFiles();
        if (files == null || files.length == 0) {
            System.out.println("No files to delete in directory: " + uploadDir.getAbsolutePath());
            return; // 没有文件需要删除
        }

        boolean allDeleted = true;
        for (File file : files) {
            System.out.println("Attempting to delete file: " + file.getAbsolutePath());
            if (!file.delete()) { // 尝试删除每个文件
                allDeleted = false; // 如果有文件未能成功删除，则标记为false
                System.out.println("Failed to delete file: " + file.getAbsolutePath());
            } else {
                System.out.println("Successfully deleted file: " + file.getAbsolutePath());
            }
        }

        if (!allDeleted) {
            System.out.println("Failed to delete some files in directory: " + uploadDir.getAbsolutePath());
        } else {
            System.out.println("All files deleted successfully 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();
//    }
}
