package com.hotent.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.baseInfo.manager.AuditedUnitManager;
import com.hotent.baseInfo.model.CostCatalog;
import com.hotent.baseInfo.req.CostCatalogPageReq;
import com.hotent.baseInfo.req.CostTaskSearchReq;
import com.hotent.baseInfo.vo.CatalogTreeVo;
import com.hotent.baseInfo.vo.TaskTreeVo;
import com.hotent.common.CrudService;
import com.hotent.constant.NodeConstant;
import com.hotent.constant.TaskStatusConstant;
import com.hotent.enterpriseDeclare.req.CostTaskReviewPageReq;
import com.hotent.project.manager.CostProjectSuperviseManager;
import com.hotent.project.manager.CostProjectTaskNodeManager;
import com.hotent.project.manager.CostProjectTaskProccessManager;
import com.hotent.project.model.CostProjectSupervise;
import com.hotent.project.model.CostProjectTaskNode;
import com.hotent.project.model.CostProjectTaskProccess;
import com.hotent.util.JsonUtil;
import com.hotent.util.treeutil.SumTree;
import com.hotent.util.treeutil.newtreeutil.TreeDotUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RestController;
import com.hotent.base.controller.BaseController;
import com.hotent.project.model.CostProjectTask;
import com.hotent.project.manager.CostProjectTaskManager;

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

/**
 * 项目任务表 前端控制器
 *
 * @author 超级管理员
 * @company 山西清众科技股份有限公司
 * @since 2025-10-03
 */
@RestController
@RequestMapping("/api/costProjectTask/v1/")
@Api(tags = "项目任务表")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostProjectTaskController extends BaseController<CostProjectTaskManager, CostProjectTask> {

    @Autowired
    private CostProjectSuperviseManager costProjectSuperviseManager;
    @Autowired
    private CostProjectTaskNodeManager costProjectTaskNodeManager;

    @Autowired
    private CostProjectTaskProccessManager costProjectTaskProccessManager;
    /**
     * 根据id获取项目任务表数据详情
     *
     * @param id
     * @return
     * @throws Exception ModelAndView
     */
    @GetMapping(value = "/getDetail")
    @ApiOperation(value = "根据id获取项目任务表数据详情", httpMethod = "GET", notes = "根据id获取项目任务表数据详情")
    public CommonResult<CostProjectTask> getDetail(@ApiParam(name = "id", value = "业务对象主键", required = true) @RequestParam(required = true) String id) throws Exception {
        return CommonResult.<CostProjectTask>ok().value(baseService.getById(id));
    }

    /**
     * 新增,更新项目任务表
     *
     * @param costProjectTask
     * @return
     * @throws Exception
     * @throws
     */
    @PostMapping(value = "/save")
    @ApiOperation(value = "新增,更新项目任务表数据", httpMethod = "POST", notes = "新增,更新项目任务表数据")
    public CommonResult<String> save(@ApiParam(name = "CostProjectTask", value = "项目任务表对象", required = true) @RequestBody CostProjectTask costProjectTask) throws Exception {
        String msg = StringUtil.isEmpty(costProjectTask.getId()) ? "添加项目任务表成功" : "更新项目任务表成功";
        baseService.createOrUpdate(costProjectTask);
        return CommonResult.<String>ok().message(msg);
    }


    /**
     * 任务进度管理
     */
    @PostMapping("/taskList")
    @ApiOperation(value = "任务进度管理列表", notes = "任务进度管理列表")
    public  CommonResult<IPage<CostProjectTask>> getCatalogList(@RequestBody CostTaskReviewPageReq req) throws Exception {
        req.setNStatus(TaskStatusConstant.COMPLETED.getStatusCode());
        IPage<CostProjectTask> pageResult = baseService.pageListForReviewTask(req);
        return CommonResult.<IPage<CostProjectTask>>ok().value(pageResult);
    }


    /**
     * 任务查询统计
     */
    @PostMapping("/taskListStatistics")
    @ApiOperation(value = "任务进度管理列表", notes = "任务进度管理列表")
    public  CommonResult<IPage<CostProjectTask>> taskListStatistics(@RequestBody CostTaskReviewPageReq req) throws Exception {
        IPage<CostProjectTask> pageResult = baseService.pageListForReviewTask(req);
        return CommonResult.<IPage<CostProjectTask>>ok().value(pageResult);
    }

    /**
     * 统计在办和已结事项数量
     */
    @PostMapping(value = "/itemsCount")
    @ApiOperation(value = "统计在办和已结事项数量", httpMethod = "POST", notes = "统计在办和已结事项数量")
    public CommonResult<Map<String, Integer>> itemsCount() throws Exception {
        List<CostProjectTask> taskList = baseService.getTaskList(null);

        // 统计在办和已结事项数量
        int pendingCount = 0;
        int completedCount = 0;

        for (CostProjectTask task : taskList) {
            if (TaskStatusConstant.COMPLETED.getStatusCode().equals(task.getStatus())) {
                completedCount++;
            } else {
                pendingCount++;
            }
        }

        Map<String, Integer> result = new java.util.HashMap<>();
        result.put("pendingCount", pendingCount);
        result.put("completedCount", completedCount);

        return CommonResult.<java.util.Map<String, Integer>>ok().value(result);
    }


    /**
     * 督办事项管理
     */
    @PostMapping("/supervisorList")
    @ApiOperation(value = "督办事项管理列表", notes = "督办事项管理列表")
    public CommonResult<List<SumTree<TaskTreeVo>>> supervisorList(@RequestBody CostTaskSearchReq req) throws Exception {
        List<CostProjectTask> taskList = baseService.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";
    }
}
