package com.hotent.project.manager.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotent.base.exception.BaseException;
import com.hotent.base.query.PageList;
import com.hotent.base.util.AuthenticationUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.baseInfo.manager.*;
import com.hotent.baseInfo.model.*;
import com.hotent.constant.BaseConstant;
import com.hotent.constant.NodeConstant;
import com.hotent.constant.TaskStatusConstant;
import com.hotent.enterpriseDeclare.req.CostAuditTaskPageReq;
import com.hotent.project.manager.*;
import com.hotent.project.model.*;
import com.hotent.project.dao.CostProjectApprovalDao;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.project.req.CostProjectApprovalPageReq;
import com.hotent.project.req.CostProjectApprovalPublishReq;
import com.hotent.project.resp.CostProjectApprovalDetailResp;
import com.hotent.surveyinfo.manager.*;
import com.hotent.surveyinfo.model.*;
import com.hotent.sys.persistence.manager.DataDictManager;
import com.hotent.sys.persistence.model.DataDict;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.manager.OrgManager;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.model.Org;
import com.hotent.uc.model.User;
import com.hotent.uc.util.ContextUtil;
import com.hotent.util.AreaCodeUtil;
import com.hotent.util.CopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.hotent.base.util.AuthenticationUtil.getCurrentUserMainOrgId;


/**
 * 成本监审立项主表 服务实现类
 *
 * @author 超级管理员
 * @company 山西清众科技股份有限公司
 * @since 2025-09-22
 */
@Service
public class CostProjectApprovalManagerImpl extends BaseManagerImpl<CostProjectApprovalDao, CostProjectApproval> implements CostProjectApprovalManager {


    @Autowired
    private OrgManager orgManager;

    @Autowired
    private AuditedUnitManager auditedUnitManager;


    @Autowired
    private CostNoticeManager costNoticeManager;


    @Autowired
    private CostProjectTaskManager costProjectTaskManager;


    @Autowired
    private CostProjectTaskApprovalManager costProjectTaskApprovalManager;


    @Autowired
    private CostProjectTaskDocumentManager costProjectTaskDocumentManager;


    @Autowired
    private CostProjectMaterialManager costProjectMaterialManager;

    @Autowired
    private CostProjectTaskMaterialManager costProjectTaskMaterialManager;


    @Autowired
    private CostProjectDocumentManager costProjectDocumentManager;


    @Autowired
    private CostProjectProccessManager costProjectProccessManager;
    @Autowired
    private CostProjectTaskProccessManager costProjectTaskProccessManager;

    @Autowired
    private CostProjectTaskNodeManager costProjectTaskNodeManager;

    @Autowired
    private CostProjectProccessNodeManager costProjectProccessNodeManager;


    @Autowired
    private CostProjectTaskPersonnelManager costProjectTaskPersonnelManager;

    @Autowired
    private CostProjectProccessPersonnelManager costProjectProccessPersonnelManager;


    @Autowired
    private CostCatalogManager costCatalogManager;

    @Autowired
    private CostCatalogUnitManager costCatalogUnitManager;

    @Autowired
    private CostCatalogInformationManager costCatalogInformationManager;


    @Autowired
    private CostProjectScenarioManager costProjectScenarioManager;

    @Autowired
    private CostProjectSurveyManager costProjectSurveyManager;


    @Autowired
    private CostSurveyFdTemplateManager costSurveyFdTemplateManager;


    @Autowired
    private CostSurveyFdTemplateHeadersManager costSurveyFdTemplateHeadersManager;


    @Autowired
    private CostSurveyFdTemplateItemsManager costSurveyFdTemplateItemsManager;


    @Autowired
    private CostSurveyTemplateManager costSurveyTemplateManager;


    @Autowired
    private CostSurveyTemplateHeadersManager costSurveyTemplateHeadersManager;

    @Autowired
    private CostSurveyTemplateItemsManager costSurveyTemplateItemsManager;

