package com.hotent.enterpriseDeclare.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.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import com.hotent.baseInfo.manager.AuditedUnitManager;
import com.hotent.baseInfo.model.AuditedUnit;
import com.hotent.enterpriseDeclare.req.CostAuditTaskPageReq;
import com.hotent.enterpriseDeclare.req.CostTaskPageReq;
import com.hotent.project.manager.CostProjectApprovalManager;
import com.hotent.project.manager.CostProjectTaskManager;
import com.hotent.project.model.*;
import com.hotent.project.resp.CostProjectApprovalDetailResp;
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.web.bind.annotation.*;

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

@Api(tags = "成本监审任务填报")
@RestController
@RequestMapping("/api/enterprise/castTask")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostAuditTaskController {

    @Autowired
    private AuditedUnitManager auditedUnitManager;

    @Autowired
    private CostProjectApprovalManager costProjectApprovalManager;

    @Autowired
    private CostProjectTaskManager costProjectTaskManager;


    /**
     * 分页查询当前用户企业需要填写的监审任务
     * @param req 分页查询请求参数
     * @return 已发布的任务分页列表
     */
    @PostMapping(value = "/pageList")
    @ApiOperation(value = "分页查询当前用户企业需要填写的监审任务", httpMethod = "POST", notes = "分页查询当前用户企业需要填写的监审任务")
    public CommonResult<IPage<CostProjectApproval>> pageList(@RequestBody CostAuditTaskPageReq req) {
        IPage<CostProjectApproval> pageResult = costProjectApprovalManager.pageListForAuditTask(req);
        return CommonResult.<IPage<CostProjectApproval>>ok().value(pageResult);
    }



    @GetMapping(value="/getDetail")
    @ApiOperation(value="任务立项详情",httpMethod = "GET",notes = "任务立项详情")
    public CommonResult<CostProjectApprovalDetailResp> getDetail(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam(required=true) String id) throws Exception{
        return CommonResult.<CostProjectApprovalDetailResp>ok().value(costProjectApprovalManager.getDetail(id));
    }


    @PostMapping(value="/save")
    @ApiOperation(value="提交任务填报",httpMethod = "POST",notes = "提交任务填报")
    public CommonResult<String> save(@RequestBody CostTaskPageReq costTaskPageReq) throws Exception{
        return CommonResult.<String>ok().value(costProjectTaskManager.saveTask(costTaskPageReq));
    }

    @PostMapping(value="/yjsave")
    @ApiOperation(value="意见反馈任务填报",httpMethod = "POST",notes = "意见反馈")
    public CommonResult<String> yjsave(@RequestBody CostProjectTaskPreliminaryOpinion costProjectTaskPreliminaryOpinion) throws Exception{
        return CommonResult.<String>ok().value(costProjectTaskManager.saveYjTask(costProjectTaskPreliminaryOpinion));
    }

    /**
     * 获取子任务的所有监审单位
     * @param taskId 主任务ID
     * @return 监审单位列表
     */
    @GetMapping(value = "/getChildTaskUnits")
    @ApiOperation(value = "获取子任务的所有监审单位", httpMethod = "GET", notes = "根据主任务ID查询所有子任务，获取子任务的监审单位字段，然后查询单位表返回所有单位")
    public CommonResult<List<AuditedUnit>> getChildTaskUnits(
            @ApiParam(name = "taskId", value = "主任务ID", required = true)
            @RequestParam(required = true) String taskId) {
        
        // 1. 查询该主任务下的所有子任务（pid等于主任务ID）
        LambdaQueryWrapper<CostProjectTask> taskQueryWrapper = new LambdaQueryWrapper<>();
        taskQueryWrapper.eq(CostProjectTask::getPid, taskId)
                .eq(CostProjectTask::getIsDeleted, "0")
                .isNotNull(CostProjectTask::getAuditedUnitId)
                .ne(CostProjectTask::getAuditedUnitId, "");
        
        List<CostProjectTask> childTasks = costProjectTaskManager.list(taskQueryWrapper);
        
        // 如果没有子任务，返回空列表
        if (childTasks == null || childTasks.isEmpty()) {
            return CommonResult.<List<AuditedUnit>>ok().value(java.util.Collections.emptyList());
        }
        
        // 2. 提取所有不重复的监审单位ID
        List<String> auditedUnitIds = childTasks.stream()
                .map(CostProjectTask::getAuditedUnitId)
                .filter(StringUtil::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());
        
        if (auditedUnitIds.isEmpty()) {
            return CommonResult.<List<AuditedUnit>>ok().value(java.util.Collections.emptyList());
        }
        
        // 3. 根据单位ID列表查询单位表
        LambdaQueryWrapper<AuditedUnit> unitQueryWrapper = new LambdaQueryWrapper<>();
        unitQueryWrapper.in(AuditedUnit::getUnitId, auditedUnitIds)
                .eq(AuditedUnit::getIsDeleted, "0");
        
        List<AuditedUnit> units = auditedUnitManager.list(unitQueryWrapper);
        
        return CommonResult.<List<AuditedUnit>>ok().value(units);
    }
}
