package com.mini.capi.biz;

import com.mini.capi.biz.domain.BizFileFolders;
import com.mini.capi.biz.domain.BizFiles;
import com.mini.capi.biz.domain.BizHomeUser;
import com.mini.capi.biz.domain.BizSubTask;
import com.mini.capi.biz.service.BizFileFoldersService;
import com.mini.capi.biz.service.BizFilesService;
import com.mini.capi.biz.service.BizSubTaskService;
import com.mini.capi.model.ApiResult;
import com.mini.capi.model.CreateFolder;
import com.mini.capi.model.info.TodoHandleDTO;
import com.mini.capi.utils.FileUtils;
import com.mini.capi.utils.vId;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/biz")
public class workController {


    @Resource
    private BizSubTaskService bizSubTaskService;

    @Resource
    private BizFileFoldersService bizFileFoldersService;

    @Resource
    private BizFilesService bizFilesService;

    private static final String UPLOAD_PATH = "/ogsapp/files/";


    /**
     * 完成待办
     *
     * @return
     */
    @PostMapping("/finishTodoSub")
    public ResponseEntity<Void> finishTodoSub(@RequestBody TodoHandleDTO handleDTO) {
        // 验证参数
        if (handleDTO.getTaskId() == null || handleDTO.getOpinion() == null || handleDTO.getOpinion().trim().isEmpty()) {
            return ResponseEntity.badRequest().build();
        }
        try {
            // 调用服务层处理任务
            BizSubTask bizSubTask = bizSubTaskService.getById(handleDTO.getTaskId());
            bizSubTask.setUstatus("CPT");
            bizSubTask.setFinishTime(LocalDateTime.now());
            bizSubTask.setRemark(handleDTO.getOpinion());
            bizSubTaskService.updateById(bizSubTask);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            // 处理异常（如任务不存在、数据库错误等）
            return ResponseEntity.status(500).build();
        }
    }


    /**
     * 创建文件夹
     */
    @PostMapping("/createFolder")
    public ApiResult<?> CreateFolder(@Validated @RequestBody CreateFolder request) {
        try {
            String dirId = vId.getCid();
            BizFileFolders folders = new BizFileFolders();
            folders.setFolderId(dirId);
            folders.setFolderName(request.getName());
            folders.setParentId(request.getParentId());
            bizFileFoldersService.save(folders);
            FileUtils.checkDirExists(UPLOAD_PATH + dirId);
            return ApiResult.success();
        } catch (Exception e) {
            // 异常捕获，返回失败响应
            return ApiResult.error(101, e.getMessage());
        }
    }


    @PostMapping("uploadFiles")
    public ResponseEntity<Map<String, Object>> uploadFiles(HttpSession session,
                                                           @RequestParam(value = "folderId") String folderId,
                                                           @RequestParam("files") MultipartFile[] files) {
        BizHomeUser user = (BizHomeUser) session.getAttribute("currentUser");
        Map<String, Object> result = new HashMap<>();
        Path basePath = Paths.get(UPLOAD_PATH + folderId);
        FileUtils.checkDirExists(basePath.toString());
        // 统计成功/失败数量
        int successCount = 0;
        int failCount = 0;
        // 遍历上传的文件
        for (MultipartFile file : files) {
            BizFiles bizFiles = new BizFiles();
            try {
                // 1. 获取原始文件名和后缀
                String originalFilename = file.getOriginalFilename();
                String fileType = FilenameUtils.getExtension(originalFilename);
                String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                // 2. 生成唯一文件名（避免文件名冲突）
                String uniqueFileName = vId.getCid() + fileSuffix;
                // 3. 构建文件存储路径
                Path filePath = basePath.resolve(uniqueFileName);
                // 4. 保存文件到本地磁盘
                file.transferTo(filePath.toFile());
                bizFiles.setFileName(originalFilename);
                bizFiles.setFolderId(folderId);
                bizFiles.setFileSize(FileUtils.formatFileSize(file.getSize()));
                bizFiles.setFileType(fileType);
                bizFiles.setFilePath(filePath.toString());
                bizFiles.setCreatorId(user.getUserId());
                bizFiles.setIsDeleted(0);
                bizFilesService.save(bizFiles);
                successCount++;
            } catch (Exception e) {
                System.err.print(e.getMessage());
                failCount++;
            }
        }
        // 构建响应结果
        result.put("success", true);
        result.put("message", "上传成功");
        result.put("successCount", successCount);
        result.put("failCount", failCount);
        return ResponseEntity.ok(result);
    }
}