    @Autowired
    private CostDistrictManager costDistrictManager;

    /**
     * cost_survey_fd_project_data
     * cost_survey_fd_project_headers
     * cost_survey_fd_project_template
     * cost_survey_project_data
     * cost_survey_project_headers
     * cost_survey_project_template
     * cost_verify_project_data
     * cost_verify_project_headers
     * cost_verify_project_template
     * @param id
     * @return
     */
    @Autowired
    private CostSurveyFdProjectDataManager costSurveyFdProjectDataManager;

    @Autowired
    private CostSurveyFdProjectHeadersManager costSurveyFdProjectHeadersManager;

    @Autowired
    private CostSurveyFdProjectTemplateManager costSurveyFdProjectTemplateManager;

    @Autowired
    private CostSurveyProjectDataManager costSurveyProjectDataManager;

    @Autowired
    private CostSurveyProjectHeadersManager costSurveyProjectHeadersManager;

    @Autowired
    private CostSurveyProjectTemplateManager costSurveyProjectTemplateManager;

    @Autowired
    private CostVerifyProjectDataManager costVerifyProjectDataManager;

    @Autowired
    private CostVerifyProjectHeadersManager costVerifyProjectHeadersManager;

    @Autowired
    private CostVerifyProjectTemplateManager costVerifyProjectTemplateManager;


    @Autowired
    private UserManager userManager;

    @Resource
    DataDictManager dataDictManager;

    @Autowired
    UserManager userService;


    @Override
    public CostProjectApprovalDetailResp getDetail(String id) {
        CostProjectApproval costProjectApproval = this.get(id);
        CostCatalog costCatalog = costCatalogManager.get(costProjectApproval.getCatalogId());
        CostProjectApprovalDetailResp detailResp = CopyUtil.copy(costProjectApproval, CostProjectApprovalDetailResp.class);
        if (costCatalog!=null) {
            detailResp.setCatalogName(costCatalog.getCatalogName());
        }

        QueryWrapper<DataDict> wrapper = new QueryWrapper<>();
        wrapper.eq("TYPE_ID_","1977230176815185920");
        wrapper.eq("KEY_",costProjectApproval.getSourceType());
        DataDict  costDictDatas= dataDictManager.getOne(wrapper);
        if (costDictDatas!=null) {
            detailResp.setSourceName(costDictDatas.getName());
        }
        //单位级别：0:省/自治区/直辖市 1:市级 2:县级
        if (ObjectUtil.isNotEmpty(costProjectApproval.getAreaCode()) && ObjectUtil.isNotEmpty(costProjectApproval.getAreaLevel())) {
            //如果是区县级
            if (BaseConstant.REGION_LEVEL_COUNTY.equals(costProjectApproval.getAreaLevel())) {
                String cityCode = AreaCodeUtil.getCityCode(costProjectApproval.getAreaCode());
                String provinceCode = AreaCodeUtil.getProvinceCode(cityCode);
                detailResp.setCity(cityCode);
                detailResp.setProvince(provinceCode);
                detailResp.setCounty(costProjectApproval.getAreaCode());
            } else if (BaseConstant.REGION_LEVEL_CITY.equals(costProjectApproval.getAreaLevel())) {
                String provinceCode = AreaCodeUtil.getProvinceCode(costProjectApproval.getAreaCode());
                detailResp.setProvince(provinceCode);
                detailResp.setCity(costProjectApproval.getAreaCode());
            } else if (BaseConstant.REGION_LEVEL_PROVINCE.equals(costProjectApproval.getAreaLevel())) {
                detailResp.setProvince(costProjectApproval.getAreaCode());
            } else {
                detailResp.setProvince("未知编码");
            }
        }

        if (ObjectUtil.isNotEmpty(costProjectApproval.getAuditedUnitId())) {
            String[] split = costProjectApproval.getAuditedUnitId().split(",");
            List<AuditedUnit> auditedUnits = auditedUnitManager.listByIds(Arrays.asList(split));
            detailResp.setAuditUnitName(auditedUnits.stream().map(AuditedUnit::getUnitName).collect(Collectors.joining(",")));
        }

        if (ObjectUtil.isNotEmpty(costProjectApproval.getOrgId())) {
            detailResp.setOrgName(orgManager.get(costProjectApproval.getOrgId()).getName());
        }

        // 反查负责人名称
        if (ObjectUtil.isNotEmpty(costProjectApproval.getLeaderId())) {
            try {
                com.hotent.uc.model.User user = userManager.get(costProjectApproval.getLeaderId());
                if (ObjectUtil.isNotEmpty(user)) {
                    detailResp.setLeaderName(user.getFullname());
                }
            } catch (Exception e) {
                // 记录异常但不影响主流程
            }
        }

        // 反查项目组成员名称
        if (ObjectUtil.isNotEmpty(costProjectApproval.getProjectMembers())) {
            try {
                String[] memberIds = costProjectApproval.getProjectMembers().split(",");
                if (memberIds.length > 0) {
                    StringBuilder memberNames = new StringBuilder();
                    for (int i = 0; i < memberIds.length; i++) {
                        String memberId = memberIds[i].trim();
                        if (StringUtil.isNotEmpty(memberId)) {
                            com.hotent.uc.model.User user = userManager.get(memberId);
                            if (ObjectUtil.isNotEmpty(user)) {
                                if (i > 0) {
                                    memberNames.append(",");
                                }
                                memberNames.append(user.getFullname());
                            }
                        }
                    }
                    detailResp.setProjectMembersName(memberNames.toString());
                }
            } catch (Exception e) {
                // 记录异常但不影响主流程
            }
        }

        CostProjectTaskProccess taskProccess = costProjectTaskProccessManager.getOne(
                new QueryWrapper<CostProjectTaskProccess>().eq("project_id", costProjectApproval.getProjectId())
                        .last("limit 1")
        );
        if (taskProccess !=null ) {
            detailResp.setPlannedAuditStartDate(taskProccess.getPlannedAuditStartDate());
            detailResp.setPlannedAuditEndDate(taskProccess.getPlannedAuditEndDate());
        }
        return detailResp;

    }

