package com.hotent.enterpriseDeclare.controller.material;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.controller.BaseController;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import com.hotent.project.manager.CostProjectTaskManager;
import com.hotent.project.manager.CostProjectTaskMaterialSummaryDetailManager;
import com.hotent.project.manager.CostProjectTaskMaterialSummaryManager;
import com.hotent.project.model.CostProjectTask;
import com.hotent.project.model.CostProjectTaskMaterialSummary;
import com.hotent.project.model.CostProjectTaskMaterialSummaryDetail;
import com.hotent.project.req.ArchiveProofreadReq;
import com.hotent.project.req.MaterialSummarySortReq;
import com.hotent.project.resp.ArchiveProofreadResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 资料归纳主表 前端控制器
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-01-27
 */
@RestController
@RequestMapping("/api/materialSummary/v1")
@Api(tags = "资料归纳主表")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostProjectTaskMaterialSummaryController extends BaseController<CostProjectTaskMaterialSummaryManager, CostProjectTaskMaterialSummary> {


    @Autowired
    private CostProjectTaskManager costProjectTaskManager;

    @Autowired
    private CostProjectTaskMaterialSummaryDetailManager costProjectTaskMaterialSummaryDetailManager;

    /**
     * 根据taskId获取资料归纳列表
     * @param taskId 任务ID
     * @return 资料归纳列表（包含明细）
     */
    @GetMapping(value = "/listByTaskId")
    @ApiOperation(value = "根据taskId获取资料归纳列表", httpMethod = "GET", notes = "根据taskId获取资料归纳列表（包含明细）")
    @Transactional
    public CommonResult<List<CostProjectTaskMaterialSummary>> listByTaskId(
            @ApiParam(name = "taskId", value = "任务ID", required = true)
            @RequestParam(required = true) String taskId) {

        List<CostProjectTaskMaterialSummary> summaryList = baseService.listByTaskId(taskId);
        // 如果为空，自动生成14个基础资料类别
        if (summaryList == null || summaryList.isEmpty()) {
            // 获取任务信息
            com.hotent.project.model.CostProjectTask mainTask = costProjectTaskManager.getById(taskId);
            if (mainTask != null) {
                // 查询子任务列表
                List<CostProjectTask> childTasks = costProjectTaskManager.list(
                        new LambdaQueryWrapper<CostProjectTask>().eq(CostProjectTask::getPid, taskId)
                );
                // 同步生成资料归纳
                asyncMaterialSummaryService.generateMaterialSummary(mainTask, childTasks);
                // 计算总页数
                asyncMaterialSummaryService.calculatePageCountAsync(mainTask.getId());
                // 重新查询
                summaryList = baseService.listByTaskId(taskId);
            }
        }

        return CommonResult.<List<CostProjectTaskMaterialSummary>>ok().value(summaryList);
    }

    @GetMapping(value = "/DetailistlByMasterId")
    @ApiOperation(value = "根据taskId获取资料归纳列表", httpMethod = "GET", notes = "根据taskId获取资料归纳列表（包含明细）")
    @Transactional
    public CommonResult<List<CostProjectTaskMaterialSummaryDetail>> listByMasetId(
            @ApiParam(name = "masterId", value = "主文件夹ID", required = true)
            @RequestParam(required = true) String masterId) {

        List<CostProjectTaskMaterialSummaryDetail> list = costProjectTaskMaterialSummaryDetailManager.list(
                new LambdaQueryWrapper<CostProjectTaskMaterialSummaryDetail>()
                        .eq(CostProjectTaskMaterialSummaryDetail::getMasterId, masterId)
        );
        return CommonResult.<List<CostProjectTaskMaterialSummaryDetail>>ok().value(list);
    }

    /**
     * 根据id获取资料归纳详情
     * @param id 主表ID
     * @return 资料归纳详情（包含明细）
     */
    @GetMapping(value = "/getDetail")
    @ApiOperation(value = "根据id获取资料归纳详情", httpMethod = "GET", notes = "根据id获取资料归纳详情（包含明细）")
    public CommonResult<CostProjectTaskMaterialSummary> getDetail(
            @ApiParam(name = "id", value = "主表ID", required = true)
            @RequestParam(required = true) String id) {
        return CommonResult.<CostProjectTaskMaterialSummary>ok().value(baseService.getDetail(id));
    }

    /**
     * 新增、更新资料归纳主表
     * @param summary 资料归纳主表
     * @return
     */
    @PostMapping(value = "/save")
    @ApiOperation(value = "新增、更新资料归纳主表", httpMethod = "POST", notes = "新增、更新资料归纳主表")
    @Transactional
    public CommonResult<String> save(
            @ApiParam(name = "summary", value = "资料归纳主表", required = true)
            @RequestBody CostProjectTaskMaterialSummary summary) {
        String msg = StringUtil.isEmpty(summary.getId()) ? "添加资料归纳成功" : "更新资料归纳成功";
        baseService.createOrUpdate(summary);
        return CommonResult.<String>ok().message(msg);
    }

    /**
     * 新增、更新资料归纳子表
     * @return
     */
    @PostMapping(value = "/saveDetail")
    @ApiOperation(value = "新增、更新资料归纳子表", httpMethod = "POST", notes = "新增、更新资料归纳主表")
    @Transactional
    public CommonResult<String> saveDetail(
            @ApiParam(name = "summary", value = "资料归纳主表", required = true)
            @RequestBody CostProjectTaskMaterialSummaryDetail detail) {
        if (detail.getMasterId()==null){
            return CommonResult.<String>error().message("请选择资料归纳");
        }
        CostProjectTaskMaterialSummary summary = baseService.getById(detail.getMasterId());
        if (summary==null){
            return CommonResult.<String>error().message("请选择资料归纳");
        }
        detail.setTaskId(summary.getTaskId());

        // 如果有附件URL，自动解析文件页数
        if (StringUtil.isNotEmpty(detail.getAttachmentUrl())) {
            try {
                int pageCount = asyncMaterialSummaryService.calculateFilePageCount(detail.getAttachmentUrl());
                detail.setPageCount(pageCount);
            } catch (Exception e) {
                System.err.println("解析文件页数失败：" + e.getMessage());
            }
        }

        String msg = StringUtil.isEmpty(detail.getId()) ? "添加资料归纳成功" : "更新资料归纳成功";
        if (detail.getId()==null){
            detail.setCreateTime(LocalDateTime.now());
        }
        detail.setUpdateTime(LocalDateTime.now());
        costProjectTaskMaterialSummaryDetailManager.createOrUpdate(detail);

        // 保存明细后，更新主表的总页数
        try {
            asyncMaterialSummaryService.updateMasterTotalPageCount(detail.getMasterId());
        } catch (Exception e) {
            System.err.println("更新主表总页数失败：" + e.getMessage());
            // 更新失败不影响返回结果
        }

        return CommonResult.<String>ok().message(msg);
    }



    /**
     * 删除资料归纳明细
     * @param id 明细ID
     * @return
     */
    @DeleteMapping(value = "/deleteDetail")
    @ApiOperation(value = "删除资料归纳明细", httpMethod = "DELETE", notes = "删除资料归纳明细并同步更新主表总页数")
    @Transactional
    public CommonResult<String> deleteDetail(
            @ApiParam(name = "id", value = "明细ID", required = true)
            @RequestParam(required = true) String id) {

        // 先查询明细信息，获取主表ID
        CostProjectTaskMaterialSummaryDetail detail = costProjectTaskMaterialSummaryDetailManager.getById(id);
        if (detail == null) {
            return CommonResult.<String>error().message("资料归纳明细不存在");
        }

        String masterId = detail.getMasterId();

        // 删除明细（物理删除）
        costProjectTaskMaterialSummaryDetailManager.deleteById(id);

        // 删除后，更新主表的总页数
        try {
            if (StringUtil.isNotEmpty(masterId)) {
                asyncMaterialSummaryService.updateMasterTotalPageCount(masterId);
            }
        } catch (Exception e) {
            System.err.println("更新主表总页数失败：" + e.getMessage());
            // 更新失败不影响删除结果
        }

        return CommonResult.<String>ok().message("删除资料归纳明细成功");
    }

    /**
     * 批量保存资料归纳（主表+明细）
     * @param summary 资料归纳主表（包含detailList）
     * @return
     */
    @PostMapping(value = "/saveWithDetails")
    @ApiOperation(value = "批量保存资料归纳（主表+明细）", httpMethod = "POST", notes = "批量保存资料归纳（主表+明细）")
    @Transactional
    public CommonResult<String> saveWithDetails(
            @ApiParam(name = "summary", value = "资料归纳主表（包含detailList）", required = true)
            @RequestBody CostProjectTaskMaterialSummary summary) {
        String msg = StringUtil.isEmpty(summary.getId()) ? "保存资料归纳成功" : "更新资料归纳成功";
        baseService.saveWithDetails(summary);
        return CommonResult.<String>ok().message(msg);
    }

    /**
     * 删除资料归纳（级联删除明细）
     * @param id 主表ID
     * @return
     */
    @DeleteMapping(value = "/delete")
    @ApiOperation(value = "删除资料归纳", httpMethod = "DELETE", notes = "删除资料归纳（级联删除明细）")
    @Transactional
    public CommonResult<String> delete(
            @ApiParam(name = "id", value = "主表ID", required = true)
            @RequestParam(required = true) String id) {
        baseService.deleteById(id);
        return CommonResult.<String>ok().message("删除资料归纳成功");
    }

    /**
     * 资料排序
     * @param req 排序请求
     * @return
     */
    @PostMapping(value = "/sort")
    @ApiOperation(value = "资料排序", httpMethod = "POST", notes = "资料排序（上移/下移）")
    @Transactional
    public CommonResult<String> sort(
            @ApiParam(name = "req", value = "排序请求", required = true)
            @RequestBody MaterialSummarySortReq req) {
        if (StringUtil.isEmpty(req.getId()) || StringUtil.isEmpty(req.getDirection())) {
            return CommonResult.<String>error().message("ID和排序方向不能为空");
        }
        baseService.sort(req.getId(), req.getDirection());
        return CommonResult.<String>ok().message("排序成功");
    }

    @Autowired
    private com.hotent.project.service.AsyncMaterialSummaryService asyncMaterialSummaryService;



    // ==================== 卷宗校对功能接口 ====================

    /**
     * 校对列表
     * @param taskId 任务ID
     * @return 卷宗校对列表
     */
    @GetMapping(value = "/archiveProofreadList")
    @ApiOperation(value = "获取卷宗校对列表", httpMethod = "GET", notes = "获取卷宗校对列表（从封面到封底，按页码排序）")
    public CommonResult<List<ArchiveProofreadResp>> archiveProofreadList(
            @ApiParam(name = "taskId", value = "任务ID", required = true)
            @RequestParam(required = true) String taskId)
    {
        // 获取所有资料归纳数据（包含封面、目录、封底）
        List<CostProjectTaskMaterialSummary> summaryList = baseService.listAllByTaskId(taskId);

        // 分离封面、目录、封底和普通资料
        CostProjectTaskMaterialSummary coverSummary = null;    // -1
        CostProjectTaskMaterialSummary catalogSummary = null;  // -2
        CostProjectTaskMaterialSummary backCoverSummary = null; // -3
        List<CostProjectTaskMaterialSummary> materialList = new ArrayList<>();

        for (CostProjectTaskMaterialSummary summary : summaryList) {
            Integer orderNum = summary.getMaterialOrderNum();
            if (orderNum != null && orderNum == -1) {
                coverSummary = summary;
            } else if (orderNum != null && orderNum == -2) {
                catalogSummary = summary;
            } else if (orderNum != null && orderNum == -3) {
                backCoverSummary = summary;
            } else {
                materialList.add(summary);
            }
        }

        List<ArchiveProofreadResp> resultList = new ArrayList<>();
        int currentPage = 1;
        int displayOrderNum = 1;

        // 1. 案卷封面（不计入页码）
        ArchiveProofreadResp coverResp = new ArchiveProofreadResp();
        coverResp.setOrderNum(displayOrderNum++);
        coverResp.setMaterialName("卷宗封面");
        coverResp.setDocumentType(1);
        coverResp.setCanGenerate("1");
        coverResp.setCanEdit("1");
        coverResp.setPageRange("—");
        if (coverSummary != null && coverSummary.getDetailList() != null && !coverSummary.getDetailList().isEmpty()) {
            CostProjectTaskMaterialSummaryDetail coverDetail = coverSummary.getDetailList().get(0);
            if (StringUtil.isNotEmpty(coverDetail.getAttachmentUrl())) {
                coverResp.setRelatedId(coverSummary.getId());
                coverResp.setAttachmentUrl(coverDetail.getAttachmentUrl());
                coverResp.setGenerateStatus("1");
            } else {
                coverResp.setRelatedId(coverSummary.getId());
                coverResp.setGenerateStatus("0");
            }
        } else {
            coverResp.setGenerateStatus("0");
        }
        resultList.add(coverResp);

        // 2. 卷内目录（不计入页码）
        ArchiveProofreadResp catalogResp = new ArchiveProofreadResp();
        catalogResp.setOrderNum(displayOrderNum++);
        catalogResp.setMaterialName("卷内目录");
        catalogResp.setDocumentType(2);
        catalogResp.setCanGenerate("1");
        catalogResp.setCanEdit("1");
        catalogResp.setPageRange("—");
        if (catalogSummary != null && catalogSummary.getDetailList() != null && !catalogSummary.getDetailList().isEmpty()) {
            CostProjectTaskMaterialSummaryDetail catalogDetail = catalogSummary.getDetailList().get(0);
            if (StringUtil.isNotEmpty(catalogDetail.getAttachmentUrl())) {
                catalogResp.setRelatedId(catalogSummary.getId());
                catalogResp.setAttachmentUrl(catalogDetail.getAttachmentUrl());
                catalogResp.setGenerateStatus("1");
            } else {
                catalogResp.setRelatedId(catalogSummary.getId());
                catalogResp.setGenerateStatus("0");
            }
        } else {
            catalogResp.setGenerateStatus("0");
        }
        resultList.add(catalogResp);

        // 3. 14个资料归纳
        for (CostProjectTaskMaterialSummary summary : materialList) {
            ArchiveProofreadResp resp = new ArchiveProofreadResp();
            resp.setOrderNum(displayOrderNum++);
            resp.setMaterialName(summary.getMaterialName());
            resp.setDocumentType(0);
            resp.setCanGenerate("0");
            resp.setCanEdit("0");
            resp.setRelatedId(summary.getId());
            resp.setGenerateStatus("1");

            int pageCount = 0;
            if (summary.getTotalPageCount() != null) {
                try {
                    pageCount = Integer.parseInt(summary.getTotalPageCount());
                } catch (NumberFormatException e) {
                    pageCount = 0;
                }
            }
            resp.setPageCount(pageCount);
            if (pageCount > 0) {
                resp.setPageRange(currentPage + "-" + (currentPage + pageCount - 1));
                currentPage += pageCount;
            } else {
                resp.setPageRange("—");
            }
            resultList.add(resp);
        }

        // 4. 案卷封底（不计入页码）
        ArchiveProofreadResp backCoverResp = new ArchiveProofreadResp();
        backCoverResp.setOrderNum(displayOrderNum);
        backCoverResp.setMaterialName("案卷封底（成本监审卷宗备考表）");
        backCoverResp.setDocumentType(3);
        backCoverResp.setCanGenerate("1");
        backCoverResp.setCanEdit("1");
        backCoverResp.setPageRange("—");
        if (backCoverSummary != null && backCoverSummary.getDetailList() != null && !backCoverSummary.getDetailList().isEmpty()) {
            CostProjectTaskMaterialSummaryDetail backCoverDetail = backCoverSummary.getDetailList().get(0);
            if (StringUtil.isNotEmpty(backCoverDetail.getAttachmentUrl())) {
                backCoverResp.setRelatedId(backCoverSummary.getId());
                backCoverResp.setAttachmentUrl(backCoverDetail.getAttachmentUrl());
                backCoverResp.setGenerateStatus("1");
            } else {
                backCoverResp.setRelatedId(backCoverSummary.getId());
                backCoverResp.setGenerateStatus("0");
            }
        } else {
            backCoverResp.setGenerateStatus("0");
        }
        resultList.add(backCoverResp);

        return CommonResult.<List<ArchiveProofreadResp>>ok().value(resultList);
    }

    /**
     * 保存卷宗文书（封面/目录/封底）
     * @param req 保存请求
     * @return 生成的文书URL
     */
    @PostMapping(value = "/saveArchiveDocument")
    @ApiOperation(value = "保存卷宗文书", httpMethod = "POST", notes = "保存案卷封面/卷内目录/案卷封底文书（新增和编辑统一接口）")
    @Transactional
    public CommonResult<String> saveArchiveDocument(
            @ApiParam(name = "req", value = "保存请求", required = true)
            @RequestBody ArchiveProofreadReq req)
    {

        if (StringUtil.isEmpty(req.getTaskId())) {
            return CommonResult.<String>error().message("任务ID不能为空");
        }
        // id为空是新增，必须传documentType；id不为空是编辑
        if (StringUtil.isEmpty(req.getRelatedId())) {
            if (req.getDocumentType() == null || req.getDocumentType() < 1 || req.getDocumentType() > 3) {
                return CommonResult.<String>error().message("新增时文书类型不能为空，请选择1-案卷封面、2-卷内目录、3-案卷封底");
            }
        }

        try {
            String documentUrl = asyncMaterialSummaryService.generateArchiveDocument(req);
            return CommonResult.<String>ok().value(documentUrl).message("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.<String>error().message("保存失败：" + e.getMessage());
        }
    }



    /**
     *  生成Word卷宗
     * @param req 请求参数（包含taskId）
     * @return
     */
    @PostMapping(value = "/approveArchive")
    @ApiOperation(value = "生成Word卷宗", httpMethod = "POST", notes = "档案校对通过后，异步生成Word卷宗")
    public CommonResult<String> approveArchive(
            @ApiParam(name = "req", value = "请求参数", required = true)
            @RequestBody Map<String, String> req)
    {
        String taskId = req.get("taskId");
        if (StringUtil.isEmpty(taskId)) {
            return CommonResult.<String>error().message("任务ID不能为空");
        }
        // 校验任务是否存在资料归纳数据（包含封面、目录、封底）
        List<CostProjectTaskMaterialSummary> summaryList = baseService.listAllByTaskId(taskId);
        if (summaryList == null || summaryList.isEmpty()) {
            return CommonResult.<String>error().message("该任务没有资料归纳数据，无法校对");
        }

        // 更新状态为"生成中"
        CostProjectTask task = costProjectTaskManager.getById(taskId);
        if (task != null) {
            task.setArchiveStatus("1");
            costProjectTaskManager.updateById(task);
        }
        // 异步生成Word卷宗
        asyncMaterialSummaryService.generateWordArchiveAsync(taskId);

        return CommonResult.<String>ok().message("档案校对通过，正在后台生成Word卷宗，请稍后查看");
    }

    /**
     * 查询Word卷宗生成状态
     * @param taskId 任务ID
     * @return 返回任务信息（包含archiveStatus、archiveUrl、archiveTime）
     */
    @GetMapping(value = "/getArchiveStatus")
    @ApiOperation(value = "查询Word卷宗生成状态", httpMethod = "GET", notes = "查询Word卷宗生成状态：0-未生成 1-生成中 2-已生成 3-生成失败")
    public CommonResult<CostProjectTask> getArchiveStatus(
            @ApiParam(name = "taskId", value = "任务ID", required = true)
            @RequestParam(required = true) String taskId)
    {
        CostProjectTask task = costProjectTaskManager.getById(taskId);
        if (task == null) {
            return CommonResult.<CostProjectTask>error().message("任务不存在");
        }
        return CommonResult.<CostProjectTask>ok().value(task).message("查询成功");
    }

    /**
     * 确定归档
     * @param req 请求参数（包含taskId）
     * @return
     */
    @PostMapping(value = "/confirmArchive")
    @ApiOperation(value = "确定归档", httpMethod = "POST", notes = "确定归档，更新任务归档状态")
    @Transactional
    public CommonResult<String> confirmArchive(
            @ApiParam(name = "req", value = "请求参数", required = true)
            @RequestBody Map<String, String> req)
    {
        String taskId = req.get("taskId");
        if (StringUtil.isEmpty(taskId)) {
            return CommonResult.<String>error().message("任务ID不能为空");
        }
        CostProjectTask task = costProjectTaskManager.getById(taskId);
        if (task == null) {
            return CommonResult.<String>error().message("任务不存在");
        }
        if (StringUtil.isEmpty(task.getArchiveUrl())) {
            return CommonResult.<String>error().message("请先生成卷宗文件");
        }
        task.setIsGd("1");
        task.setArchiveStatus("2");
        task.setArchiveTime(java.time.LocalDateTime.now());
        costProjectTaskManager.updateById(task);
        return CommonResult.<String>ok().message("归档成功");
    }
}

