package com.jeeplus.finance.reportCancellApplyArchived.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.common.constant.CacheNames;
import com.jeeplus.common.redis.RedisUtils;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.finance.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.finance.projectReport.domain.CwProjectInfoData;
import com.jeeplus.finance.projectReport.domain.CwProjectReport;
import com.jeeplus.finance.projectReport.mapper.CwProjectInfoMapper;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportMapper;
import com.jeeplus.finance.reportCancellApply.domain.ReportCancellApply;
import com.jeeplus.finance.reportCancellApply.mapper.ReportCancellApplyMapper;
import com.jeeplus.finance.reportCancellApplyArchived.domain.CwProjectReportApplyArchive;
import com.jeeplus.finance.reportCancellApplyArchived.mapper.ReportCancellApplyArchivedMapper;
import com.jeeplus.finance.reportCancellApplyArchived.service.dto.ApplyArchiveReportDTO;
import com.jeeplus.finance.reportCancellApplyArchived.service.dto.ArchivedReportInfoDto;
import com.jeeplus.finance.reportCancellApplyArchived.service.dto.CwWorkAttachmentArchiveDto;
import com.jeeplus.flowable.feign.IFlowableApi;
//import com.jeeplus.pubmodules.oss.domain.WorkAttachment;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
//import com.jeeplus.pubmodules.oss.service.OssService;
//import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IRoleApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: 王强
 * @create: 2022-11-18 17:36
 **/
@Service
@Transactional
public class ReportCancellApplyArchivedService extends ServiceImpl<ReportCancellApplyArchivedMapper, CwProjectReportApplyArchive> {

    @Resource
    private ReportCancellApplyArchivedMapper applyMapper;

//    @Resource
//    private SerialnumTplService serialnumTplService;

//    @Resource
//    private OssServiceMapper ossServiceMapper;

    @Resource
    private ReportCancellApplyMapper cancellApplyMapper;

    @Resource
    private CwProjectInfoMapper infoMapper;

    @Resource
    private CwProjectReportMapper reportMapper;

//    @Resource
//    private OssService ossService;

    @Resource
    private IFlowableApi flowTaskService;


    /**
     * 差选项目列表信息
     *
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<ArchivedReportInfoDto> getList(Page<ArchivedReportInfoDto> page, ArchivedReportInfoDto projectReportData) throws Exception {
        QueryWrapper<ArchivedReportInfoDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(projectReportData, ArchivedReportInfoDto.class);
        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.eq("a.status", "5");
        //条件
        if (StringUtils.isNotEmpty(projectReportData.getProjectNumber())) {
            queryWrapper.like("d.project_number", projectReportData.getProjectNumber());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectName())) {
            queryWrapper.like("d.project_name", projectReportData.getProjectName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterId())) {
            queryWrapper.eq("d.project_master_id", projectReportData.getProjectMasterId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Id())) {
            queryWrapper.eq("d.real_header", projectReportData.getProjectMaster2Id());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterName())) { // 项目经理1筛选
            queryWrapper.like("g.id", projectReportData.getProjectMasterName()).or().like("g.name", projectReportData.getProjectMasterName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Name())) { // 项目经理2筛选
            queryWrapper.like("k.id", projectReportData.getProjectMaster2Name()).or().like("k.name", projectReportData.getProjectMaster2Name());
        }
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.like("a.create_by_id", projectReportData.getCreateBy().getId()).or().like("f.name",projectReportData.getCreateBy().getId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getApplyFileType())) { // 状态筛选
            queryWrapper.eq("a.apply_file_type", projectReportData.getApplyFileType());
        }
        //创建时间
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_time", contractDates[0], contractDates[1]);
        }
        // 如果当前用户是部门主任，则可以查看部门所有的项目、自己创建的项目以及所属项目组的项目
        // 如果当前用户是员工，则可以查看自己创建的项目以及所属项目组的项目
        StringBuilder officeIds = new StringBuilder();
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> manageOfficeIdList= Lists.newArrayList();

        /*//获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        //获取当前登录人所属角色
        //若是评估部门主任，则仅展示部门主任信息
        //若是评估员工，则仅展示自己的数据信息
        List<RoleDTO> roleDTOList = userDTO.getRoleDTOList();
        for (RoleDTO roleDTO : roleDTOList) {
            //根据角色id查询角色信息
            RoleDTO roleDTOById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
            if("cwyg".equals(roleDTOById.getEnName()) && "兴光会计员工".equals(roleDTOById.getName())){
                queryWrapper.eq("a.create_by_id", userDTO.getId());
                break;
            }else if("cw_bmzr".equals(roleDTOById.getEnName()) && "兴光会计部门主任".equals(roleDTOById.getName())){
                queryWrapper.eq("sumo.user_id", userDTO.getId());
                break;
            }
        }*/