    @Override
    @Transactional
    public void createOrUpdate(CostProjectApproval costProjectApproval) {
        //新建或更新
        this.saveOrUpdate(costProjectApproval);
    }

    //新增
    @Override
    public boolean save(CostProjectApproval costProjectApproval) {
        costProjectApproval.setIsDeleted(BaseConstant.NORMAL_STATUS);
        costProjectApproval.setCreateBy(ContextUtil.getCurrentUser().getAccount());
        costProjectApproval.setCreateTime(LocalDateTime.now());
        costProjectApproval.setAreaLevel(AreaCodeUtil.getAreaLevel(costProjectApproval.getAreaCode()).getLevel().getDescription());

        CostCatalog costCatalog = costCatalogManager.get(costProjectApproval.getCatalogId());
        if (costCatalog == null) {
            throw new BaseException("请选择成本目录");
        }
        super.save(costProjectApproval);
        //报送资料
        List<CostCatalogUnit> catalogUnitList = costCatalogUnitManager.getListByCatalogId(costProjectApproval.getCatalogId());

        List<CostProjectMaterial> materialList = CopyUtil.copyList(catalogUnitList, CostProjectMaterial.class);
        materialList.forEach(material -> {
            material.setId(null);
            material.setProjectId(costProjectApproval.getProjectId());
        });
        this.costProjectMaterialManager.saveBatch(materialList);

        return true;
    }

