package com.hotent.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import com.hotent.baseInfo.req.CostTaskSearchReq;
import com.hotent.baseInfo.vo.CatalogTreeVo;
import com.hotent.baseInfo.vo.TaskTreeVo;
import com.hotent.project.manager.CostProjectSuperviseManager;
import com.hotent.project.manager.CostProjectTaskManager;
import com.hotent.project.manager.CostProjectTaskNodeManager;
import com.hotent.project.manager.CostProjectTaskProccessManager;
import com.hotent.project.model.*;
import com.hotent.project.req.CostProjectSuperviseReq;
import com.hotent.project.vo.CostProjectSuperviseDataVo;
import com.hotent.util.JsonUtil;
import com.hotent.util.treeutil.SumTree;
import com.hotent.util.treeutil.newtreeutil.TreeDotUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 *@author: zhao yue yue
 *@create: 2025-11-18 14:45
 */

@RestController
@Api(tags = "项目督办")
@RequestMapping("/cost/project/supervise/v1")
@ApiGroup(group = {ApiGroupConsts.GROUP_PROJECT})
public class CostProjectSuperviseController {

    @Autowired
    private CostProjectSuperviseManager costProjectSuperviseManager;

    @Autowired
    private CostProjectTaskManager costProjectTaskManager;
    @Autowired
    private CostProjectTaskProccessManager costProjectTaskProccessManager;
    @Autowired
    private CostProjectTaskNodeManager costProjectTaskNodeManager;



    @ApiOperation("创建（新增）督办任务")
    @RequestMapping(value = "/save", method = { RequestMethod.POST})
    public CommonResult<String> save (@RequestBody CostProjectSuperviseReq param) throws Exception {
        String msg= costProjectSuperviseManager.add(param);
        return CommonResult.<String>ok().message(msg);
    }

    @ApiOperation("修改（上报）督办内容")
    @RequestMapping(value = "/modify", method = { RequestMethod.POST})
    public CommonResult<String> modify (@RequestBody CostProjectSuperviseReq param) throws Exception {
        String msg= costProjectSuperviseManager.modify(param);
        return CommonResult.<String>ok().message(msg);
    }


    @ApiOperation("（删除）停止督办")
    @RequestMapping(value = "/delete", method = { RequestMethod.POST})
    public CommonResult<String> delete (@RequestBody CostProjectSuperviseReq param) throws Exception {
        String msg= costProjectSuperviseManager.delete(param);
        return CommonResult.<String>ok().message(msg);
    }

    @ApiOperation("查询督办报告")
    @RequestMapping(value = "/getReportList", method = { RequestMethod.POST})
    public CommonResult<List<CostProjectSuperviseDataVo>> getReportList (@RequestBody CostProjectSuperviseReq param) throws Exception {
        List<CostProjectSuperviseDataVo> reportList = costProjectSuperviseManager.getReportList(param);
        return CommonResult.<List<CostProjectSuperviseDataVo>>ok().value(reportList);
    }

    @ApiOperation("查询督办报告")
    @RequestMapping(value = "/getList", method = { RequestMethod.POST})
    public CommonResult<List<SumTree<TaskTreeVo>>> getList (@RequestBody CostTaskSearchReq req) throws Exception {
        List<CostProjectTask> taskList = costProjectTaskManager.getTaskList(req);
        List<TaskTreeVo> allList = JsonUtil.getJsonToList(taskList, TaskTreeVo.class);
        List<String> projectIds = allList.stream().map(TaskTreeVo::getProjectId).distinct().collect(Collectors.toList());
        List<CostProjectSupervise> supervises = costProjectSuperviseManager.getListByprojectIds(projectIds);
        for (int i = 0; i < taskList.size(); i++) {
            CostProjectTask task = taskList.get(i);
            TaskTreeVo taskTreeVo = allList.get(i);
            taskTreeVo.setId(task.getId());
            taskTreeVo.setParentId(task.getPid());
            taskTreeVo.setWarningStatus(calculateWarningStatus(task));
            CostProjectSupervise projectSupervise = supervises.stream().filter(s -> s.getProjectId().equals(taskTreeVo.getProjectId())&& StringUtil.isNotEmpty(taskTreeVo.getAuditType()) && taskTreeVo.getAuditType().equals("1")).findAny().orElse(null);
            if (projectSupervise!=null) {
                taskTreeVo.setSuperviseStatus(String.valueOf(projectSupervise.getStatus()));
                taskTreeVo.setSuperviseId(projectSupervise.getId());
            }
        }
        List<SumTree<TaskTreeVo>> trees = TreeDotUtils.convertListToTreeDotFilter(allList);
        CommonResult<List<SumTree<TaskTreeVo>>> result = CommonResult.ok();
        result.setValue(trees);
        return result;

    }


    /**
     * 计算任务预警状态
     * @param task 任务对象
     * @return 预警状态：green-绿色预警(在办理期限内) yellow-黄色预警(超过环节期限但没超过流程期限) red-红色预警(超过流程期限)
     */
    private String calculateWarningStatus(CostProjectTask task) {
        // 获取任务对应的流程信息
        CostProjectTaskProccess process = costProjectTaskProccessManager.getOne(
                new LambdaQueryWrapper<CostProjectTaskProccess>()
                        .eq(CostProjectTaskProccess::getTaskId, task.getId())
        );

        if (process == null) {
            return "green"; // 默认绿色预警
        }

        // 获取当前环节的节点信息
        CostProjectTaskNode currentNode = costProjectTaskNodeManager.getOne(
                new LambdaQueryWrapper<CostProjectTaskNode>()
                        .eq(CostProjectTaskNode::getTaskId, task.getId())
                        .eq(CostProjectTaskNode::getProcessNodeKey, task.getCurrentNode())
        );

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 1. 如果超过流程期限，红色预警
        if (process.getPlannedAuditEndDate() != null &&
                now.toLocalDate().isAfter(process.getPlannedAuditEndDate())) {
            return "red";
        }

        // 2. 如果当前环节有截止时间且已超过，但未超过流程期限，黄色预警
        if (currentNode != null && currentNode.getEndTime() != null &&
                now.isAfter(currentNode.getEndTime())) {
            // 检查是否超过流程期限
            if (process.getPlannedAuditEndDate() != null &&
                    now.toLocalDate().isAfter(process.getPlannedAuditEndDate())) {
                return "red"; // 超过流程期限，红色预警
            } else {
                return "yellow"; // 超过环节期限但未超过流程期限，黄色预警
            }
        }

        // 3. 默认绿色预警（在办理期限内）
        return "green";
    }
}