        IPage<ArchivedReportInfoDto> list = applyMapper.getList(page, queryWrapper,officeIds.toString());
        list.getRecords().stream().forEach(i -> {
            // 报告作废归档
            if (StringUtils.isNotBlank(i.getArchivedTaskId()) && StringUtils.isNotBlank(i.getApplyFileType())) {
                if ("2".equals(i.getApplyFileType())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsArchived(flowTaskService.getTaskAuditUsers(i.getArchivedTaskId()));  // 获取数据审核人
                }
            }
        });
//        List<UserDTO> allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        List<UserDTO> allUserInfo = (List<UserDTO>) RedisUtils.getInstance().get(CacheNames.USER_CACHE_USER_ALL_INFO);
        if (null == allUserInfo || allUserInfo.size() == 0) {
            allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        }
        List<UserDTO> finalAllUserInfo = allUserInfo;
        list.getRecords().forEach(li -> {
            if (StringUtils.isBlank(li.getProjectMasterName())){
                //根据项目经理1的id去查项目经理去名称
                if (StringUtils.isNotBlank(li.getProjectMasterId())){
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getProjectMasterId().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setProjectMasterName(projectMasterName);
                    }
                }

                if (StringUtils.isNotBlank(li.getProjectMaster2Id())){
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getProjectMaster2Id().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setProjectMaster2Name(projectMasterName);
                    }
                }

                if (StringUtils.isBlank(li.getReportSponsor())) {
                    if (StringUtils.isNotBlank(li.getReportSponsorId())){
                        UserDTO matchingUser = null;
                        for (UserDTO user : finalAllUserInfo) {
                            if (li.getReportSponsorId().equals(user.getId())) {
                                matchingUser = user;
                                break;
                            }
                        }
                        if (matchingUser != null) {
                            String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                            li.setReportSponsor(projectMasterName);
                        }
                    }
                }

            }
        });
        return list;
    }

    /**
     * 根据id查询项目详情
     *
     * @param id
     * @return
     */
    public ApplyArchiveReportDTO queryById(String id) {
        //传过来的是报告作废流程表的id
        ReportCancellApply apply = cancellApplyMapper.getById(id);
        ApplyArchiveReportDTO reportDTO = new ApplyArchiveReportDTO();
        if (null != apply) {
            //根据报告表id查出报废归档信息
            CwProjectReportApplyArchive applyArchive = applyMapper.getInfoByBFID(apply.getId());
            if (null != applyArchive) {
                reportDTO.setReportNum(applyArchive.getReportNum());
                reportDTO.setPapersNum(applyArchive.getPapersNum());
                reportDTO.setYear(applyArchive.getYear());
                reportDTO.setNumber(applyArchive.getNumber());
                reportDTO.setIsNumber(applyArchive.getIsNumber());
                reportDTO.setAuditDate(applyArchive.getAuditDate());
                reportDTO.setFileNumber(applyArchive.getFileNumber());
                reportDTO.setApplyFileType(applyArchive.getApplyFileType());
                reportDTO.setReportRemarks(applyArchive.getReportRemarks());
                reportDTO.setCarchivedType(applyArchive.getCarchivedType());
                reportDTO.setRemarks(applyArchive.getRemarks());

                //设置附件
                List<CwWorkAttachmentArchiveDto> files = applyMapper.selectFileInfoByAttid(applyArchive.getId());
                if (null != files) {
                    files.forEach(fi -> {
                        UserDTO userDTO = applyMapper.getUserInfo(fi.getUserId());
                        fi.setCreateBy(userDTO);
                    });
                    //附件信息
                    reportDTO.setWorkAttachmentDtoList(files);
                }
            }
            //设置项目信息
            //根据新建行id找到项目id
            CwProjectRecordsDTO recordsDTO = applyMapper.getProjectByNewLineId(apply.getReportNewLineId());
            reportDTO.setCwProjectRecordsDTO(recordsDTO);
            //设置报告文号相关信息
            //根据新建行找到签字注师信息与报告文号信息
            CwProjectInfoData byId = infoMapper.getById(apply.getReportNewLineId());
            CwProjectReport report = reportMapper.getByNewLineId(byId.getReportId());
            reportDTO.setReportNo(byId.getReportNo());
            reportDTO.setReportDate(byId.getReportDate());
            reportDTO.setReportCreateName(byId.getReportCreateName());
            reportDTO.setSignatureAnnotator1Name(report.getSignatureAnnotator1Name());
            reportDTO.setSignatureAnnotator2Name(report.getSignatureAnnotator2Name());
        } else {
            //传来的是归档的id
            apply = cancellApplyMapper.selectByArchivedId(id);
            if (null != apply) {
                //根据报告表id查出报废归档信息
                CwProjectReportApplyArchive applyArchive = applyMapper.getInfoByBFID(apply.getId());
                if (null != applyArchive) {
                    reportDTO.setReportNum(applyArchive.getReportNum());
                    reportDTO.setPapersNum(applyArchive.getPapersNum());
                    reportDTO.setYear(applyArchive.getYear());
                    reportDTO.setNumber(applyArchive.getNumber());
                    reportDTO.setIsNumber(applyArchive.getIsNumber());
                    reportDTO.setAuditDate(applyArchive.getAuditDate());
                    reportDTO.setFileNumber(applyArchive.getFileNumber());
                    reportDTO.setApplyFileType(applyArchive.getApplyFileType());
                    reportDTO.setReportRemarks(applyArchive.getReportRemarks());
                    reportDTO.setCarchivedType(applyArchive.getCarchivedType());
                    reportDTO.setRemarks(applyArchive.getRemarks());
                    //设置附件
                    List<CwWorkAttachmentArchiveDto> files = applyMapper.selectFileInfoByAttid(applyArchive.getId());
                    if (null != files) {
                        files.forEach(fi -> {
                            UserDTO userDTO = applyMapper.getUserInfo(fi.getUserId());
                            fi.setCreateBy(userDTO);
                        });
                        //附件信息
                        reportDTO.setWorkAttachmentDtoList(files);
                    }
                }
                //设置项目信息
                //根据新建行id找到项目id
                CwProjectRecordsDTO recordsDTO = applyMapper.getProjectByNewLineId(apply.getReportNewLineId());
                reportDTO.setCwProjectRecordsDTO(recordsDTO);
                //设置报告文号相关信息
                //根据新建行找到签字注师信息与报告文号信息
                CwProjectInfoData byId = infoMapper.getById(apply.getReportNewLineId());
                CwProjectReport report = reportMapper.getByNewLineId(byId.getReportId());
                reportDTO.setReportNo(byId.getReportNo());
                reportDTO.setReportDate(byId.getReportDate());
                reportDTO.setReportCreateName(byId.getCreateById());
                reportDTO.setSignatureAnnotator1Name(report.getSignatureAnnotator1Name());
                reportDTO.setSignatureAnnotator2Name(report.getSignatureAnnotator2Name());
            }
        }
        return reportDTO;
    }

    /**
     * 保存项目归档信息以及其他相关信息
     *
     * @param cwProjectReportArchiveDTO
     * @return
     * @throws Exception
     */
    public String saveForm(ApplyArchiveReportDTO cwProjectReportArchiveDTO) throws Exception {
        //根据报废id来查是否有改数据
        CwProjectReportApplyArchive report = applyMapper.getInfoByBFID(cwProjectReportArchiveDTO.getId());
        if (null != report) {
            report.setCreateById(cwProjectReportArchiveDTO.getCreateBy().getId());
            return update(cwProjectReportArchiveDTO, report.getId(),report.getArchiveId(),report.getProcInsId(),report.getProcessDefinitionId());
        } else {
            report = applyMapper.getById(cwProjectReportArchiveDTO.getId());
            if (null != report) {
                return update(cwProjectReportArchiveDTO, report.getId(),report.getArchiveId(),report.getProcInsId(),report.getProcessDefinitionId());
            } else {
                return add(cwProjectReportArchiveDTO);
            }
        }
    }

    /**
     * 合同登记新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(ApplyArchiveReportDTO reportDTO) throws Exception {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        String id = UUID.randomUUID().toString().replace("-", "");
        CwProjectReportApplyArchive applyArchive = new CwProjectReportApplyArchive();
        BeanUtils.copyProperties(reportDTO, applyArchive);
        applyArchive.setId(id);
        applyArchive.setCreateById(userDTO.getId());
        applyArchive.setCreateTime(new Date());
        applyArchive.setUpdateById(userDTO.getId());
        applyArchive.setUpdateTime(new Date());
        //传过来的是report表的id
        //根据改id查报废信息
//        String newLineId = applyMapper.getNewLineId(reportDTO.getId());
        //根据newLineID查出报废表id
//        String bfId = applyMapper.getBfId(newLineId);
        applyArchive.setArchiveId(reportDTO.getId());
        applyMapper.insert(applyArchive);
        //修改报告作废表的归档状态
        applyMapper.updateArchiveStyle(reportDTO.getId(), applyArchive.getApplyFileType());
        List<CwWorkAttachmentArchiveDto> list = reportDTO.getWorkAttachmentDtoList();
//        if (CollectionUtils.isNotEmpty(list)) {
//            saveFiles(list, userDTO, id);
//        }
        saveFiles(list, userDTO, id);
        return id;
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(ApplyArchiveReportDTO reportData, String id,String archiveId,String procInsId,String defId) throws Exception {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());

        CwProjectReportApplyArchive cwProjectReportArchive = new CwProjectReportApplyArchive();
        BeanUtils.copyProperties(reportData, cwProjectReportArchive);
        cwProjectReportArchive.setUpdateById(userDTO.getId());
        cwProjectReportArchive.setUpdateTime(new Date());
        cwProjectReportArchive.setId(id);
        cwProjectReportArchive.setArchiveId(archiveId);
        cwProjectReportArchive.setProcInsId(procInsId);
        cwProjectReportArchive.setProcessDefinitionId(defId);
        applyMapper.updateInfoById(cwProjectReportArchive);
        //修改报告作废表的归档状态
        applyMapper.updateArchiveStyle(cwProjectReportArchive.getArchiveId(), cwProjectReportArchive.getApplyFileType());
        //对上传的文件数据进行持久化操作
        List<CwWorkAttachmentArchiveDto> list = reportData.getWorkAttachmentDtoList();
        if (CollectionUtils.isNotEmpty(list)) {
            updateFiles(list, userDTO, cwProjectReportArchive.getId());
        } else {
            applyMapper.deleteFileInfo(cwProjectReportArchive.getId());
        }

        return cwProjectReportArchive.getId();
    }

    /**
     * 修改附件信息
     *
     * @param list    待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id      关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<CwWorkAttachmentArchiveDto> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (CwWorkAttachmentArchiveDto dto : list) {
            names = names + "," + dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = applyMapper.findList(id);
        if (CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (CwWorkAttachmentArchiveDto dto : list) {
            //判断是否存在
            Integer isExit = applyMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateTime(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateTime(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                String fileName = dto.getName();
                List<String> strings = Arrays.asList(fileName.split("\\."));
                // 检查文件名是否有后缀
                if (CollectionUtil.isNotEmpty(strings) && strings.size() > 1) {
                    // 获取最后一个部分作为文件类型
                    i.setType(strings.get(strings.size() - 1));
                } else {
                    // 如果没有后缀或文件名无效，设置一个默认类型或空
                    i.setType("");
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("cwWorkContract");
                i.setFileSize(dto.getSize());
                i.setSort(j);
                Map<String,String> map = new HashMap<>();
                String workAttachment = JSON.toJSONString((i));
                String userDTOInfo = JSON.toJSONString((userDTO));
                map.put("workAttachment",workAttachment);
                map.put("userDTO",userDTOInfo);
                SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
//                ossServiceMapper.insertWorkAttachment(i, userDTO);
                j++;
            }
        }
    }

    /**
     * 保存附件信息
     *
     * @param list    待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id      关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<CwWorkAttachmentArchiveDto> list, UserDTO userDTO, String id) {
        int j = 1;
        for (CwWorkAttachmentArchiveDto dto : list) {
            WorkAttachmentInfo i = new WorkAttachmentInfo();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateTime(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateTime(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            String fileName = dto.getName();
            List<String> strings = Arrays.asList(fileName.split("\\."));
            // 检查文件名是否有后缀
            if (CollectionUtil.isNotEmpty(strings) && strings.size() > 1) {
                // 获取最后一个部分作为文件类型
                i.setType(strings.get(strings.size() - 1));
            } else {
                // 如果没有后缀或文件名无效，设置一个默认类型或空
                i.setType("");
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("cwWorkContract");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            Map<String,String> map = new HashMap<>();
            String workAttachment = JSON.toJSONString((i));
            String userDTOInfo = JSON.toJSONString((userDTO));
            map.put("workAttachment",workAttachment);
            map.put("userDTO",userDTOInfo);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
//            ossServiceMapper.insertWorkAttachment(i, userDTO);
            j++;
        }
    }

    /**
     * 修改状态
     *
     * @param cwProjectReportArchiveDTO
     * @return
     */
    public String updateStatusById(ApplyArchiveReportDTO cwProjectReportArchiveDTO) {
        CwProjectReportApplyArchive cwProjectReportArchive = new CwProjectReportApplyArchive();
        CwProjectReportApplyArchive applyArchive = applyMapper.selectById(cwProjectReportArchiveDTO.getId());
        if (null != applyArchive){
            applyMapper.updateCancellArchiveType(cwProjectReportArchiveDTO.getApplyFileType(), cwProjectReportArchiveDTO.getId());

            applyMapper.updateStatusByArchiveId(cwProjectReportArchiveDTO.getApplyFileType(), applyArchive.getArchiveId());
        } else {
            applyArchive = applyMapper.getInfoByBFID(cwProjectReportArchiveDTO.getId());
            applyMapper.updateCancellArchiveType(cwProjectReportArchiveDTO.getApplyFileType(), applyArchive.getId());

            applyMapper.updateStatusByArchiveId(cwProjectReportArchiveDTO.getApplyFileType(), applyArchive.getArchiveId());
        }

        return "操作成功";
    }

    public ApplyArchiveReportDTO findByContractInfoId(String id) {
        return applyMapper.selectFilePaperByContractInfoId(id);
    }

    /**
     * 差选项目列表信息
     *
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<ArchivedReportInfoDto> findNotCompList(Page<ArchivedReportInfoDto> page, ArchivedReportInfoDto projectReportData) throws Exception {
        QueryWrapper<ArchivedReportInfoDto> queryWrapper = QueryWrapperGenerator.buildQueryCondition(projectReportData, ArchivedReportInfoDto.class);
        queryWrapper.eq("a.del_flag", "0");
        queryWrapper.eq("a.status", "5");
        //条件
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.like("a.create_by_id", projectReportData.getCreateBy().getId()).or().like("f.name",projectReportData.getCreateBy().getId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getApplyFileType()) && "-1".equals(projectReportData.getApplyFileType())) { // 状态筛选
            queryWrapper.ne("a.apply_file_type","5");
        }
        //创建时间
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {
            queryWrapper.between("a.create_time", contractDates[0], contractDates[1]);
        }
        StringBuilder officeIds = new StringBuilder();
        List<String> manageOfficeIdList= Lists.newArrayList();
        IPage<ArchivedReportInfoDto> list = applyMapper.getList(page, queryWrapper,officeIds.toString());
        list.getRecords().stream().forEach(i -> {
            // 报告作废归档
            if (StringUtils.isNotBlank(i.getArchivedTaskId()) && StringUtils.isNotBlank(i.getApplyFileType())) {
                if ("2".equals(i.getApplyFileType())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsArchived(flowTaskService.getTaskAuditUsers(i.getArchivedTaskId()));  // 获取数据审核人
                }
            }
        });
        List<UserDTO> allUserInfo = (List<UserDTO>) RedisUtils.getInstance().get(CacheNames.USER_CACHE_USER_ALL_INFO);
        if (null == allUserInfo || allUserInfo.size() == 0) {
            allUserInfo = SpringUtil.getBean(IUserApi.class).getAllUserInfo();
        }
        List<UserDTO> finalAllUserInfo = allUserInfo;
        list.getRecords().forEach(li -> {
            if (StringUtils.isBlank(li.getProjectMasterName())){
                //根据项目经理1的id去查项目经理去名称
                if (StringUtils.isNotBlank(li.getProjectMasterId())){
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getProjectMasterId().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setProjectMasterName(projectMasterName);
                    }
                }

                if (StringUtils.isNotBlank(li.getProjectMaster2Id())){
                    UserDTO matchingUser = null;
                    for (UserDTO user : finalAllUserInfo) {
                        if (li.getProjectMaster2Id().equals(user.getId())) {
                            matchingUser = user;
                            break;
                        }
                    }
                    if (matchingUser != null) {
                        String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                        li.setProjectMaster2Name(projectMasterName);
                    }
                }

                if (StringUtils.isBlank(li.getReportSponsor())) {
                    if (StringUtils.isNotBlank(li.getReportSponsorId())){
                        UserDTO matchingUser = null;
                        for (UserDTO user : finalAllUserInfo) {
                            if (li.getReportSponsorId().equals(user.getId())) {
                                matchingUser = user;
                                break;
                            }
                        }
                        if (matchingUser != null) {
                            String projectMasterName = matchingUser.getName(); // Assuming the property name is "userName"
                            li.setReportSponsor(projectMasterName);
                        }
                    }
                }

            }
        });
        return list;
    }

}