    //修改
    @Override
    @Transactional
    public boolean updateById(CostProjectApproval costProjectApproval) {
        if (StringUtil.isEmpty(costProjectApproval.getProjectId())) {
            throw new BaseException("请选择要修改的记录");
        }
        costProjectApproval.setUpdateBy(ContextUtil.getCurrentUser().getAccount());
        costProjectApproval.setUpdateTime(LocalDateTime.now());
        costProjectApproval.setAreaLevel(AreaCodeUtil.getAreaLevel(costProjectApproval.getAreaCode()).getLevel().getDescription());
        return super.updateById(costProjectApproval);
    }


    @Override
    public PageList<CostProjectApproval> pageList(CostProjectApprovalPageReq req) throws Exception {
        /*LambdaQueryWrapper<CostProjectApproval> qw = new LambdaQueryWrapper<>();
        qw.eq(CostProjectApproval::getIsDeleted, BaseConstant.NORMAL_STATUS);
        if (StringUtil.isNotEmpty(req.getProjectName())) {
            qw.like(CostProjectApproval::getProjectName, req.getProjectName());
        }
        if (StringUtil.isNotEmpty(req.getProjectYear())) {
            qw.eq(CostProjectApproval::getProjectYear, req.getProjectYear());
        }
        if (StringUtil.isNotEmpty(req.getAreaCode())) {
            qw.eq(CostProjectApproval::getAreaCode, req.getAreaCode());
        }
        IPage<CostProjectApproval> page = new Page<>(req.getPageNum(), req.getPageSize());
        return this.page(page, qw);*/

        IUser iUser = ContextUtil.getCurrentUser();
        User user = userService.getByAccount(iUser.getAccount());
        req.setDataScope(user.getDataScope());
        req.setProvinceCode(user.getProvinceCode());
        req.setCityCode(user.getCityCode());
        req.setCountyCode(user.getCountyCode());
        Page<CostProjectApproval> objectPage = new Page<>(req.getPage(),req.getPageSize());
        //Page<CostSurveyTemplate> page =baseMapper.getCostSurveyTemplatePage(objectPage,params);
        Page<CostProjectApproval> page =baseMapper.getCostProjectApprovalPage(objectPage
                ,req.getDataScope()
                ,req.getProvinceCode(),req.getCityCode()
                ,req.getCountyCode()
                ,req.getProjectYear()
                ,req.getAreaCode()
                ,req.getProjectName());
        return new PageList<>(page);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publish(CostProjectApprovalPublishReq req) {
        CostProjectApproval costProjectApproval = this.get(req.getProjectId());
        if (costProjectApproval == null) {
            throw new BaseException("项目不存在");
        }

        if ("2".equals(costProjectApproval.getStatus())) {
            throw new BaseException("项目已发布");
        }

        LambdaUpdateWrapper<CostProjectApproval> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CostProjectApproval::getStatus, "2");
        updateWrapper.set(CostProjectApproval::getAuditGroup, req.getAuditGroup());
        updateWrapper.set(CostProjectApproval::getSendType, req.getSendType());
        updateWrapper.eq(CostProjectApproval::getProjectId, req.getProjectId());
        this.update(updateWrapper);

        //任务创建
        CostProjectTask costProjectTask = new CostProjectTask();
        costProjectTask.setProjectId(costProjectApproval.getProjectId());
        costProjectTask.setProjectName(costProjectApproval.getProjectName());
        costProjectTask.setAuditedUnitId(costProjectApproval.getAuditedUnitId());
        costProjectTask.setAuditPeriod(costProjectApproval.getAuditPeriod());
        costProjectTask.setSourceType(costProjectApproval.getSourceType());
        costProjectTask.setAuditType(costProjectApproval.getAuditType());
        costProjectTask.setCurrentNode(NodeConstant.tjcl.getNodeKey());
        costProjectTask.setStatus(TaskStatusConstant.WAIT_SUBMIT.getStatusCode());
        costProjectTask.setOrderNum(1);
        costProjectTask.setIsDeleted(BaseConstant.NORMAL_STATUS);
        costProjectTask.setYear(costProjectApproval.getProjectYear());
        costProjectTask.setPid("0");
        this.costProjectTaskManager.save(costProjectTask);

        //文书集合
        List<CostProjectDocument> documentList = this.costProjectDocumentManager.getListByProjectId(costProjectApproval.getProjectId());
        //资料集合
        List<CostProjectMaterial> materialList = this.costProjectMaterialManager.getListByProjectId(costProjectApproval.getProjectId());
        //流程对象
        CostProjectProccess projectProccess = costProjectProccessManager.getProcessByProjectId(costProjectApproval.getProjectId());
        //节点集合
        List<CostProjectProccessNode> proccessNodeList = costProjectProccessNodeManager.getListByProcessId(projectProccess.getProcessId());

        //政策文件、监审对象提交资料清单、成本调查表
        //监审目录id
        String catalogId = costProjectApproval.getCatalogId();

        //TODO 根据监审目录id查询关联的成本调查表、财务表
        //财务表
        List<CostSurveyFdTemplate> costSurveyFdTemplates = costSurveyFdTemplateManager.listByCatalogId(catalogId);

//        if (ObjectUtil.isNotEmpty(costSurveyFdTemplates)) {
//            if (costSurveyFdTemplates.size() == 1) {
//                CostSurveyFdTemplate costSurveyFdTemplate = costSurveyFdTemplates.get(0);
//                List<CostSurveyFdTemplateHeaders> costSurveyFdTemplateHeaders = this.costSurveyFdTemplateHeadersManager.listBySurveyTemplateId(costSurveyFdTemplate.getSurveyTemplateId());
//                List<CostSurveyFdTemplateItems> costSurveyFdTemplateItems = this.costSurveyFdTemplateItemsManager.selectBySurveyTemplateId(costSurveyFdTemplate.getSurveyTemplateId());
//
//            } else {
//                throw new BaseException("财务表关系为一对一");
//            }
//        }


        //成本表
        List<CostSurveyTemplate> costSurveyTemplates = costSurveyTemplateManager.listByCatalogId(catalogId);

        if (ObjectUtil.isNotEmpty(costSurveyTemplates)) {
            List<String> surveyTemplateIdList = costSurveyTemplates.stream().map(CostSurveyTemplate::getSurveyTemplateId).collect(Collectors.toList());
            LambdaQueryWrapper<CostSurveyTemplateHeaders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(CostSurveyTemplateHeaders::getSurveyTemplateId, surveyTemplateIdList);
            List<CostSurveyTemplateHeaders> headersList = this.costSurveyTemplateHeadersManager.list(queryWrapper);


            LambdaQueryWrapper<CostSurveyTemplateItems> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.in(CostSurveyTemplateItems::getSurveyTemplateId, surveyTemplateIdList);
            List<CostSurveyTemplateItems> itemsList = this.costSurveyTemplateItemsManager.list(queryWrapper1);


        }

        //核定表


        List<CostProjectTask> childList = new ArrayList<>();
        StringBuilder auditUnitName = new StringBuilder();

        // 统一处理 auditedUnitId，无论单个还是多个
        String[] unitIdList = costProjectTask.getAuditedUnitId().split(",");

        int orderNum = 1;
        for (String unitId : unitIdList) {
            // 创建子任务
            CostProjectTask childTask = new CostProjectTask();
            childTask.setProjectId(costProjectApproval.getProjectId());
            childTask.setProjectName(costProjectApproval.getProjectName() + "-子任务");
            childTask.setAuditedUnitId(unitId);
            childTask.setAuditedUnitName(auditedUnitManager.get(unitId).getUnitName());
            childTask.setCurrentNode(NodeConstant.tjcl.getNodeKey());
            childTask.setStatus(TaskStatusConstant.WAIT_SUBMIT.getStatusCode());
            childTask.setOrderNum(orderNum++);
            childTask.setPid(costProjectTask.getId());
            childTask.setIsDeleted(BaseConstant.NORMAL_STATUS);
            childTask.setYear(costProjectApproval.getProjectYear());

            childList.add(childTask);
            auditUnitName.append(childTask.getAuditedUnitName()).append(",");
        }

        // 保存所有子任务
        this.costProjectTaskManager.saveBatch(childList);

        // 给每个子任务对应的企业发送任务通知（绑定taskId）
        for (CostProjectTask childTask : childList) {
            // 查询企业对应的账号（用户ID）
            AuditedUnit auditedUnit = auditedUnitManager.getOne(
                new LambdaQueryWrapper<AuditedUnit>()
                    .eq(AuditedUnit::getUnitId, childTask.getAuditedUnitId())
                    .eq(AuditedUnit::getIsDeleted, "0")
            );
            String sendTarget = childTask.getCreateBy() == null ? "" : childTask.getCreateBy();

            String title = "监审任务发布通知";
            String content = "您有新的监审任务：" + costProjectApproval.getProjectName();
            if (StringUtil.isNotEmpty(req.getContent())) {
                content += "，" + req.getContent();
            }
            String orgId = getCurrentUserMainOrgId();
            Org org = orgManager.getById(orgId);
            String noticeSource = (org != null ? org.getName() : "系统") + " " + AuthenticationUtil.getCurrentUserFullname();
            // 站内通知（绑定子任务ID）
            this.costNoticeManager.sendNotice(
                    req.getProjectId(),
                    childTask.getId(),
                    "1",
                    title,
                    content,
                    childTask.getAuditedUnitId(),
                    noticeSource,
                    sendTarget
            );

        }

        // 设置父任务的审计单位名称
        if (auditUnitName.length() > 0) {
            costProjectTask.setAuditedUnitName(
                    auditUnitName.substring(0, auditUnitName.length() - 1)
            );
        }

        // 在子任务保存后创建关联数据
        List<CostProjectTaskDocument> taskDocumentList = new ArrayList<>();
        List<CostProjectTaskApproval> taskApprovals = new ArrayList<>();
        List<CostProjectTaskMaterial> taskMaterialList = new ArrayList<>();
        List<CostProjectTaskProccess> taskProccessList = new ArrayList<>();
        List<CostProjectTaskNode> taskNodeList = new ArrayList<>();
        List<CostProjectTaskPersonnel> taskPersonnelList = new ArrayList<>();

        for (CostProjectTask childTask : childList) {
            // 立项任务
            CostProjectTaskApproval taskApproval = CopyUtil.copy(costProjectApproval, CostProjectTaskApproval.class);
            taskApproval.setAuditedUnitId(childTask.getAuditedUnitId());
            taskApproval.setTaskId(childTask.getId());
            taskApprovals.add(taskApproval);

            // 关联文书
            List<CostProjectTaskDocument> documents = CopyUtil.copyList(documentList, CostProjectTaskDocument.class);
            documents.forEach(doc ->{
                doc.setTaskId(childTask.getId());
                doc.setId(null);
            } );
            taskDocumentList.addAll(documents);

            // 关联资料
            List<CostProjectTaskMaterial> materials = CopyUtil.copyList(materialList, CostProjectTaskMaterial.class);
            materials.forEach(mat ->{
                mat.setTaskId(childTask.getId());
                mat.setId(null);
            } );
            taskMaterialList.addAll(materials);

            // 关联成本调查表


            // 工作流程
            CostProjectTaskProccess process = CopyUtil.copy(projectProccess, CostProjectTaskProccess.class);
            process.setTaskId(childTask.getId());
            process.setProcessId(null);
            taskProccessList.add(process);


            // 流程节点
            List<CostProjectTaskNode> nodes = CopyUtil.copyList(proccessNodeList, CostProjectTaskNode.class);
            nodes.forEach(node -> {
                node.setTaskId(childTask.getId());
                node.setId(null);
            });
            taskNodeList.addAll(nodes);

        }

        // 保存所有关联数据
        this.costProjectTaskApprovalManager.saveBatch(taskApprovals);
        this.costProjectTaskDocumentManager.saveBatch(taskDocumentList);
        this.costProjectTaskMaterialManager.saveBatch(taskMaterialList);
        this.costProjectTaskProccessManager.saveBatch(taskProccessList);
        this.costProjectTaskNodeManager.saveBatch(taskNodeList);
        this.costProjectTaskPersonnelManager.saveBatch(taskPersonnelList);

        //更新监审单位名称
        this.costProjectTaskManager.updateById(costProjectTask);
    }

    @Override
    public IPage<CostProjectApproval> pageListForAuditTask(CostAuditTaskPageReq req) {
        // 获取当前用户
        IUser currentUser = ContextUtil.getCurrentUser();
        AuditedUnit unit = auditedUnitManager.getOne(
                new LambdaQueryWrapper<AuditedUnit>()
                        .eq(AuditedUnit::getAccount, currentUser.getUserId())
                        .eq(AuditedUnit::getIsDeleted, "0")
        );
        if (unit == null){
            return new Page<>();
        }

        // 构建查询条件
        LambdaQueryWrapper<CostProjectApproval> queryWrapper = new LambdaQueryWrapper<>();

        // 查询已发布状态的任务
        queryWrapper.eq(CostProjectApproval::getStatus, "2");

        // 查询未删除的记录
        queryWrapper.eq(CostProjectApproval::getIsDeleted, "0");

        // 查询包含当前用户企业ID的记录
        queryWrapper.like(CostProjectApproval::getAuditedUnitId, unit.getUnitId());

        // 根据请求参数添加查询条件
        if (StringUtil.isNotEmpty(req.getProjectName())) {
            queryWrapper.like(CostProjectApproval::getProjectName, req.getProjectName());
        }
        if (StringUtil.isNotEmpty(req.getAreaCode())) {
            queryWrapper.eq(CostProjectApproval::getAreaCode, req.getAreaCode());
        }
        if (StringUtil.isNotEmpty(req.getProjectYear())) {
            queryWrapper.eq(CostProjectApproval::getProjectYear, req.getProjectYear());
        }
        if (StringUtil.isNotEmpty(req.getAuditType())) {
            queryWrapper.eq(CostProjectApproval::getAuditType, req.getAuditType());
        }

        // 按创建时间倒序排列
        queryWrapper.orderByDesc(CostProjectApproval::getCreateTime);

        // 创建分页对象并执行查询
        Page<CostProjectApproval> page = new Page<>(req.getPageNum(), req.getPageSize());

        IPage<CostProjectApproval> result = this.page(page, queryWrapper);

        // 填充orgName和areaName
        List<CostProjectApproval> records = result.getRecords();
        for (CostProjectApproval record : records) {
            // 设置监审主体
            if (StringUtil.isNotEmpty(record.getOrgId())) {
                String[] orgIds = record.getOrgId().split(",");
                StringBuilder orgNames = new StringBuilder();
                for (int i = 0; i < orgIds.length; i++) {
                    String orgId = orgIds[i].trim();
                    if (StringUtil.isNotEmpty(orgId)) {
                        if (i > 0) {
                            orgNames.append(",");
                        }
                        orgNames.append(orgManager.get(orgId).getName());
                    }
                }
                record.setOrgName(orgNames.toString());
            }

            // 设置立项地区
            if (StringUtil.isNotEmpty(record.getAreaCode())) {
                CostDistrict district = costDistrictManager.getOne(
                        new LambdaQueryWrapper<CostDistrict>()
                                .eq(CostDistrict::getCode, record.getAreaCode())
                );
                record.setAreaName(district != null ? district.getName() : "山西省");
            }

            // 查询当前用户对应的子任务
            CostProjectTask userTask = costProjectTaskManager.getOne(
                    new LambdaQueryWrapper<CostProjectTask>()
                            .eq(CostProjectTask::getProjectId, record.getProjectId())
                            .ne(CostProjectTask::getPid,0)
                            .eq(CostProjectTask::getAuditedUnitId, unit.getUnitId())
                            .eq(CostProjectTask::getIsDeleted, 0)
            );


            if(userTask!=null) {
                // 设置子任务对象
                record.setUserTask(userTask);
                // 设置主状态为子任务状态
                record.setStatus(userTask.getStatus());
                record.setStatusName(TaskStatusConstant.getStatusNameByCode(userTask.getStatus()));
                record.setCurrentNode(userTask.getCurrentNode());
                record.setCurrentNodeName(NodeConstant.getNodeValueByKey(userTask.getCurrentNode()) + "-" + TaskStatusConstant.getStatusNameByCode(userTask.getStatus()));
            }

            //设置监审单位
            record.setAuditedUnitId(unit.getUnitId());
            record.setAuditedUnitName(unit.getUnitName());
        }
        return result;
    }

    @Override
    public List<CostProjectApproval> getList() {
        User currentUser = ContextUtil.getCurrentUser();
        String userId = currentUser.getId();
        User user = userService.getById(userId);
        Integer dataScope = user.getDataScope();

        QueryWrapper<CostProjectApproval> queryWrapper = new QueryWrapper<>();
        // 只能查自己和自己下属的
        if(dataScope != null && dataScope != 0){
            Set<String> areaSet = new HashSet<>();
            if(dataScope == 1){
                String cityCode = user.getCityCode();
                String codeSub = cityCode.substring(0, 4);
                QueryWrapper<CostDistrict> districtQueryWrapper = new QueryWrapper<>();
                districtQueryWrapper.like("code", codeSub);
                List<CostDistrict> costDistricts = costDistrictManager.list(districtQueryWrapper);
                for (CostDistrict costDistrict1 : costDistricts) {
                    areaSet.add(costDistrict1.getCode());
                }
            }
            if(dataScope == 2){
                String code = user.getCountyCode();
                areaSet.add(code);
            }
            queryWrapper.in("area_code", areaSet);
        }
        queryWrapper.orderByDesc("create_time");
        return this.list(queryWrapper);
    }

    @Override
    public List<CostProjectApproval> getAnalyzeList() {
        User currentUser = ContextUtil.getCurrentUser();
        String userId = currentUser.getId();
        User user = userService.getById(userId);
        Integer dataScope = user.getDataScope();
        QueryWrapper<CostProjectTask> wrapperTask = new QueryWrapper<>();
        wrapperTask.eq("is_gd",1);
        List<CostProjectTask> list = costProjectTaskManager.list(wrapperTask);
        List<String> projectIds = list.stream().map(CostProjectTask::getProjectId).distinct().collect(Collectors.toList());

        QueryWrapper<CostProjectApproval> queryWrapper = new QueryWrapper<>();
        // 只能查自己和自己下属的
        if(dataScope != null && dataScope != 0){
            Set<String> areaSet = new HashSet<>();
            if(dataScope == 1){
                String cityCode = user.getCityCode();
                String codeSub = cityCode.substring(0, 4);
                QueryWrapper<CostDistrict> districtQueryWrapper = new QueryWrapper<>();
                districtQueryWrapper.like("code", codeSub);
                List<CostDistrict> costDistricts = costDistrictManager.list(districtQueryWrapper);
                for (CostDistrict costDistrict1 : costDistricts) {
                    areaSet.add(costDistrict1.getCode());
                }
            }
            if(dataScope == 2){
                String code = user.getCountyCode();
                areaSet.add(code);
            }
            queryWrapper.in("area_code", areaSet);
        }
        queryWrapper.in("project_id",projectIds);
        queryWrapper.orderByDesc("create_time");
        return this.list(queryWrapper);
    }

}
