package com.jeeplus.finance.projectReport.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.invoice.mapper.CwFinanceInvoiceMapper;
import com.jeeplus.finance.invoice.util.SignaturePostUtil;
import com.jeeplus.finance.projectRecords.domain.CwProjectRecords;
import com.jeeplus.finance.projectRecords.service.CwProjectRecordsService;
import com.jeeplus.finance.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.finance.projectReport.domain.*;
import com.jeeplus.finance.projectReport.mapper.*;
import com.jeeplus.finance.projectReport.service.dto.CwProjectReportDTO;
import com.jeeplus.finance.projectReport.service.dto.CwProjectReportSignatureDTO;
import com.jeeplus.finance.projectReport.service.dto.ProjectReportWorkAttachmentDTO;
import com.jeeplus.finance.projectReport.service.mapstruct.CwProjectReportFileWrapper;
import com.jeeplus.finance.projectReportArchive.domain.CwProjectReportArchive;
import com.jeeplus.finance.projectReportArchive.mapper.CwProjectReportArchiveMapper;
import com.jeeplus.finance.projectReportArchive.service.dto.CwProjectReportArchiveDTO;
import com.jeeplus.finance.utils.FileUtil;
import com.jeeplus.finance.utils.Global;
import com.jeeplus.finance.workClientInfo.domain.CwWorkClientBase;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientBaseDTO;
import com.jeeplus.finance.workClientInfo.service.mapstruct.CwWorkClientBaseWrapper;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IDictApi;
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 org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import org.springframework.core.env.Environment;

/**
 * @author: 王强
 * @create: 2022-11-16 14:17
 **/
@Service
@Transactional(rollbackFor = Exception.class)
@Component
public class CwProjectReportService extends ServiceImpl<CwProjectReportMapper, CwProjectReport> {

    private static final String HTTPTOP = Global.getConfig("signature_http_top");

    private static String APPROVALCATEGORYID  = Global.getConfig("approval_category_id");;
    @Autowired
    private Environment environment;

    @Resource
    private CwProjectReportMapper reportMapper;

    @Resource
    private CwProofreadDetailMapper detailMapper;

    @Resource
    private CwProjectInfoMapper infoMapper;

    @Resource
    private ProjectReportWorkAttachmentMapper attachmentMapper;


    @Resource
    private CwProjectReportCancelMapper cancelMapper;


    @Resource
    private CwProjectReportSignatureMapper cwProjectReportSignatureMapper;

    @Autowired
    private IFlowableApi flowTaskService;

    @Resource
    private CwProjectReportReviewMapper reviewMapper;

    @Resource
    private CwProjectReportReviewMapper mapper;

    @Resource
    private CwProjectReportService cwProjectReportService;
    @Resource
    private CwProjectReportArchiveMapper cwProjectReportArchiveMapper;

    @Resource
    private CwProjectRecordsService cwProjectRecordsService;

    @Resource
    private CwSignatureAnnotatorMapper cwSignatureAnnotatorMapper;

    @Resource
    private CwProjectReportNumberApplyMapper applyMapper;

    @Resource
    private CwRevocationSignatureMapper cwRevocationSignatureMapper;

    @Resource
    private CwFinanceInvoiceMapper cwFinanceInvoiceMapper;


    /**
     * 保存项目以及其他相关信息
     * @param reportData
     * @return
     * @throws Exception
     */
    public String saveForm(CwProjectReportData reportData) throws Exception{
        if (StringUtils.isNotEmpty(reportData.getId())){

            CwProjectReport report = reportMapper.getById(reportData.getId());
            if (report != null){
                reportData.setCreateBy(reportData.getCreateBy());
                reportData.setProcInsReview(report.getProcInsReview());
                reportData.setReviewStatus(report.getReviewStatus());
                return update(reportData);
            }
        }
        return add(reportData);

    }


    /**
     * 保存项目以及其他相关信息
     * @param reportData
     * @return
     * @throws Exception
     */
    public String saveForm2(CwProjectReportData reportData) throws Exception{
        if (StringUtils.isNotEmpty(reportData.getId())){

            CwProjectReport report = reportMapper.getById(reportData.getId());
            if (report != null){
                reportData.setCreateBy(reportData.getCreateBy());
                reportData.setProcInsReview(report.getProcInsReview());
                reportData.setReviewStatus(report.getReviewStatus());
                return update2(reportData);
            }
        }
        return null;
    }

    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(CwProjectReportData reportData) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));

        CwProjectReport report = new CwProjectReport();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());
        reportMapper.updateCwProjectReportDataById(report);
        //修改新增行数据
        CwProjectInfoData infoData = infoMapper.selectInfoByReportId(report.getId());
        infoData.setServedUnitName(report.getServedUnitName());
        infoData.setReportDate(report.getReportDate());
        infoData.setReportType(report.getReportType());
        infoData.setOpinionType(report.getOpinionType());
        infoData.setSealType(report.getSealType());
        infoData.setServedUnitId(report.getServedUnitId());
        infoData.setUpdateById(userDTO.getId());
        infoData.setApprovedIncludingTax(report.getApprovedIncludingTax());
        infoData.setApprovedNoIncludingTax(report.getApprovedNoIncludingTax());
        infoData.setBankLettersCount(report.getBankLettersCount());
        infoData.setDigitalLetterCount(report.getDigitalLetterCount());
//        infoData.setUpdateById(UserUtils.getCurrentUserDTO().getId());
        infoData.setUpdateTime(new Date());
        infoMapper.updateCwProjectInfoDataById(infoData);


        //对上传的文件数据进行持久化操作
        List<ProjectReportWorkAttachmentDTO> cwFileInfoList = report.getCwFileInfoList();
        List<WorkAttachmentInfo> cwFileInfoList2 = report.getCwFileInfoList2();

        CwProjectReportData cwProjectReportData = reportMapper.queryById(report.getId());
        //获取当前节点
        String currentTaskName = flowTaskService.getCurrentTaskName(cwProjectReportData.getProcInsId3());
        //当前节点为空时,说明为第一次发起,则可以修改附件
        if (StringUtils.isBlank(currentTaskName)){
            if (CollectionUtils.isNotEmpty(cwFileInfoList2)) {
//            updateFiles2(cwFileInfoList2, userDTO, report.getId());
//            ossService.saveOrUpdateFileList(cwFileInfoList2,report.getId(),"cwWorkContract");

                Map<String,String> map = new HashMap<>();
                String fileList = JSON.toJSONString((cwFileInfoList2));
                String attachmentId = report.getId();
                String attachmentFlag = "cwWorkContract";
                map.put("fileList",fileList);
                map.put("attachmentId",attachmentId);
                map.put("attachmentFlag",attachmentFlag);
                map.put("currentToken",TokenProvider.getCurrentToken ( ));
                SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map);

            }

            if (null != cwFileInfoList && cwFileInfoList.size()>0 ) {

                updateSignatureFiles(cwFileInfoList, userDTO, report.getId());

            }
        }else {
            //否则的话判断当前节点
            //当为驳回调整,撤回时 也可以对附件进行修改
            if ("发起人重新申请".equals(currentTaskName) || cwProjectReportData.getReviewStatus().equals("3")){
                if (CollectionUtils.isNotEmpty(cwFileInfoList2)) {
//            updateFiles2(cwFileInfoList2, userDTO, report.getId());
//            ossService.saveOrUpdateFileList(cwFileInfoList2,report.getId(),"cwWorkContract");

                    Map<String,String> map = new HashMap<>();
                    String fileList = JSON.toJSONString((cwFileInfoList2));
                    String attachmentId = report.getId();
                    String attachmentFlag = "cwWorkContract";
                    map.put("fileList",fileList);
                    map.put("attachmentId",attachmentId);
                    map.put("attachmentFlag",attachmentFlag);
                    map.put("currentToken",TokenProvider.getCurrentToken ( ));
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map);

                }

                if (null != cwFileInfoList && cwFileInfoList.size()>0 ) {

                    updateSignatureFiles(cwFileInfoList, userDTO, report.getId());

                }
            }
        }
        return report.getId();
    }


    /**
     * 修改审定金额
     * @param reportData
     * @return
     * @throws Exception
     */
    public String updateAmount(CwProjectReportData reportData) throws Exception {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        CwProjectReport report = new CwProjectReport();
        BeanUtils.copyProperties(reportData, report);
        CwProjectInfoData infoData = infoMapper.selectInfoByReportId(report.getId());
        infoData.setUpdateById(userDTO.getId());
        infoData.setApprovedIncludingTax(report.getApprovedIncludingTax());
        infoData.setApprovedNoIncludingTax(report.getApprovedNoIncludingTax());
        infoData.setUpdateTime(new Date());
        infoMapper.updateCwProjectInfoDataById(infoData);
        return report.getId();
    }

    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update2(CwProjectReportData reportData) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));

        CwProjectReport report = new CwProjectReport();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateById(userDTO.getId());
        report.setUpdateTime(new Date());
        reportMapper.updateCwProjectReportDataById(report);
        //当审核通过时,且该报告已完成关联,则将关联状态改为2
        CwProjectReportData cwProjectReportData = reportMapper.queryById(reportData.getId());
        if (StringUtils.isNotBlank(cwProjectReportData.getIsCompleteInvoice())){
            if ("5".equals(cwProjectReportData.getApplyStatus()) && "1".equals(cwProjectReportData.getIsCompleteInvoice())){
                reportMapper.updateCompleteInvoice(reportData.getId());
            }
        }

        //修改新增行数据
        CwProjectInfoData infoData = infoMapper.selectInfoByReportId(report.getId());
        infoData.setServedUnitName(report.getServedUnitName());
        infoData.setReportDate(report.getReportDate());
        infoData.setReportType(report.getReportType());
        infoData.setOpinionType(report.getOpinionType());
        infoData.setSealType(report.getSealType());
        infoData.setServedUnitId(report.getServedUnitId());
        infoData.setUpdateById(userDTO.getId());
        infoData.setApprovedNoIncludingTax(report.getApprovedNoIncludingTax());
        infoData.setApprovedIncludingTax(report.getApprovedIncludingTax());
        infoData.setBankLettersCount(report.getBankLettersCount());
        infoData.setDigitalLetterCount(report.getDigitalLetterCount());
//        infoData.setUpdateById(UserUtils.getCurrentUserDTO().getId());
        infoData.setUpdateTime(new Date());
        infoMapper.updateCwProjectInfoDataById(infoData);


        //对上传的文件数据进行持久化操作
//        List<WorkAttachmentInfo> cwFileInfoList3 = report.getCwFileInfoList3();
//        if (CollectionUtils.isNotEmpty(cwFileInfoList3)) {
//
//            Map<String,String> map = new HashMap<>();
//            String fileList = JSON.toJSONString((cwFileInfoList3));
//            String attachmentId = report.getId();
//            String attachmentFlag = "cwReportNumberApply";
//            map.put("fileList",fileList);
//            map.put("attachmentId",attachmentId);
//            map.put("attachmentFlag",attachmentFlag);
//            map.put("currentToken",TokenProvider.getCurrentToken ( ));
//            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map);
//
//        }

        //对上传的附件进行持久化操作
        List<WorkAttachmentInfo> fileInfoList3 = new ArrayList<>();
        if ( null !=report.getCwFileInfoList3()){
            fileInfoList3 = report.getCwFileInfoList3();
        }
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(report.getId());

        AtomicInteger j2 = new AtomicInteger(1);
        if (fileInfoList3 != null){
            fileInfoList3.forEach(item -> {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
                i.setCreateTime(new Date());
                i.setUpdateTime(new Date());
                i.setCreateById(userDTO.getId());
                i.setUpdateById(userDTO.getId());
                i.setDelFlag(0);
                i.setUrl(item.getUrl());
                //文件类型处理
                String fileName = item.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(report.getId());
                i.setAttachmentName(item.getName());
                i.setAttachmentFlag("cw_project_report_number_apply");
                i.setFileSize(item.getSize());
                i.setSort(j2.get());

                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);

            });
        }

        return report.getId();
    }

    public void updateSignatureInfo(CwProjectReportData projectReportData){
        reportMapper.updateSignatureInfo(projectReportData);
    }

    /**
     * 保存签章文件地址
     * @param projectReportData
     */
    public void updateSignatureUrl(CwProjectReportData projectReportData){
        reportMapper.updateSignatureUrl(projectReportData);
    }

    /**
     * 修改盖章状态
     * @param projectReportData
     */
    public void updateReportSealType(CwProjectReportData projectReportData){
        reportMapper.updateReportSealType(projectReportData);
    }

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(CwProjectReportData reportData) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        if(StringUtils.isBlank(reportData.getId())){
            //单据编号生成
            String documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), CwProjectReportDTO.BIZ_CODE,TokenProvider.getCurrentToken());
//            String documentNo = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), CwProjectReportDTO.BIZ_CODE);
            reportData.setDocumentNo(documentNo);
        }
        CwProjectReport report = new CwProjectReport();
        BeanUtils.copyProperties(reportData, report);
        if (ObjectUtil.isNotEmpty(report)) {
            if (StringUtils.isBlank(report.getCreateById())) {
                report.setCreateById(userDTO.getId());
//                report.setCreateById(UserUtils.getCurrentUserDTO().getId());
                String id = UUID.randomUUID().toString().replace("-", "");
                report.setId(id);
            }
        }
        //对新增行数据进行持久化操作
        CwProjectInfoData infoData = new CwProjectInfoData();
//        List<CwProjectInfoData> infoList = new ArrayList<>();
        infoData.setCreateById(userDTO.getId());
//        infoData.setCreateById(UserUtils.getCurrentUserDTO().getId());
        infoData.setCreateTime(new Date());
        infoData.setUpdateById(userDTO.getId());
//        infoData.setUpdateById(UserUtils.getCurrentUserDTO().getId());
        infoData.setUpdateTime(new Date());
        infoData.setReportId(report.getId());
        String id = UUID.randomUUID().toString().replace("-", "");
        infoData.setId(id);
        infoData.setServedUnitName(report.getServedUnitName());
        infoData.setReportDate(report.getReportDate());
        infoData.setReportType(report.getReportType());
        infoData.setOpinionType(report.getOpinionType());
        infoData.setSealType(report.getSealType());
        infoData.setServedUnitId(report.getServedUnitId());
        infoData.setApprovedIncludingTax(report.getApprovedIncludingTax());
        infoData.setApprovedNoIncludingTax(report.getApprovedNoIncludingTax());
//        //报告文号生成
//        String documentNo = "";
//        try {
//            documentNo = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), CwProjectInfoData.BIZ_CODE);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //在插入报告文号前先去报告文号报废表中根据时间排序查看是否有报告文号，有则使用，delflag改为1
//        List<String> reportNo = infoMapper.getReportNo();
//        if (null!= reportNo & reportNo.size()>0){
//            infoData.setReportNo(reportNo.get(0));
//            cancelMapper.updateFlag("1",reportNo.get(0));
//        }else {
//            infoData.setReportNo(documentNo);
//        }
        //报告流水号生成  根据项目编号去new_line表查询
//        String reportNumber = infoMapper.selectReportNumberByProjectNo(report.getProjectNumber());
//        int stress = 0;
//        if (null != reportNumber){
//            if (reportNumber.contains(report.getProjectNumber() + "-0")){
//                stress = reportNumber.indexOf("-0");//分隔符位置
//            }else {
//                stress = reportNumber.indexOf("-");//分隔符位置
//            }
//            String substring = reportNumber.substring(stress + 1, reportNumber.length());
//            int integer = Integer.parseInt(substring);
//
//            String newReportNumber = "";
//            if (integer>=9){
//                newReportNumber = report.getProjectNumber() + "-" + (integer + 1);
//            }else {
//                newReportNumber = report.getProjectNumber() + "-0" + (integer + 1);
//            }
//
//            infoData.setReportNumber(newReportNumber);
//        }else {
//            infoData.setReportNumber(report.getProjectNumber() + "-0" + "1");
//        }
        infoMapper.insert(infoData);

        //对上传的附件进行持久化操作
        List<WorkAttachmentInfo> fileInfoList2 = new ArrayList<>();
        if ( null !=report.getCwFileInfoList2()){
            fileInfoList2 = report.getCwFileInfoList2();
        }
//        ossServiceMapper.delete(new QueryWrapper<WorkAttachmentInfo>().lambda().eq(WorkAttachmentInfo::getAttachmentId, report.getId()));
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(report.getId());

        AtomicInteger j2 = new AtomicInteger(1);
        if (fileInfoList2 != null){
            fileInfoList2.forEach(item -> {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
                i.setCreateTime(new Date());
                i.setUpdateTime(new Date());
                i.setCreateById(userDTO.getId());
                i.setUpdateById(userDTO.getId());
                i.setDelFlag(0);
                i.setUrl(item.getUrl());
                //文件类型处理
                String fileName = item.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(report.getId());
                i.setAttachmentName(item.getName());
                i.setAttachmentFlag("cw_project_report");
                i.setFileSize(item.getSize());
                i.setSort(j2.get());

                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);
            });
        }

        //对上传的文件数据进行持久化操作
        List<ProjectReportWorkAttachmentDTO> fileInfoList = new ArrayList<>();
        if ( null !=report.getCwFileInfoList()){
            fileInfoList = report.getCwFileInfoList();
        }

        AtomicInteger j = new AtomicInteger(1);
        if (fileInfoList != null){
            fileInfoList.forEach(item -> {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
                i.setCreateTime(new Date());
                i.setUpdateTime(new Date());
                i.setDelFlag(0);
                i.setUrl(item.getUrl());
                //文件类型处理
                String fileName = item.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(report.getId());
                i.setAttachmentName(item.getName());
                i.setAttachmentFlag("cw_project_report_file");
                i.setFileSize(item.getSize());
                i.setSort(j.get());

                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.getAndIncrement();
                CwProjectReportFile cwProjectReportFile = CwProjectReportFileWrapper.INSTANCE.toEntity(item);
                cwProjectReportFile.setReportFileId(i.getId());
                attachmentMapper.insert(cwProjectReportFile);
            });
        }

        this.reportMapper.insert(report);

        // 添加签章流程初始数据
        // 公章流程
        CwProjectReportSignature cwProjectReportSignature1 = new CwProjectReportSignature();
        cwProjectReportSignature1.setReportId(report.getId());
        cwProjectReportSignature1.setType("1");
        cwProjectReportSignature1.setStatus("0");
        cwProjectReportSignatureMapper.insert(cwProjectReportSignature1);
        // 公章+执业章流程
        CwProjectReportSignature cwProjectReportSignature2 = new CwProjectReportSignature();
        cwProjectReportSignature2.setReportId(report.getId());
        cwProjectReportSignature2.setType("2");
        cwProjectReportSignature2.setStatus("0");
        cwProjectReportSignatureMapper.insert(cwProjectReportSignature2);
        // 实体章流程
        CwProjectReportSignature cwProjectReportSignature3 = new CwProjectReportSignature();
        cwProjectReportSignature3.setReportId(report.getId());
        cwProjectReportSignature3.setType("3");
        cwProjectReportSignature3.setStatus("0");
        cwProjectReportSignatureMapper.insert(cwProjectReportSignature3);

        //复核数据添加
        //保存基本信息
        CwProjectReview info = new CwProjectReview();
        BeanUtils.copyProperties(reportData, info);
        //报告编号生成
        String documentNo = "";
        /*if (info.getReportType().equals("1")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE1);
        } else if (info.getReportType().equals("2")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE2);
        } else if (info.getReportType().equals("3")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE3);
        } else if (info.getReportType().equals("4")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE4);
        } else if (info.getReportType().equals("5")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE5);
        }*/
        info.setId(id);
        info.setReportReviewNo(documentNo);
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setReportId(report.getId());
        mapper.insert(info);

        return report.getId();
    }

    /**
     * 差选项目列表信息
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<CwProjectReportData> findList(Page<CwProjectReportData> page, CwProjectReportData projectReportData) throws Exception{
        QueryWrapper<CwProjectReportData> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,CwProjectReportData.class);
        queryWrapper.eq("a.del_flag","0");
//        queryWrapper.orderByDesc("a.create_date");
        //条件
        if (StringUtils.isNotEmpty(projectReportData.getProjectNumber())) {
            queryWrapper.like("b.project_number", projectReportData.getProjectNumber());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectName())) {
            queryWrapper.like("b.project_name", projectReportData.getProjectName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getReportName())) {
            queryWrapper.like("a.report_name", projectReportData.getReportName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterId())) {
            queryWrapper.eq("b.project_master_id", projectReportData.getProjectMasterId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Id())) {
            queryWrapper.eq("b.real_header", projectReportData.getProjectMaster2Id());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterName())) { // 项目经理1筛选
            queryWrapper.like("e.id", projectReportData.getProjectMasterName()).or().like("e.name", projectReportData.getProjectMasterName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getRealHeaderName())) { // 项目经理2筛选
            queryWrapper.like("f.id", projectReportData.getRealHeaderName()).or().like("f.name", projectReportData.getRealHeaderName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.and(wrapper -> wrapper.like("a.create_by_id", projectReportData.getCreateBy().getId())
                    .or()
                    .like("d.name", projectReportData.getCreateBy().getId()));
        }
        //4、签约时间（区间）
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_time", contractDates[0], contractDates[1]);
        }
        //5、报告文号
        if (StringUtils.isNotEmpty(projectReportData.getReportNo())) {
            queryWrapper.like("new_line.report_no", projectReportData.getReportNo());
        }
        //6、审计收费
        String[] contractAmounts = projectReportData.getContractAmounts();
        if (contractAmounts != null) {
            if (StringUtils.isNotEmpty(contractAmounts[0])) {
                queryWrapper.ge("a.audit_fees",contractAmounts[0]);
            }
            if (contractAmounts.length>1 && StringUtils.isNotEmpty(contractAmounts[1])) {
                queryWrapper.le("a.audit_fees", contractAmounts[1]);
            }
        }
        if (StringUtils.isNotEmpty(projectReportData.getReviewStatus()) && !"-1".equals(projectReportData.getReviewStatus())){
            queryWrapper.eq("cw_rev.review_status", projectReportData.getReviewStatus());
        }
        //报告号签章状态
        if (StringUtils.isNotEmpty(projectReportData.getApplyStatus()) && !"-1".equals(projectReportData.getApplyStatus()) ) {
            if("0".equals(projectReportData.getApplyStatus())){
                queryWrapper.isNull("cw_na.review_status");
                if(StringUtils.isBlank(projectReportData.getReviewStatus())){
                    queryWrapper.eq("cw_rev.review_status","0");
                }
            }else{
                queryWrapper.eq("cw_na.review_status", projectReportData.getApplyStatus());
            }
        }
//        if(StringUtils.isNotEmpty(projectReportData.getApplyStatus()) && StringUtils.isNotEmpty(projectReportData.getReviewStatus())){
//            if("-1".equals(projectReportData.getApplyStatus()) && "-1".equals(projectReportData.getReviewStatus())){
//                queryWrapper.and(wrapper ->
//                        wrapper.ne("cw_na.review_status", "5")
//                                .or()
//                                .ne("cw_rev.review_status", "5")
//                );
//            }
//        }
        if (StringUtils.isNotEmpty(projectReportData.getStatus1())) {
            queryWrapper.eq("cw_prs1.status", projectReportData.getStatus1());
        }
        if (StringUtils.isNotBlank(projectReportData.getFilingType())) {
            List<CwProjectRecords> projectList = cwProjectRecordsService.list(new LambdaQueryWrapper<CwProjectRecords>().eq(CwProjectRecords::getReportType, projectReportData.getFilingType()));
            List<String> projectIdList = projectList.stream().map(CwProjectRecords::getId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(projectIdList)) {
                queryWrapper.in("b.id", projectIdList);
            } else {
                return new Page<>();
            }
        }
        if (ArrayUtil.isNotEmpty(projectReportData.getCreateDates())) {
            queryWrapper.between("a.create_time", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1]);
        }
        //报告日期
        if (ArrayUtil.isNotEmpty(projectReportData.getReportDates())) {
            queryWrapper.between("new_line.report_date", projectReportData.getReportDates()[0], projectReportData.getReportDates()[1]);
        }
        //项目分类
        if (StringUtils.isNotEmpty(projectReportData.getProjectClassification())) {
            queryWrapper.eq("b.project_classification", projectReportData.getProjectClassification());
        }
        //报告类型
        if (StringUtils.isNotEmpty(projectReportData.getReportType())) {
            queryWrapper.eq("new_line.report_type", projectReportData.getReportType());
        }

        String isBmzr = "0";
        StringBuilder officeIds = new StringBuilder();
        //UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> manageOfficeIdList= Lists.newArrayList();



        long l1 = System.currentTimeMillis();
        IPage<CwProjectReportData> list = null;
        long l2 = System.currentTimeMillis();
        System.out.println("报告列表查询service方法消耗时间:" + (l2-l1));

        //获取当前登录人角色是否是苏州报告签字盖章代办
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                if ("szbgqzgzdb".equals(dtoById.getEnName())){
                    list = reportMapper.findList2(page,isBmzr, officeIds.toString(), queryWrapper);
                    break;
                }
            }
        }

        if(null == list){
            list = reportMapper.findList(page,isBmzr, officeIds.toString(), queryWrapper);
        }

        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();
        }
        ArrayList<User> users = new ArrayList<>();
        List<UserDTO> finalAllUserInfo = allUserInfo;

        List<CwProjectReportData> records = list.getRecords();
        //获取查询的所有报告id
        List<String> reportIdList = Lists.newArrayList();

        for (CwProjectReportData record : records) {
            reportIdList.add(record.getId());
        }
        //根据报告id查询修改签字注师记录表信息
        List<CwSignatureAnnotator> sigByIdList = new ArrayList<CwSignatureAnnotator>();
        if(reportIdList.size()>0){
            sigByIdList = cwSignatureAnnotatorMapper.getSigByIdList(reportIdList);
        }

        List<CwSignatureAnnotator> finalSigByIdList = sigByIdList;
        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.isBlank(li.getRealHeaderName())) {
                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.isEmpty(li.getSignatureAnnotatorStatus())){
                li.setSignatureAnnotatorStatus("0");
            }
            /*CwSignatureAnnotator sigById = cwSignatureAnnotatorMapper.getSigById(li.getId());
            if (ObjectUtil.isNotEmpty(sigById)){
                li.setProcInsSigId(sigById.getProcInsId());
                li.setSigReason(sigById.getReason());
                li.setTaskSigId(sigById.getTaskId());
            }*/
            for (CwSignatureAnnotator annotator : finalSigByIdList) {
                if(li.getId().equals(annotator.getReportId())){
                    li.setProcInsSigId(annotator.getProcInsId());
                    li.setSigReason(annotator.getReason());
                    li.setTaskSigId(annotator.getTaskId());
                }
            }

            //如果质控审核已经完成且审核通过时间存在，则判断审核时间是否已经超过一天，若不超过，则可以重复发起质控审核
            if (null != li.getAuditTime() && "5".equals(li.getReviewStatus())){
                li.setRepetitionReviewFlag(getRepetitionReviewFlag(li.getAuditTime()));
            }

        });
        return list;

    }

    /**
     * 查询报告列表信息(发票选择)
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<CwProjectReportData> findList2(Page<CwProjectReportData> page, CwProjectReportData projectReportData) throws Exception{
        QueryWrapper<CwProjectReportData> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,CwProjectReportData.class);
        queryWrapper.eq("a.del_flag","0");
//        queryWrapper.orderByDesc("a.create_date");
        //条件
        if (StringUtils.isNotEmpty(projectReportData.getProjectNumber())) {
            queryWrapper.like("b.project_number", projectReportData.getProjectNumber());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectName())) {
            queryWrapper.like("b.project_name", projectReportData.getProjectName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getReportName())) {
            queryWrapper.like("a.report_name", projectReportData.getReportName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterId())) {
            queryWrapper.eq("b.project_master_id", projectReportData.getProjectMasterId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Id())) {
            queryWrapper.eq("b.real_header", projectReportData.getProjectMaster2Id());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterName())) { // 项目经理1筛选
            queryWrapper.like("e.id", projectReportData.getProjectMasterName()).or().like("e.name", projectReportData.getProjectMasterName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getRealHeaderName())) { // 项目经理2筛选
            queryWrapper.like("f.id", projectReportData.getRealHeaderName()).or().like("f.name", projectReportData.getRealHeaderName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.like("a.create_by_id", projectReportData.getCreateBy().getId()).or().like("d.name", projectReportData.getCreateBy().getId());
        }
        //4、签约时间（区间）
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_time", contractDates[0], contractDates[1]);
        }
        //5、报告文号
        if (StringUtils.isNotEmpty(projectReportData.getReportNo())) {
            queryWrapper.like("new_line.report_no", projectReportData.getReportNo());
        }
        //6、审计收费
        String[] contractAmounts = projectReportData.getContractAmounts();
        if (contractAmounts != null) {
            if (StringUtils.isNotEmpty(contractAmounts[0])) {
                queryWrapper.ge("a.audit_fees",contractAmounts[0]);
            }
            if (contractAmounts.length>1 && StringUtils.isNotEmpty(contractAmounts[1])) {
                queryWrapper.le("a.audit_fees", contractAmounts[1]);
            }
        }
        if (StringUtils.isNotEmpty(projectReportData.getReviewStatus())) {
            queryWrapper.eq("cw_rev.review_status", projectReportData.getReviewStatus());
        }
        //报告号签章状态
        if (StringUtils.isNotEmpty(projectReportData.getApplyStatus())) {
            if("0".equals(projectReportData.getApplyStatus())){
                queryWrapper.isNull("cw_na.review_status");
                if(StringUtils.isBlank(projectReportData.getReviewStatus())){
                    queryWrapper.eq("cw_rev.review_status","0");
                }
            }else{
                queryWrapper.eq("cw_na.review_status", projectReportData.getApplyStatus());
            }
        }
        if (StringUtils.isNotEmpty(projectReportData.getStatus1())) {
            queryWrapper.eq("cw_prs1.status", projectReportData.getStatus1());
        }
        if (StringUtils.isNotBlank(projectReportData.getFilingType())) {
            List<CwProjectRecords> projectList = cwProjectRecordsService.list(new LambdaQueryWrapper<CwProjectRecords>().eq(CwProjectRecords::getReportType, projectReportData.getFilingType()));
            List<String> projectIdList = projectList.stream().map(CwProjectRecords::getId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(projectIdList)) {
                queryWrapper.in("b.id", projectIdList);
            } else {
                return new Page<>();
            }
        }
        if (ArrayUtil.isNotEmpty(projectReportData.getCreateDates())) {
            queryWrapper.between("a.create_time", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1]);
        }
        String isBmzr = "0";
        StringBuilder officeIds = new StringBuilder();
        //UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> manageOfficeIdList= Lists.newArrayList();



        long l1 = System.currentTimeMillis();
        IPage<CwProjectReportData> list = null;
        long l2 = System.currentTimeMillis();
        System.out.println("报告列表查询service方法消耗时间:" + (l2-l1));

        //获取当前登录人角色是否是苏州报告签字盖章代办
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                if ("szbgqzgzdb".equals(dtoById.getEnName())){
                    list = reportMapper.findList2(page,isBmzr, officeIds.toString(), queryWrapper);
                    break;
                }
            }
        }

        if(null == list){
            list = reportMapper.findList(page,isBmzr, officeIds.toString(), queryWrapper);
        }

        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();
        }
        ArrayList<User> users = new ArrayList<>();
        List<UserDTO> finalAllUserInfo = allUserInfo;
        //查找预开票未关联完成的项目
        CwProjectRecordsDTO cwProjectRecordsDTO = new CwProjectRecordsDTO();
        Page<CwProjectRecordsDTO> dtoPage = new Page<>();
        IPage<CwProjectRecordsDTO> preInvoiceList = cwProjectRecordsService.findPreInvoiceList(dtoPage, cwProjectRecordsDTO);
        //用来保存待处理的报告id
        ArrayList<String> strings = new ArrayList<>();

        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.isBlank(li.getRealHeaderName())) {
                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.isEmpty(li.getSignatureAnnotatorStatus())){
                li.setSignatureAnnotatorStatus("0");
            }
            CwSignatureAnnotator sigById = cwSignatureAnnotatorMapper.getSigById(li.getId());
            if (ObjectUtil.isNotEmpty(sigById)){
                li.setProcInsSigId(sigById.getProcInsId());
                li.setSigReason(sigById.getReason());
                li.setTaskSigId(sigById.getTaskId());
            }

            //如果质控审核已经完成且审核通过时间存在，则判断审核时间是否已经超过一天，若不超过，则可以重复发起质控审核
            if (null != li.getAuditTime() && "5".equals(li.getReviewStatus())){
                li.setRepetitionReviewFlag(getRepetitionReviewFlag(li.getAuditTime()));
            }

            if (ObjectUtil.isNotEmpty(preInvoiceList)){
                preInvoiceList.getRecords().forEach(project->{
                    if (project.getId().equals(li.getProjectId())){
                        strings.add(li.getId());
                    }
                });
            }

        });
        list.getRecords().removeIf(record -> strings.contains(record.getId()));
        return list;

    }

    /**
     * 查询报告列表信息(发票选择)
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<CwProjectReportData> getSignatureScribeList(Page<CwProjectReportData> page, CwProjectReportData projectReportData) throws Exception{
        QueryWrapper<CwProjectReportData> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,CwProjectReportData.class);
        queryWrapper.eq("a.del_flag","0");
        queryWrapper.and(qw -> qw.eq("a.signature_annotator1", projectReportData.getSignatureAnnotator1())
                .or()
                .eq("a.signature_annotator2", projectReportData.getSignatureAnnotator1()));
        Calendar cal = Calendar.getInstance();
        String yearStr = String.valueOf(cal.get(Calendar.YEAR));
        yearStr = yearStr + "-";
        queryWrapper.like("a.document_no",yearStr);
        //条件
        if (StringUtils.isNotEmpty(projectReportData.getProjectNumber())) {
            queryWrapper.like("b.project_number", projectReportData.getProjectNumber());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectName())) {
            queryWrapper.like("b.project_name", projectReportData.getProjectName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getReportName())) {
            queryWrapper.like("a.report_name", projectReportData.getReportName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterId())) {
            queryWrapper.eq("b.project_master_id", projectReportData.getProjectMasterId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Id())) {
            queryWrapper.eq("b.real_header", projectReportData.getProjectMaster2Id());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterName())) { // 项目经理1筛选
            queryWrapper.like("e.id", projectReportData.getProjectMasterName()).or().like("e.name", projectReportData.getProjectMasterName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getRealHeaderName())) { // 项目经理2筛选
            queryWrapper.like("f.id", projectReportData.getRealHeaderName()).or().like("f.name", projectReportData.getRealHeaderName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.like("a.create_by_id", projectReportData.getCreateBy().getId()).or().like("d.name", projectReportData.getCreateBy().getId());
        }
        //4、签约时间（区间）
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_time", contractDates[0], contractDates[1]);
        }
        //5、报告文号
        if (StringUtils.isNotEmpty(projectReportData.getReportNo())) {
            queryWrapper.like("new_line.report_no", projectReportData.getReportNo());
        }
        //6、审计收费
        String[] contractAmounts = projectReportData.getContractAmounts();
        if (contractAmounts != null) {
            if (StringUtils.isNotEmpty(contractAmounts[0])) {
                queryWrapper.ge("a.audit_fees",contractAmounts[0]);
            }
            if (contractAmounts.length>1 && StringUtils.isNotEmpty(contractAmounts[1])) {
                queryWrapper.le("a.audit_fees", contractAmounts[1]);
            }
        }
        if (StringUtils.isNotEmpty(projectReportData.getReviewStatus())) {
            queryWrapper.eq("cw_rev.review_status", projectReportData.getReviewStatus());
        }
        //报告号签章状态
        if (StringUtils.isNotEmpty(projectReportData.getApplyStatus())) {
            if("0".equals(projectReportData.getApplyStatus())){
                queryWrapper.isNull("cw_na.review_status");
                if(StringUtils.isBlank(projectReportData.getReviewStatus())){
                    queryWrapper.eq("cw_rev.review_status","0");
                }
            }else{
                queryWrapper.eq("cw_na.review_status", projectReportData.getApplyStatus());
            }
        }
        if (StringUtils.isNotEmpty(projectReportData.getStatus1())) {
            queryWrapper.eq("cw_prs1.status", projectReportData.getStatus1());
        }
        if (StringUtils.isNotBlank(projectReportData.getFilingType())) {
            List<CwProjectRecords> projectList = cwProjectRecordsService.list(new LambdaQueryWrapper<CwProjectRecords>().eq(CwProjectRecords::getReportType, projectReportData.getFilingType()));
            List<String> projectIdList = projectList.stream().map(CwProjectRecords::getId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(projectIdList)) {
                queryWrapper.in("b.id", projectIdList);
            } else {
                return new Page<>();
            }
        }
        if (ArrayUtil.isNotEmpty(projectReportData.getCreateDates())) {
            queryWrapper.between("a.create_time", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1]);
        }
        String isBmzr = "0";
        StringBuilder officeIds = new StringBuilder();
        //UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> manageOfficeIdList= Lists.newArrayList();



        long l1 = System.currentTimeMillis();
        IPage<CwProjectReportData> list = null;
        long l2 = System.currentTimeMillis();
        System.out.println("报告列表查询service方法消耗时间:" + (l2-l1));

        //获取当前登录人角色是否是苏州报告签字盖章代办
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                if ("szbgqzgzdb".equals(dtoById.getEnName())){
                    list = reportMapper.findList2(page,isBmzr, officeIds.toString(), queryWrapper);
                    break;
                }
            }
        }

        if(null == list){
            list = reportMapper.findList(page,isBmzr, officeIds.toString(), queryWrapper);
        }

        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();
        }
        ArrayList<User> users = new ArrayList<>();
        List<UserDTO> finalAllUserInfo = allUserInfo;
        //查找预开票未关联完成的项目
        CwProjectRecordsDTO cwProjectRecordsDTO = new CwProjectRecordsDTO();
        Page<CwProjectRecordsDTO> dtoPage = new Page<>();
        IPage<CwProjectRecordsDTO> preInvoiceList = cwProjectRecordsService.findPreInvoiceList(dtoPage, cwProjectRecordsDTO);
        //用来保存待处理的报告id
        ArrayList<String> strings = new ArrayList<>();

        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.isBlank(li.getRealHeaderName())) {
                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.isEmpty(li.getSignatureAnnotatorStatus())){
                li.setSignatureAnnotatorStatus("0");
            }
            CwSignatureAnnotator sigById = cwSignatureAnnotatorMapper.getSigById(li.getId());
            if (ObjectUtil.isNotEmpty(sigById)){
                li.setProcInsSigId(sigById.getProcInsId());
                li.setSigReason(sigById.getReason());
                li.setTaskSigId(sigById.getTaskId());
            }

            //如果质控审核已经完成且审核通过时间存在，则判断审核时间是否已经超过一天，若不超过，则可以重复发起质控审核
            if (null != li.getAuditTime() && "5".equals(li.getReviewStatus())){
                li.setRepetitionReviewFlag(getRepetitionReviewFlag(li.getAuditTime()));
            }

            if (ObjectUtil.isNotEmpty(preInvoiceList)){
                preInvoiceList.getRecords().forEach(project->{
                    if (project.getId().equals(li.getProjectId())){
                        strings.add(li.getId());
                    }
                });
            }

        });
        list.getRecords().removeIf(record -> strings.contains(record.getId()));
        return list;

    }


    /**
     * 差选项目列表信息(移动端)
     * @param page
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<CwProjectReportData> findListApp(Page<CwProjectReportData> page, CwProjectReportData projectReportData) throws Exception{
        QueryWrapper<CwProjectReportData> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,CwProjectReportData.class);
        queryWrapper.eq("a.del_flag","0");
//        queryWrapper.orderByDesc("a.create_date");
        //条件
        if (StringUtils.isNotEmpty(projectReportData.getProjectNumber())) {
            queryWrapper.like("b.project_number", projectReportData.getProjectNumber());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectName())) {
            queryWrapper.like("b.project_name", projectReportData.getProjectName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getReportName())) {
            queryWrapper.like("a.report_name", projectReportData.getReportName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterId())) {
            queryWrapper.eq("b.project_master_id", projectReportData.getProjectMasterId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Id())) {
            queryWrapper.eq("b.real_header", projectReportData.getProjectMaster2Id());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterName())) { // 项目经理1筛选
            queryWrapper.like("e.id", projectReportData.getProjectMasterName()).or().like("e.name", projectReportData.getProjectMasterName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getRealHeaderName())) { // 项目经理2筛选
            queryWrapper.like("f.id", projectReportData.getRealHeaderName()).or().like("f.name", projectReportData.getRealHeaderName());
        }
        if ( null != projectReportData.getCreateBy() && StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.like("a.create_by_id", projectReportData.getCreateBy().getId()).or().like("d.name", projectReportData.getCreateBy().getId());
        }
        //4、签约时间（区间）
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_time", contractDates[0], contractDates[1]);
        }
        //5、报告文号
        if (StringUtils.isNotEmpty(projectReportData.getReportNo())) {
            queryWrapper.like("new_line.report_no", projectReportData.getReportNo());
        }
        //6、审计收费
        String[] contractAmounts = projectReportData.getContractAmounts();
        if (contractAmounts != null) {
            if (StringUtils.isNotEmpty(contractAmounts[0])) {
                queryWrapper.ge("a.audit_fees",contractAmounts[0]);
            }
            if (contractAmounts.length>1 && StringUtils.isNotEmpty(contractAmounts[1])) {
                queryWrapper.le("a.audit_fees", contractAmounts[1]);
            }
        }
        if (StringUtils.isNotEmpty(projectReportData.getReviewStatus())) {
            queryWrapper.eq("cw_rev.review_status", projectReportData.getReviewStatus());
        }
        //报告号签章状态
        if (StringUtils.isNotEmpty(projectReportData.getApplyStatus())) {
            if("0".equals(projectReportData.getApplyStatus())){
                queryWrapper.isNull("cw_na.review_status");
                if(StringUtils.isBlank(projectReportData.getReviewStatus())){
                    queryWrapper.eq("cw_rev.review_status","0");
                }
            }else{
                queryWrapper.eq("cw_na.review_status", projectReportData.getApplyStatus());
            }
        }
        if (StringUtils.isNotEmpty(projectReportData.getStatus1())) {
            queryWrapper.eq("cw_prs1.status", projectReportData.getStatus1());
        }
        if (StringUtils.isNotBlank(projectReportData.getFilingType())) {
            List<CwProjectRecords> projectList = cwProjectRecordsService.list(new LambdaQueryWrapper<CwProjectRecords>().eq(CwProjectRecords::getReportType, projectReportData.getFilingType()));
            List<String> projectIdList = projectList.stream().map(CwProjectRecords::getId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(projectIdList)) {
                queryWrapper.in("b.id", projectIdList);
            } else {
                return new Page<>();
            }
        }
        if (ArrayUtil.isNotEmpty(projectReportData.getCreateDates())) {
            queryWrapper.between("a.create_time", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1]);
        }
        String isBmzr = "0";
        StringBuilder officeIds = new StringBuilder();
        //UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> manageOfficeIdList= Lists.newArrayList();



        long l1 = System.currentTimeMillis();
        IPage<CwProjectReportData> list = null;
        long l2 = System.currentTimeMillis();
        System.out.println("报告列表查询service方法消耗时间:" + (l2-l1));

        //获取当前登录人角色是否是苏州报告签字盖章代办
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOByIdForApp(roleDTO.getId());
                if ("szbgqzgzdb".equals(dtoById.getEnName())){
                    list = reportMapper.findList2(page,isBmzr, officeIds.toString(), queryWrapper);
                    break;
                }
            }
        }

        if(null == list){
            list = reportMapper.findList(page,isBmzr, officeIds.toString(), queryWrapper);
        }

        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();
        }
        ArrayList<User> users = new ArrayList<>();
        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.isBlank(li.getRealHeaderName())) {
                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.isEmpty(li.getSignatureAnnotatorStatus())){
                li.setSignatureAnnotatorStatus("0");
            }
            CwSignatureAnnotator sigById = cwSignatureAnnotatorMapper.getSigById(li.getId());
            if (ObjectUtil.isNotEmpty(sigById)){
                li.setProcInsSigId(sigById.getProcInsId());
                li.setSigReason(sigById.getReason());
                li.setTaskSigId(sigById.getTaskId());
            }

            //如果质控审核已经完成且审核通过时间存在，则判断审核时间是否已经超过一天，若不超过，则可以重复发起质控审核
            if (null != li.getAuditTime() && "5".equals(li.getReviewStatus())){
                li.setRepetitionReviewFlag(getRepetitionReviewFlag(li.getAuditTime()));
            }

        });
        return list;

    }
    /**
     * 计算两时间是否超过一天（秒）
     * @param auditTime
     * @return
     */
    public Boolean getRepetitionReviewFlag(Date auditTime){
        // 创建一个Calendar对象，表示当前时间
        Calendar currentTime = Calendar.getInstance();
        // 获取当前时间的毫秒数
        long currentTimeInMillis = currentTime.getTimeInMillis();
        // 获取质控审核已经完成的毫秒数
        long targetTimeInMillis = auditTime.getTime();
        // 计算时间差异（以毫秒为单位）
        long timeDifferenceInMillis = currentTimeInMillis - targetTimeInMillis;
        // 将时间差异转换为秒
        long timeDifferenceInMinutes = timeDifferenceInMillis / (1000);
        if(timeDifferenceInMinutes > 86400){
            //若超过86400， 则超过一天，即不可进行重新复核操作
            return false;
        }else{
            //可进行重复质控操作
            return true;
        }

    }

    /**
     * 修改状态
     * @param data
     * @return
     */
    public String updateStatusById(CwProjectReportData data) {
        CwProjectReport cwProjectRecords = new CwProjectReport();
        BeanUtils.copyProperties(data, cwProjectRecords);
        reportMapper.update(cwProjectRecords, new QueryWrapper<CwProjectReport>().lambda().eq(CwProjectReport::getId, cwProjectRecords.getId()));
        return "操作成功";
    }

    public CwProjectReportData queryById(String id) {

        CwProjectReportData reportData = reportMapper.queryById(id);

        //如果质控审核已经完成且审核通过时间存在，则判断审核时间是否已经超过一天，若不超过，则可以重复发起质控审核
        if (null != reportData && null != reportData.getAuditTime() && "5".equals(reportData.getReviewStatus())){
            reportData.setRepetitionReviewFlag(getRepetitionReviewFlag(reportData.getAuditTime()));
        }

        //将新增行数据查询出来放入到cwProjectInfoList中
        CwProjectInfoData cwProjectInfoData = infoMapper.selectByReportId(id);
        if (null != cwProjectInfoData){
            reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
            reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
            reportData.setReportDate(cwProjectInfoData.getReportDate());
            reportData.setReportType(cwProjectInfoData.getReportType());
            reportData.setReportNumber(cwProjectInfoData.getReportNumber());
            reportData.setReportNo(cwProjectInfoData.getReportNo());
            reportData.setSealType(cwProjectInfoData.getSealType());
        }

//        List<CwProjectInfoData> infoData = new ArrayList<>();

        List<ProjectReportWorkAttachmentDTO> dtoList = new ArrayList<>();
        List<ProjectReportWorkAttachmentDTO> signatureList = new ArrayList<>();
        if ( null != reportData){
            List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
            if (null != dtos){

                Iterator<ProjectReportWorkAttachmentDTO> it = dtos.iterator();
                while(it.hasNext()){
                    ProjectReportWorkAttachmentDTO d = it.next();
                    //根据id查出cw_project_report_file文件表的其他信息
                    //未签章附件
                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                    if (null != file) {
                        d.setFileType(file.getFileType());
                        d.setSealType(file.getSealType());
                        d.setSealedFile(file.getSealedFile());
                        d.setSealUser(file.getSealUser());
                        d.setSealDate(file.getSealDate());
                        d.setRemarks(file.getRemarks());
                        UserDTO userDTO = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name = reportMapper.getUserNameById(file.getCreateById());
                        userDTO.setId(file.getCreateById());
                        userDTO.setName(name);
                        d.setCreateBy(userDTO);
                        d.setCreateTime(file.getCreateTime());
                        dtoList.add(d);
                        it.remove();
                    }

                    //已签章附件
                    CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                    if (null != signatureFile){
                        d.setFileType(signatureFile.getFileType());
                        d.setSealType(signatureFile.getSealType());
                        d.setSealedFile(signatureFile.getSealedFile());
                        d.setSealUser(signatureFile.getSealUser());
                        d.setSealDate(signatureFile.getSealDate());
                        d.setRemarks(signatureFile.getRemarks());
                        UserDTO userDTO2 = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                        userDTO2.setId(signatureFile.getCreateById());
                        userDTO2.setName(name2);
                        d.setCreateBy(userDTO2);
                        d.setCreateTime(signatureFile.getCreateTime());
                        signatureList.add(d);
                        it.remove();
                    }
                }
                reportData.setCwFileInfoList(dtoList);
                reportData.setSignatureFileList(signatureList);
            }

            //将附件信息查出
            // 查询附件信息
            List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(id);
            List<WorkAttachmentInfo> reportFileList = Lists.newArrayList();
            if(CollectionUtils.isNotEmpty(dtos) && CollectionUtils.isNotEmpty(fileInfo2)){
                for (ProjectReportWorkAttachmentDTO dto : dtos) {
                    for (WorkAttachmentInfo workAttachmentDto : fileInfo2) {
                        if(dto.getId().equals(workAttachmentDto.getId())){
                            reportFileList.add(workAttachmentDto);
                        }
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : reportFileList) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            reportData.setCwFileInfoList2(reportFileList);
            //设置历史报告列表
            //根据项目id查出所有的信息
            List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
            List<CwProjectInfoData> dataInfoList = new ArrayList<>();
            if (null != byProjectList) {
                CwProjectReportData finalReportData1 = reportData;
                byProjectList.forEach(pro->{
                    //根据reportid查出新增行数据
                    CwProjectInfoData infoData = infoMapper.getByReportId(pro.getId());
                    //根据reportid查出所有的附件信息
                    List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                    List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData1.getId());
                    //历史的附件信息是否是查改reportid对应的所有附件
                    if (null != cwFileInfoList){
                        cwFileInfoList.forEach(fi->{
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                            if (null != file) {
                                fi.setFileType(file.getFileType());
                                fi.setSealType(file.getSealType());
                                fi.setSealedFile(file.getSealedFile());
                                fi.setSealUser(file.getSealUser());
                                fi.setSealDate(file.getSealDate());
                                fi.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                fi.setCreateBy(userDTO);
                                fi.setCreateTime(file.getCreateTime());
                                fileList.add(fi);
                            }
                        });
                        //设置附件信息
                        infoData.setCwFileInfoList(fileList);
                        if (pro.getStatus().equals("5")) {
                            infoData.setDocumentStatus("已完成");
                        }
                        dataInfoList.add(infoData);
                    }
                });
            }

            reportData.setCwWorkClientContactDTOList(dataInfoList);

            //将复核数据查出来
            CwProjectReview review = reviewMapper.selectByReportId(reportData.getId());
            if ( null != review) {
                reportData.setReviewStatus(review.getReviewStatus());
                reportData.setAllPrintNum(review.getAllPrintNum());
                reportData.setIssueNum(review.getIssueNum());
                reportData.setPlaceOnFileNum(review.getPlaceOnFileNum());
                reportData.setPrintedBy(review.getPrintedBy());
                reportData.setCheckAutograph(review.getCheckAutograph());
                reportData.setReportTitleType(review.getReportTitleType());
                reportData.setNeedUpdate1(review.getNeedUpdate1());
                reportData.setNeedUpdate2(review.getNeedUpdate2());
                reportData.setNeedUpdate3(review.getNeedUpdate3());
                reportData.setRemark1(review.getRemark1());
                reportData.setRemark2(review.getRemark2());
                reportData.setRemark3(review.getRemark3());
                reportData.setComputerNo(review.getComputerNo());
                reportData.setReportReviewNo(review.getReportReviewNo());
                reportData.setReviewBy(review.getReviewBy());
                //将一级复核等填入数据查出
                List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                if (null != details) {
                    reportData.setDetails(details);
                }
            }
            //根据报告类型查询下一节点用户
            List<ReviewUser> stringList = new ArrayList<>();
            //如果是苏州分部，这里写死
            String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
            if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                stringList = reportMapper.getReviewByPost("质控-苏州分部");
            }else if (reportData.getReportType().equals("1")) {
                stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
            } else {
                stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
            }
            reportData.setReviewBys(stringList);
        } else {
            //传来的是复核表的id
            CwProjectReview review = reviewMapper.selectById(id);
            if (null != review) {
                reportData = reportMapper.queryById(review.getReportId());
                if ( null != reportData){

                    //如果质控审核已经完成且审核通过时间存在，则判断审核时间是否已经超过一天，若不超过，则可以重复发起质控审核
                    if (null != reportData.getAuditTime() && "5".equals(reportData.getReviewStatus())){
                        reportData.setRepetitionReviewFlag(getRepetitionReviewFlag(reportData.getAuditTime()));
                    }

                    List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
                    if (null != dtos){

                        Iterator<ProjectReportWorkAttachmentDTO> it = dtos.iterator();
                        while(it.hasNext()){
                            ProjectReportWorkAttachmentDTO d = it.next();
                            //根据id查出cw_project_report_file文件表的其他信息
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                            if (null != file) {
                                d.setFileType(file.getFileType());
                                d.setSealType(file.getSealType());
                                d.setSealedFile(file.getSealedFile());
                                d.setSealUser(file.getSealUser());
                                d.setSealDate(file.getSealDate());
                                d.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                d.setCreateBy(userDTO);
                                d.setCreateTime(file.getCreateTime());
                                dtoList.add(d);
                                it.remove();
                            }

                            //已签章附件
                            CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                            if (null != signatureFile){
                                d.setFileType(signatureFile.getFileType());
                                d.setSealType(signatureFile.getSealType());
                                d.setSealedFile(signatureFile.getSealedFile());
                                d.setSealUser(signatureFile.getSealUser());
                                d.setSealDate(signatureFile.getSealDate());
                                d.setRemarks(signatureFile.getRemarks());
                                UserDTO userDTO2 = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                                userDTO2.setId(signatureFile.getCreateById());
                                userDTO2.setName(name2);
                                d.setCreateBy(userDTO2);
                                d.setCreateTime(signatureFile.getCreateTime());
                                signatureList.add(d);
                                it.remove();
                            }
                        }
                        reportData.setCwFileInfoList(dtoList);
                        reportData.setSignatureFileList(signatureList);
                    }
                    //将附件信息查出
                    // 查询附件信息
                    List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(reportData.getId());
                    List<WorkAttachmentInfo> reportFileList = Lists.newArrayList();
                    if(CollectionUtils.isNotEmpty(dtos) && CollectionUtils.isNotEmpty(fileInfo2)){
                        for (ProjectReportWorkAttachmentDTO dto : dtos) {
                            for (WorkAttachmentInfo workAttachmentDto : fileInfo2) {
                                if(dto.getId().equals(workAttachmentDto.getId())){
                                    reportFileList.add(workAttachmentDto);
                                }
                            }
                        }
                    }

                    if (CollectionUtils.isNotEmpty(dtos)) {
                        for (WorkAttachmentInfo i : reportFileList) {
                            i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                        }
                    }
                    reportData.setCwFileInfoList2(reportFileList);
                    //设置历史报告列表
                    //根据项目id查出所有的信息
                    List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
                    List<CwProjectInfoData> dataInfoList = new ArrayList<>();
                    if (null != byProjectList) {
                        CwProjectReportData finalReportData = reportData;
                        byProjectList.forEach(pro->{
                            //根据reportid查出新增行数据
                            CwProjectInfoData infoData = infoMapper.getByReportId(pro.getId());
                            //根据reportid查出所有的附件信息
                            List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                            List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData.getId());
                            //历史的附件信息是否是查改reportid对应的所有附件
                            if (null != cwFileInfoList){
                                cwFileInfoList.forEach(fi->{
                                    //未签章附件
                                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                                    if (null != file) {
                                        fi.setFileType(file.getFileType());
                                        fi.setSealType(file.getSealType());
                                        fi.setSealedFile(file.getSealedFile());
                                        fi.setSealUser(file.getSealUser());
                                        fi.setSealDate(file.getSealDate());
                                        fi.setRemarks(file.getRemarks());
                                        UserDTO userDTO = new UserDTO();
                                        //根据创建人id查出创建人名称
                                        String name = reportMapper.getUserNameById(file.getCreateById());
                                        userDTO.setId(file.getCreateById());
                                        userDTO.setName(name);
                                        fi.setCreateBy(userDTO);
                                        fi.setCreateTime(file.getCreateTime());
                                        fileList.add(fi);
                                    }
                                });
                                //设置附件信息
                                infoData.setCwFileInfoList(fileList);
                                if (pro.getStatus().equals("5")) {
                                    infoData.setDocumentStatus("已完成");
                                }
                                dataInfoList.add(infoData);
                            }
                        });
                    }

                    reportData.setCwWorkClientContactDTOList(dataInfoList);

                    //将复核数据查出来
//                CwProjectReview review = reviewMapper.selectByReportId(reportData.getId());
//                    if ( null != review) {
//
//                    }
                    reportData.setReviewStatus(review.getReviewStatus());
                    reportData.setAllPrintNum(review.getAllPrintNum());
                    reportData.setIssueNum(review.getIssueNum());
                    reportData.setPlaceOnFileNum(review.getPlaceOnFileNum());
                    reportData.setPrintedBy(review.getPrintedBy());
                    reportData.setCheckAutograph(review.getCheckAutograph());
                    reportData.setReportTitleType(review.getReportTitleType());
                    reportData.setNeedUpdate1(review.getNeedUpdate1());
                    reportData.setNeedUpdate2(review.getNeedUpdate2());
                    reportData.setNeedUpdate3(review.getNeedUpdate3());
                    reportData.setRemark1(review.getRemark1());
                    reportData.setRemark2(review.getRemark2());
                    reportData.setRemark3(review.getRemark3());
                    reportData.setComputerNo(review.getComputerNo());
                    reportData.setReviewBy(review.getReviewBy());

                    //将一级复核等填入数据查出
                    List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                    if (null != details) {
                        reportData.setDetails(details);
                    }
                    //根据报告类型查询下一节点用户
                    List<ReviewUser> stringList = new ArrayList<>();
                    //如果是苏州分部，这里写死
                    String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
                    if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                        stringList = reportMapper.getReviewByPost("质控-苏州分部");
                    }else if (reportData.getReportType().equals("1")) {
                        stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
                    } else {
                        stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
                    }
                    reportData.setReviewBys(stringList);
                    //将新增行数据查询出来放入到cwProjectInfoList中
                    cwProjectInfoData = infoMapper.selectByReportId(reportData.getId());
                    if (null != cwProjectInfoData){
                        reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
                        reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
                        reportData.setReportDate(cwProjectInfoData.getReportDate());
                        reportData.setReportType(cwProjectInfoData.getReportType());
                        reportData.setReportNumber(cwProjectInfoData.getReportNumber());
                        reportData.setReportNo(cwProjectInfoData.getReportNo());
                        reportData.setSealType(cwProjectInfoData.getSealType());
                    }
                }
            }

        }
        CwSignatureAnnotator cwSignatureAnnotator=cwSignatureAnnotatorMapper.getSigById(id);
        if (ObjectUtil.isNotEmpty(cwSignatureAnnotator)){
            reportData.setProcInsSigId(cwSignatureAnnotator.getProcInsId());
            reportData.setSigReason(cwSignatureAnnotator.getReason());
        }
        //获取当前登录人角色是否是苏州报告签字盖章代办
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                if (null != dtoById && "szbgqzgzdb".equals(dtoById.getEnName())){
                    reportData.setIsXs("1");
                }
            }
        }

        return reportData;
    }

    public CwProjectReportData queryByReId(String id) {

        CwProjectReportData reportData = reportMapper.queryByReId(id);

        //如果质控审核已经完成且审核通过时间存在，则判断审核时间是否已经超过一天，若不超过，则可以重复发起质控审核
        if (null != reportData && null != reportData.getAuditTime() && "5".equals(reportData.getReviewStatus())){
            reportData.setRepetitionReviewFlag(getRepetitionReviewFlag(reportData.getAuditTime()));
        }

        //将新增行数据查询出来放入到cwProjectInfoList中
        CwProjectInfoData cwProjectInfoData = infoMapper.selectByReportId(id);
        if (null != cwProjectInfoData){
            reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
            reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
            reportData.setReportDate(cwProjectInfoData.getReportDate());
            reportData.setReportType(cwProjectInfoData.getReportType());
            reportData.setReportNumber(cwProjectInfoData.getReportNumber());
            reportData.setReportNo(cwProjectInfoData.getReportNo());
            reportData.setSealType(cwProjectInfoData.getSealType());
        }

//        List<CwProjectInfoData> infoData = new ArrayList<>();

        List<ProjectReportWorkAttachmentDTO> dtoList = new ArrayList<>();
        List<ProjectReportWorkAttachmentDTO> signatureList = new ArrayList<>();
        if ( null != reportData){
            List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
            if (null != dtos){

                Iterator<ProjectReportWorkAttachmentDTO> it = dtos.iterator();
                while(it.hasNext()){
                    ProjectReportWorkAttachmentDTO d = it.next();
                    //根据id查出cw_project_report_file文件表的其他信息
                    //未签章附件
                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                    if (null != file) {
                        d.setFileType(file.getFileType());
                        d.setSealType(file.getSealType());
                        d.setSealedFile(file.getSealedFile());
                        d.setSealUser(file.getSealUser());
                        d.setSealDate(file.getSealDate());
                        d.setRemarks(file.getRemarks());
                        UserDTO userDTO = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name = reportMapper.getUserNameById(file.getCreateById());
                        userDTO.setId(file.getCreateById());
                        userDTO.setName(name);
                        d.setCreateBy(userDTO);
                        d.setCreateTime(file.getCreateTime());
                        dtoList.add(d);
                        it.remove();
                    }

                    //已签章附件
                    CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                    if (null != signatureFile){
                        d.setFileType(signatureFile.getFileType());
                        d.setSealType(signatureFile.getSealType());
                        d.setSealedFile(signatureFile.getSealedFile());
                        d.setSealUser(signatureFile.getSealUser());
                        d.setSealDate(signatureFile.getSealDate());
                        d.setRemarks(signatureFile.getRemarks());
                        UserDTO userDTO2 = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                        userDTO2.setId(signatureFile.getCreateById());
                        userDTO2.setName(name2);
                        d.setCreateBy(userDTO2);
                        d.setCreateTime(signatureFile.getCreateTime());
                        signatureList.add(d);
                        it.remove();
                    }
                }
                reportData.setCwFileInfoList(dtoList);
                reportData.setSignatureFileList(signatureList);
            }

            //将附件信息查出
            // 查询附件信息
            List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(id);
            List<WorkAttachmentInfo> reportFileList = Lists.newArrayList();
            if(CollectionUtils.isNotEmpty(dtos) && CollectionUtils.isNotEmpty(fileInfo2)){
                for (ProjectReportWorkAttachmentDTO dto : dtos) {
                    for (WorkAttachmentInfo workAttachmentDto : fileInfo2) {
                        if(dto.getId().equals(workAttachmentDto.getId())){
                            reportFileList.add(workAttachmentDto);
                        }
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : reportFileList) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            reportData.setCwFileInfoList2(reportFileList);
            //设置历史报告列表
            //根据项目id查出所有的信息
            List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
            List<CwProjectInfoData> dataInfoList = new ArrayList<>();
            if (null != byProjectList) {
                CwProjectReportData finalReportData1 = reportData;
                byProjectList.forEach(pro->{
                    //根据reportid查出新增行数据
                    CwProjectInfoData infoData = infoMapper.getByReportId(pro.getId());
                    //根据reportid查出所有的附件信息
                    List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                    List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData1.getId());
                    //历史的附件信息是否是查改reportid对应的所有附件
                    if (null != cwFileInfoList){
                        cwFileInfoList.forEach(fi->{
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                            if (null != file) {
                                fi.setFileType(file.getFileType());
                                fi.setSealType(file.getSealType());
                                fi.setSealedFile(file.getSealedFile());
                                fi.setSealUser(file.getSealUser());
                                fi.setSealDate(file.getSealDate());
                                fi.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                fi.setCreateBy(userDTO);
                                fi.setCreateTime(file.getCreateTime());
                                fileList.add(fi);
                            }
                        });
                        //设置附件信息
                        infoData.setCwFileInfoList(fileList);
                        if (pro.getStatus().equals("5")) {
                            infoData.setDocumentStatus("已完成");
                        }
                        dataInfoList.add(infoData);
                    }
                });
            }

            reportData.setCwWorkClientContactDTOList(dataInfoList);

            //将复核数据查出来
            CwProjectReview review = reviewMapper.selectByReportId(reportData.getId());
            if ( null != review) {
                reportData.setReviewStatus(review.getReviewStatus());
                reportData.setAllPrintNum(review.getAllPrintNum());
                reportData.setIssueNum(review.getIssueNum());
                reportData.setPlaceOnFileNum(review.getPlaceOnFileNum());
                reportData.setPrintedBy(review.getPrintedBy());
                reportData.setCheckAutograph(review.getCheckAutograph());
                reportData.setReportTitleType(review.getReportTitleType());
                reportData.setNeedUpdate1(review.getNeedUpdate1());
                reportData.setNeedUpdate2(review.getNeedUpdate2());
                reportData.setNeedUpdate3(review.getNeedUpdate3());
                reportData.setRemark1(review.getRemark1());
                reportData.setRemark2(review.getRemark2());
                reportData.setRemark3(review.getRemark3());
                reportData.setComputerNo(review.getComputerNo());
                reportData.setReportReviewNo(review.getReportReviewNo());
                reportData.setReviewBy(review.getReviewBy());
                //将一级复核等填入数据查出
                List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                if (null != details) {
                    reportData.setDetails(details);
                }
            }
            //根据报告类型查询下一节点用户
            List<ReviewUser> stringList = new ArrayList<>();
            //如果是苏州分部，这里写死
            String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
            if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                stringList = reportMapper.getReviewByPost("质控-苏州分部");
            }else if (reportData.getReportType().equals("1")) {
                stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
            } else {
                stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
            }
            reportData.setReviewBys(stringList);
        } else {
            //传来的是复核表的id
            CwProjectReview review = reviewMapper.selectById(id);
            if (null != review) {
                reportData = reportMapper.queryById(review.getReportId());
                if ( null != reportData){

                    //如果质控审核已经完成且审核通过时间存在，则判断审核时间是否已经超过一天，若不超过，则可以重复发起质控审核
                    if (null != reportData.getAuditTime() && "5".equals(reportData.getReviewStatus())){
                        reportData.setRepetitionReviewFlag(getRepetitionReviewFlag(reportData.getAuditTime()));
                    }

                    List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
                    if (null != dtos){

                        Iterator<ProjectReportWorkAttachmentDTO> it = dtos.iterator();
                        while(it.hasNext()){
                            ProjectReportWorkAttachmentDTO d = it.next();
                            //根据id查出cw_project_report_file文件表的其他信息
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                            if (null != file) {
                                d.setFileType(file.getFileType());
                                d.setSealType(file.getSealType());
                                d.setSealedFile(file.getSealedFile());
                                d.setSealUser(file.getSealUser());
                                d.setSealDate(file.getSealDate());
                                d.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                d.setCreateBy(userDTO);
                                d.setCreateTime(file.getCreateTime());
                                dtoList.add(d);
                                it.remove();
                            }

                            //已签章附件
                            CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                            if (null != signatureFile){
                                d.setFileType(signatureFile.getFileType());
                                d.setSealType(signatureFile.getSealType());
                                d.setSealedFile(signatureFile.getSealedFile());
                                d.setSealUser(signatureFile.getSealUser());
                                d.setSealDate(signatureFile.getSealDate());
                                d.setRemarks(signatureFile.getRemarks());
                                UserDTO userDTO2 = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                                userDTO2.setId(signatureFile.getCreateById());
                                userDTO2.setName(name2);
                                d.setCreateBy(userDTO2);
                                d.setCreateTime(signatureFile.getCreateTime());
                                signatureList.add(d);
                                it.remove();
                            }
                        }
                        reportData.setCwFileInfoList(dtoList);
                        reportData.setSignatureFileList(signatureList);
                    }
                    //将附件信息查出
                    // 查询附件信息
                    List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(reportData.getId());
                    List<WorkAttachmentInfo> reportFileList = Lists.newArrayList();
                    if(CollectionUtils.isNotEmpty(dtos) && CollectionUtils.isNotEmpty(fileInfo2)){
                        for (ProjectReportWorkAttachmentDTO dto : dtos) {
                            for (WorkAttachmentInfo workAttachmentDto : fileInfo2) {
                                if(dto.getId().equals(workAttachmentDto.getId())){
                                    reportFileList.add(workAttachmentDto);
                                }
                            }
                        }
                    }

                    if (CollectionUtils.isNotEmpty(dtos)) {
                        for (WorkAttachmentInfo i : reportFileList) {
                            i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                        }
                    }
                    reportData.setCwFileInfoList2(reportFileList);
                    //设置历史报告列表
                    //根据项目id查出所有的信息
                    List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
                    List<CwProjectInfoData> dataInfoList = new ArrayList<>();
                    if (null != byProjectList) {
                        CwProjectReportData finalReportData = reportData;
                        byProjectList.forEach(pro->{
                            //根据reportid查出新增行数据
                            CwProjectInfoData infoData = infoMapper.getByReportId(pro.getId());
                            //根据reportid查出所有的附件信息
                            List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                            List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData.getId());
                            //历史的附件信息是否是查改reportid对应的所有附件
                            if (null != cwFileInfoList){
                                cwFileInfoList.forEach(fi->{
                                    //未签章附件
                                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                                    if (null != file) {
                                        fi.setFileType(file.getFileType());
                                        fi.setSealType(file.getSealType());
                                        fi.setSealedFile(file.getSealedFile());
                                        fi.setSealUser(file.getSealUser());
                                        fi.setSealDate(file.getSealDate());
                                        fi.setRemarks(file.getRemarks());
                                        UserDTO userDTO = new UserDTO();
                                        //根据创建人id查出创建人名称
                                        String name = reportMapper.getUserNameById(file.getCreateById());
                                        userDTO.setId(file.getCreateById());
                                        userDTO.setName(name);
                                        fi.setCreateBy(userDTO);
                                        fi.setCreateTime(file.getCreateTime());
                                        fileList.add(fi);
                                    }
                                });
                                //设置附件信息
                                infoData.setCwFileInfoList(fileList);
                                if (pro.getStatus().equals("5")) {
                                    infoData.setDocumentStatus("已完成");
                                }
                                dataInfoList.add(infoData);
                            }
                        });
                    }

                    reportData.setCwWorkClientContactDTOList(dataInfoList);

                    //将复核数据查出来
//                CwProjectReview review = reviewMapper.selectByReportId(reportData.getId());
//                    if ( null != review) {
//
//                    }
                    reportData.setReviewStatus(review.getReviewStatus());
                    reportData.setAllPrintNum(review.getAllPrintNum());
                    reportData.setIssueNum(review.getIssueNum());
                    reportData.setPlaceOnFileNum(review.getPlaceOnFileNum());
                    reportData.setPrintedBy(review.getPrintedBy());
                    reportData.setCheckAutograph(review.getCheckAutograph());
                    reportData.setReportTitleType(review.getReportTitleType());
                    reportData.setNeedUpdate1(review.getNeedUpdate1());
                    reportData.setNeedUpdate2(review.getNeedUpdate2());
                    reportData.setNeedUpdate3(review.getNeedUpdate3());
                    reportData.setRemark1(review.getRemark1());
                    reportData.setRemark2(review.getRemark2());
                    reportData.setRemark3(review.getRemark3());
                    reportData.setComputerNo(review.getComputerNo());
                    reportData.setReviewBy(review.getReviewBy());

                    //将一级复核等填入数据查出
                    List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                    if (null != details) {
                        reportData.setDetails(details);
                    }
                    //根据报告类型查询下一节点用户
                    List<ReviewUser> stringList = new ArrayList<>();
                    //如果是苏州分部，这里写死
                    String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
                    if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                        stringList = reportMapper.getReviewByPost("质控-苏州分部");
                    }else if (reportData.getReportType().equals("1")) {
                        stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
                    } else {
                        stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
                    }
                    reportData.setReviewBys(stringList);
                    //将新增行数据查询出来放入到cwProjectInfoList中
                    cwProjectInfoData = infoMapper.selectByReportId(reportData.getId());
                    if (null != cwProjectInfoData){
                        reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
                        reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
                        reportData.setReportDate(cwProjectInfoData.getReportDate());
                        reportData.setReportType(cwProjectInfoData.getReportType());
                        reportData.setReportNumber(cwProjectInfoData.getReportNumber());
                        reportData.setReportNo(cwProjectInfoData.getReportNo());
                        reportData.setSealType(cwProjectInfoData.getSealType());
                    }
                }
            }

        }
        CwSignatureAnnotator cwSignatureAnnotator=cwSignatureAnnotatorMapper.getSigById(id);
        if (ObjectUtil.isNotEmpty(cwSignatureAnnotator)){
            reportData.setProcInsSigId(cwSignatureAnnotator.getProcInsId());
            reportData.setSigReason(cwSignatureAnnotator.getReason());
        }
        //获取当前登录人角色是否是苏州报告签字盖章代办
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                if ("szbgqzgzdb".equals(dtoById.getEnName())){
                    reportData.setIsXs("1");
                }
            }
        }

        return reportData;
    }

    public CwProjectReportData queryById2(String id) {

        CwProjectReportData reportData = reportMapper.queryById(id);

        //将新增行数据查询出来放入到cwProjectInfoList中
        CwProjectInfoData cwProjectInfoData = infoMapper.selectByReportId(id);
        if (null != cwProjectInfoData){
            reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
            reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
            reportData.setReportDate(cwProjectInfoData.getReportDate());
            reportData.setReportType(cwProjectInfoData.getReportType());
            reportData.setReportNumber(cwProjectInfoData.getReportNumber());
            reportData.setReportNo(cwProjectInfoData.getReportNo());
            reportData.setSealType(cwProjectInfoData.getSealType());
        }

//        List<CwProjectInfoData> infoData = new ArrayList<>();

        List<ProjectReportWorkAttachmentDTO> dtoList = new ArrayList<>();
        List<ProjectReportWorkAttachmentDTO> signatureList = new ArrayList<>();
        if ( null != reportData){

            List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
            if (null != dtos){

                Iterator<ProjectReportWorkAttachmentDTO> it = dtos.iterator();
                while(it.hasNext()){
                    ProjectReportWorkAttachmentDTO d = it.next();
                    //根据id查出cw_project_report_file文件表的其他信息
                    //未签章附件
                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                    if (null != file) {
                        d.setFileType(file.getFileType());
                        d.setSealType(file.getSealType());
                        d.setSealedFile(file.getSealedFile());
                        d.setSealUser(file.getSealUser());
                        d.setSealDate(file.getSealDate());
                        d.setRemarks(file.getRemarks());
                        UserDTO userDTO = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name = reportMapper.getUserNameById(file.getCreateById());
                        userDTO.setId(file.getCreateById());
                        userDTO.setName(name);
                        d.setCreateBy(userDTO);
                        d.setCreateTime(file.getCreateTime());
                        dtoList.add(d);
                        it.remove();
                    }

                    //已签章附件
                    CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                    if (null != signatureFile){
                        d.setFileType(signatureFile.getFileType());
                        d.setSealType(signatureFile.getSealType());
                        d.setSealedFile(signatureFile.getSealedFile());
                        d.setSealUser(signatureFile.getSealUser());
                        d.setSealDate(signatureFile.getSealDate());
                        d.setRemarks(signatureFile.getRemarks());
                        UserDTO userDTO2 = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                        userDTO2.setId(signatureFile.getCreateById());
                        userDTO2.setName(name2);
                        d.setCreateBy(userDTO2);
                        d.setCreateTime(signatureFile.getCreateTime());
                        signatureList.add(d);
                        it.remove();
                    }
                }
                reportData.setCwFileInfoList(dtoList);
                reportData.setSignatureFileList(signatureList);
            }

            //将附件信息查出
            // 查询附件信息
            List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(id);
            List<WorkAttachmentInfo> reportFileList = Lists.newArrayList();
            if(CollectionUtils.isNotEmpty(dtos) && CollectionUtils.isNotEmpty(fileInfo2)){
                for (ProjectReportWorkAttachmentDTO dto : dtos) {
                    for (WorkAttachmentInfo workAttachmentDto : fileInfo2) {
                        if(dto.getId().equals(workAttachmentDto.getId())){
                            reportFileList.add(workAttachmentDto);
                        }
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : reportFileList) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            reportData.setCwFileInfoList3(reportFileList);
            //设置历史报告列表
            //根据项目id查出所有的信息
            List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
            List<CwProjectInfoData> dataInfoList = new ArrayList<>();
            if (null != byProjectList) {
                CwProjectReportData finalReportData1 = reportData;
                byProjectList.forEach(pro->{
                    //根据reportid查出新增行数据
                    CwProjectInfoData infoData = infoMapper.getByReportId(pro.getId());
                    //根据reportid查出所有的附件信息
                    List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                    List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData1.getId());
                    //历史的附件信息是否是查改reportid对应的所有附件
                    if (null != cwFileInfoList){
                        cwFileInfoList.forEach(fi->{
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                            if (null != file) {
                                fi.setFileType(file.getFileType());
                                fi.setSealType(file.getSealType());
                                fi.setSealedFile(file.getSealedFile());
                                fi.setSealUser(file.getSealUser());
                                fi.setSealDate(file.getSealDate());
                                fi.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                fi.setCreateBy(userDTO);
                                fi.setCreateTime(file.getCreateTime());
                                fileList.add(fi);
                            }
                        });
                        //设置附件信息
                        infoData.setCwFileInfoList(fileList);
                        if (pro.getStatus().equals("5")) {
                            infoData.setDocumentStatus("已完成");
                        }
                        dataInfoList.add(infoData);
                    }
                });
            }

            reportData.setCwWorkClientContactDTOList(dataInfoList);

            //将复核数据查出来
            CwProjectReview review = reviewMapper.selectByReportId(reportData.getId());
            if ( null != review) {
                reportData.setReviewStatus(review.getReviewStatus());
                reportData.setAllPrintNum(review.getAllPrintNum());
                reportData.setIssueNum(review.getIssueNum());
                reportData.setPlaceOnFileNum(review.getPlaceOnFileNum());
                reportData.setPrintedBy(review.getPrintedBy());
                reportData.setCheckAutograph(review.getCheckAutograph());
                reportData.setReportTitleType(review.getReportTitleType());
                reportData.setNeedUpdate1(review.getNeedUpdate1());
                reportData.setNeedUpdate2(review.getNeedUpdate2());
                reportData.setNeedUpdate3(review.getNeedUpdate3());
                reportData.setRemark1(review.getRemark1());
                reportData.setRemark2(review.getRemark2());
                reportData.setRemark3(review.getRemark3());
                reportData.setComputerNo(review.getComputerNo());
                reportData.setReportReviewNo(review.getReportReviewNo());
                reportData.setReviewBy(review.getReviewBy());
                //将一级复核等填入数据查出
                List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                if (null != details) {
                    reportData.setDetails(details);
                }
            }
            //根据报告类型查询下一节点用户
            List<ReviewUser> stringList = new ArrayList<>();
            //如果是苏州分部，这里写死
            String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
            if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                stringList = reportMapper.getReviewByPost("质控-苏州分部");
            }else if (reportData.getReportType().equals("1")) {
                stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
            } else {
                stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
            }
            reportData.setReviewBys(stringList);
        } else {
            //传来的是  报告号申请表 的id
            CwProjectReportNumberApply review = applyMapper.selectById(id);
            if (null != review) {
                reportData = reportMapper.queryById(review.getReportId());
                if ( null != reportData){
                    List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
                    if (null != dtos){

                        Iterator<ProjectReportWorkAttachmentDTO> it = dtos.iterator();
                        while(it.hasNext()){
                            ProjectReportWorkAttachmentDTO d = it.next();
                            //根据id查出cw_project_report_file文件表的其他信息
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                            if (null != file) {
                                d.setFileType(file.getFileType());
                                d.setSealType(file.getSealType());
                                d.setSealedFile(file.getSealedFile());
                                d.setSealUser(file.getSealUser());
                                d.setSealDate(file.getSealDate());
                                d.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                d.setCreateBy(userDTO);
                                d.setCreateTime(file.getCreateTime());
                                dtoList.add(d);
                                it.remove();
                            }

                            //已签章附件
                            CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                            if (null != signatureFile){
                                d.setFileType(signatureFile.getFileType());
                                d.setSealType(signatureFile.getSealType());
                                d.setSealedFile(signatureFile.getSealedFile());
                                d.setSealUser(signatureFile.getSealUser());
                                d.setSealDate(signatureFile.getSealDate());
                                d.setRemarks(signatureFile.getRemarks());
                                UserDTO userDTO2 = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                                userDTO2.setId(signatureFile.getCreateById());
                                userDTO2.setName(name2);
                                d.setCreateBy(userDTO2);
                                d.setCreateTime(signatureFile.getCreateTime());
                                signatureList.add(d);
                                it.remove();
                            }
                        }
                        reportData.setCwFileInfoList(dtoList);
                        reportData.setSignatureFileList(signatureList);
                    }
                    //将附件信息查出
                    // 查询附件信息
                    List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(reportData.getId());
                    List<WorkAttachmentInfo> reportFileList = Lists.newArrayList();
                    if(CollectionUtils.isNotEmpty(dtos) && CollectionUtils.isNotEmpty(fileInfo2)){
                        for (ProjectReportWorkAttachmentDTO dto : dtos) {
                            for (WorkAttachmentInfo workAttachmentDto : fileInfo2) {
                                if(dto.getId().equals(workAttachmentDto.getId())){
                                    reportFileList.add(workAttachmentDto);
                                }
                            }
                        }
                    }

                    if (CollectionUtils.isNotEmpty(dtos)) {
                        for (WorkAttachmentInfo i : reportFileList) {
                            i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                        }
                    }
                    reportData.setCwFileInfoList3(reportFileList);
                    //设置历史报告列表
                    //根据项目id查出所有的信息
                    List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
                    List<CwProjectInfoData> dataInfoList = new ArrayList<>();
                    if (null != byProjectList) {
                        CwProjectReportData finalReportData = reportData;
                        byProjectList.forEach(pro->{
                            //根据reportid查出新增行数据
                            CwProjectInfoData infoData = infoMapper.getByReportId(pro.getId());
                            //根据reportid查出所有的附件信息
                            List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                            List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData.getId());
                            //历史的附件信息是否是查改reportid对应的所有附件
                            if (null != cwFileInfoList){
                                cwFileInfoList.forEach(fi->{
                                    //未签章附件
                                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                                    if (null != file) {
                                        fi.setFileType(file.getFileType());
                                        fi.setSealType(file.getSealType());
                                        fi.setSealedFile(file.getSealedFile());
                                        fi.setSealUser(file.getSealUser());
                                        fi.setSealDate(file.getSealDate());
                                        fi.setRemarks(file.getRemarks());
                                        UserDTO userDTO = new UserDTO();
                                        //根据创建人id查出创建人名称
                                        String name = reportMapper.getUserNameById(file.getCreateById());
                                        userDTO.setId(file.getCreateById());
                                        userDTO.setName(name);
                                        fi.setCreateBy(userDTO);
                                        fi.setCreateTime(file.getCreateTime());
                                        fileList.add(fi);
                                    }
                                });
                                //设置附件信息
                                infoData.setCwFileInfoList(fileList);
                                if (pro.getStatus().equals("5")) {
                                    infoData.setDocumentStatus("已完成");
                                }
                                dataInfoList.add(infoData);
                            }
                        });
                    }

                    reportData.setCwWorkClientContactDTOList(dataInfoList);

                    //将复核数据查出来
                    //设置下一节点审核人信息
                    CwProjectReview projectReview = reviewMapper.selectByReportId(reportData.getId());
                    reportData.setReviewBy(projectReview.getReviewBy());

                    //将一级复核等填入数据查出
                    List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                    if (null != details) {
                        reportData.setDetails(details);
                    }
                    //根据报告类型查询下一节点用户
                    List<ReviewUser> stringList = new ArrayList<>();
                    //如果是苏州分部，这里写死
                    String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
                    if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                        stringList = reportMapper.getReviewByPost("质控-苏州分部");
                    }else if (reportData.getReportType().equals("1")) {
                        stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
                    } else {
                        stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
                    }
                    reportData.setReviewBys(stringList);
                    //将新增行数据查询出来放入到cwProjectInfoList中
                    cwProjectInfoData = infoMapper.selectByReportId(reportData.getId());
                    if (null != cwProjectInfoData){
                        reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
                        reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
                        reportData.setReportDate(cwProjectInfoData.getReportDate());
                        reportData.setReportType(cwProjectInfoData.getReportType());
                        reportData.setReportNumber(cwProjectInfoData.getReportNumber());
                        reportData.setReportNo(cwProjectInfoData.getReportNo());
                        reportData.setSealType(cwProjectInfoData.getSealType());
                    }
                }
            }

        }
        CwSignatureAnnotator cwSignatureAnnotator=cwSignatureAnnotatorMapper.getSigById(id);
        if (ObjectUtil.isNotEmpty(cwSignatureAnnotator)){
            reportData.setProcInsSigId(cwSignatureAnnotator.getProcInsId());
            reportData.setSigReason(cwSignatureAnnotator.getReason());
        }
        return reportData;
    }


    public Map getAuditInfoMap(HttpServletResponse response, String id) {

        CwProjectReportData reportData = reportMapper.queryById(id);

        //将新增行数据查询出来放入到cwProjectInfoList中
        CwProjectInfoData cwProjectInfoData = infoMapper.selectByReportId(id);
        if (null != cwProjectInfoData){
            reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
            reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
            reportData.setReportDate(cwProjectInfoData.getReportDate());
            reportData.setReportType(cwProjectInfoData.getReportType());
            reportData.setReportNumber(cwProjectInfoData.getReportNumber());
            reportData.setReportNo(cwProjectInfoData.getReportNo());
            reportData.setSealType(cwProjectInfoData.getSealType());
        }

//        List<CwProjectInfoData> infoData = new ArrayList<>();

        List<ProjectReportWorkAttachmentDTO> dtoList = new ArrayList<>();
        List<ProjectReportWorkAttachmentDTO> signatureList = new ArrayList<>();
        if ( null != reportData){
            List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
            if (null != dtos){
                dtos.forEach(d->{
                    //根据id查出cw_project_report_file文件表的其他信息
                    //未签章附件
                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                    if (null != file) {
                        d.setFileType(file.getFileType());
                        d.setSealType(file.getSealType());
                        d.setSealedFile(file.getSealedFile());
                        d.setSealUser(file.getSealUser());
                        d.setSealDate(file.getSealDate());
                        d.setRemarks(file.getRemarks());
                        UserDTO userDTO = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name = reportMapper.getUserNameById(file.getCreateById());
                        userDTO.setId(file.getCreateById());
                        userDTO.setName(name);
                        d.setCreateBy(userDTO);
                        d.setCreateTime(file.getCreateTime());
                        dtoList.add(d);
                    }

                    //已签章附件
                    CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                    if (null != signatureFile){
                        d.setFileType(signatureFile.getFileType());
                        d.setSealType(signatureFile.getSealType());
                        d.setSealedFile(signatureFile.getSealedFile());
                        d.setSealUser(signatureFile.getSealUser());
                        d.setSealDate(signatureFile.getSealDate());
                        d.setRemarks(signatureFile.getRemarks());
                        UserDTO userDTO2 = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                        userDTO2.setId(signatureFile.getCreateById());
                        userDTO2.setName(name2);
                        d.setCreateBy(userDTO2);
                        d.setCreateTime(signatureFile.getCreateTime());
                        signatureList.add(d);
                    }
                });
                reportData.setCwFileInfoList(dtoList);
                reportData.setSignatureFileList(signatureList);
            }
            //将附件信息查出
            // 查询附件信息
            List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : fileInfo2) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            reportData.setCwFileInfoList2(fileInfo2);
            //设置历史报告列表
            //根据项目id查出所有的信息
            List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
            List<CwProjectInfoData> dataInfoList = new ArrayList<>();
            if (null != byProjectList) {
                CwProjectReportData finalReportData1 = reportData;
                byProjectList.forEach(pro->{
                    //根据reportid查出新增行数据
                    CwProjectInfoData infoData = infoMapper.getByReportId(pro.getId());
                    //根据reportid查出所有的附件信息
                    List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                    List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData1.getId());
                    //历史的附件信息是否是查改reportid对应的所有附件
                    if (null != cwFileInfoList){
                        cwFileInfoList.forEach(fi->{
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                            if (null != file) {
                                fi.setFileType(file.getFileType());
                                fi.setSealType(file.getSealType());
                                fi.setSealedFile(file.getSealedFile());
                                fi.setSealUser(file.getSealUser());
                                fi.setSealDate(file.getSealDate());
                                fi.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                fi.setCreateBy(userDTO);
                                fi.setCreateTime(file.getCreateTime());
                                fileList.add(fi);
                            }
                        });
                        //设置附件信息
                        infoData.setCwFileInfoList(fileList);
                        if (pro.getStatus().equals("5")) {
                            infoData.setDocumentStatus("已完成");
                        }
                        dataInfoList.add(infoData);
                    }
                });
            }

            reportData.setCwWorkClientContactDTOList(dataInfoList);

            //将复核数据查出来
            CwProjectReview review = reviewMapper.selectByReportId(reportData.getId());
            if ( null != review) {
                reportData.setReviewStatus(review.getReviewStatus());
                reportData.setAllPrintNum(review.getAllPrintNum());
                reportData.setIssueNum(review.getIssueNum());
                reportData.setPlaceOnFileNum(review.getPlaceOnFileNum());
                reportData.setPrintedBy(review.getPrintedBy());
                reportData.setCheckAutograph(review.getCheckAutograph());
                reportData.setReportTitleType(review.getReportTitleType());
                reportData.setNeedUpdate1(review.getNeedUpdate1());
                reportData.setNeedUpdate2(review.getNeedUpdate2());
                reportData.setNeedUpdate3(review.getNeedUpdate3());
                reportData.setRemark1(review.getRemark1());
                reportData.setRemark2(review.getRemark2());
                reportData.setRemark3(review.getRemark3());
                reportData.setComputerNo(review.getComputerNo());
                reportData.setReportReviewNo(review.getReportReviewNo());
                reportData.setReviewBy(review.getReviewBy());
                //将一级复核等填入数据查出
                List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                if (null != details) {
                    reportData.setDetails(details);
                }
            }
            //根据报告类型查询下一节点用户
            List<ReviewUser> stringList = new ArrayList<>();
            //如果是苏州分部，这里写死
            String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
            if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                stringList = reportMapper.getReviewByPost("质控-苏州分部");
            }else if (reportData.getReportType().equals("1")) {
                stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
            } else {
                stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
            }
            reportData.setReviewBys(stringList);
        } else {
            //传来的是复核表的id
            CwProjectReview review = reviewMapper.selectById(id);
            if (null != review) {
                reportData = reportMapper.queryById(review.getReportId());
                if ( null != reportData){
                    List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
                    if (null != dtos){
                        dtos.forEach(d->{
                            //根据id查出cw_project_report_file文件表的其他信息
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                            if (null != file) {
                                d.setFileType(file.getFileType());
                                d.setSealType(file.getSealType());
                                d.setSealedFile(file.getSealedFile());
                                d.setSealUser(file.getSealUser());
                                d.setSealDate(file.getSealDate());
                                d.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                d.setCreateBy(userDTO);
                                d.setCreateTime(file.getCreateTime());
                                dtoList.add(d);
                            }

                            //已签章附件
                            CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                            if (null != signatureFile){
                                d.setFileType(signatureFile.getFileType());
                                d.setSealType(signatureFile.getSealType());
                                d.setSealedFile(signatureFile.getSealedFile());
                                d.setSealUser(signatureFile.getSealUser());
                                d.setSealDate(signatureFile.getSealDate());
                                d.setRemarks(signatureFile.getRemarks());
                                UserDTO userDTO2 = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                                userDTO2.setId(signatureFile.getCreateById());
                                userDTO2.setName(name2);
                                d.setCreateBy(userDTO2);
                                d.setCreateTime(signatureFile.getCreateTime());
                                signatureList.add(d);
                            }
                        });
                        reportData.setCwFileInfoList(dtoList);
                        reportData.setSignatureFileList(signatureList);
                    }
                    // 查询附件信息
                    List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(reportData.getId());
                    if (CollectionUtils.isNotEmpty(dtos)) {
                        for (WorkAttachmentInfo i : fileInfo2) {
                            i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                        }
                    }
                    reportData.setCwFileInfoList2(fileInfo2);
                    //设置历史报告列表
                    //根据项目id查出所有的信息
                    List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
                    List<CwProjectInfoData> dataInfoList = new ArrayList<>();
                    if (null != byProjectList) {
                        CwProjectReportData finalReportData = reportData;
                        byProjectList.forEach(pro->{
                            //根据reportid查出新增行数据
                            CwProjectInfoData infoData = infoMapper.getByReportId(pro.getId());
                            //根据reportid查出所有的附件信息
                            List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                            List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData.getId());
                            //历史的附件信息是否是查改reportid对应的所有附件
                            if (null != cwFileInfoList){
                                cwFileInfoList.forEach(fi->{
                                    //未签章附件
                                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                                    if (null != file) {
                                        fi.setFileType(file.getFileType());
                                        fi.setSealType(file.getSealType());
                                        fi.setSealedFile(file.getSealedFile());
                                        fi.setSealUser(file.getSealUser());
                                        fi.setSealDate(file.getSealDate());
                                        fi.setRemarks(file.getRemarks());
                                        UserDTO userDTO = new UserDTO();
                                        //根据创建人id查出创建人名称
                                        String name = reportMapper.getUserNameById(file.getCreateById());
                                        userDTO.setId(file.getCreateById());
                                        userDTO.setName(name);
                                        fi.setCreateBy(userDTO);
                                        fi.setCreateTime(file.getCreateTime());
                                        fileList.add(fi);
                                    }
                                });
                                //设置附件信息
                                infoData.setCwFileInfoList(fileList);
                                if (pro.getStatus().equals("5")) {
                                    infoData.setDocumentStatus("已完成");
                                }
                                dataInfoList.add(infoData);
                            }
                        });
                    }

                    reportData.setCwWorkClientContactDTOList(dataInfoList);

                    //将复核数据查出来
//                CwProjectReview review = reviewMapper.selectByReportId(reportData.getId());
//                    if ( null != review) {
//
//                    }
                    reportData.setReviewStatus(review.getReviewStatus());
                    reportData.setAllPrintNum(review.getAllPrintNum());
                    reportData.setIssueNum(review.getIssueNum());
                    reportData.setPlaceOnFileNum(review.getPlaceOnFileNum());
                    reportData.setPrintedBy(review.getPrintedBy());
                    reportData.setCheckAutograph(review.getCheckAutograph());
                    reportData.setReportTitleType(review.getReportTitleType());
                    reportData.setNeedUpdate1(review.getNeedUpdate1());
                    reportData.setNeedUpdate2(review.getNeedUpdate2());
                    reportData.setNeedUpdate3(review.getNeedUpdate3());
                    reportData.setRemark1(review.getRemark1());
                    reportData.setRemark2(review.getRemark2());
                    reportData.setRemark3(review.getRemark3());
                    reportData.setComputerNo(review.getComputerNo());
                    reportData.setReviewBy(review.getReviewBy());

                    //将一级复核等填入数据查出
                    List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                    if (null != details) {
                        reportData.setDetails(details);
                    }
                    //根据报告类型查询下一节点用户
                    List<ReviewUser> stringList = new ArrayList<>();
                    //如果是苏州分部，这里写死
                    String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
                    if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                        stringList = reportMapper.getReviewByPost("质控-苏州分部");
                    }else if (reportData.getReportType().equals("1")) {
                        stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
                    } else {
                        stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
                    }
                    reportData.setReviewBys(stringList);
                    //将新增行数据查询出来放入到cwProjectInfoList中
                    cwProjectInfoData = infoMapper.selectByReportId(reportData.getId());
                    if (null != cwProjectInfoData){
                        reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
                        reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
                        reportData.setReportDate(cwProjectInfoData.getReportDate());
                        reportData.setReportType(cwProjectInfoData.getReportType());
                        reportData.setReportNumber(cwProjectInfoData.getReportNumber());
                        reportData.setReportNo(cwProjectInfoData.getReportNo());
                        reportData.setSealType(cwProjectInfoData.getSealType());
                    }
                }
            }

        }

        Map data = new HashMap();


        data.put("firstAuditName","");
        data.put("firstAuditDate","    年  月  日");
        data.put("secondAuditName","");
        data.put("secondAuditDate","    年  月  日");
        data.put("thirdlyAuditName","");
        data.put("thirdlyAuditDate","    年  月  日");
        //发出人
        data.put("giveName","");
        //发出时间
        data.put("giveDate","    年  月  日");
        //归档人
        data.put("archiveName","");
        //归档时间
        data.put("archiveDate","    年  月  日");
        data.put("type","");
        data.put("projectName","");
        data.put("servedUnitName","");
        data.put("reportDate","    年  月  日");
        data.put("reportNumber","");
        data.put("totalCount","");
        data.put("giveOutCount","");
        data.put("archiveCount","");
        data.put("printName","");
        data.put("proofreadName","");
        data.put("pcNumber","");
        data.put("s114","");
        data.put("s115","");
        data.put("s214","");
        data.put("s215","");
        data.put("s314","");
        data.put("s315","");
        data.put("s111","");
        data.put("s112","");
        data.put("s113","");

        data.put("s121","");
        data.put("s122","");
        data.put("s123","");

        data.put("s131","");
        data.put("s132","");
        data.put("s133","");

        data.put("s141","");
        data.put("s142","");
        data.put("s143","");

        data.put("s151","");
        data.put("s152","");
        data.put("s153","");

        data.put("s161","");
        data.put("s162","");
        data.put("s163","");

        data.put("s171","");
        data.put("s172","");
        data.put("s173","");

        data.put("s181","");
        data.put("s182","");
        data.put("s183","");

        data.put("s191","");
        data.put("s192","");
        data.put("s193","");

        data.put("s1101","");
        data.put("s1102","");
        data.put("s1103","");

        data.put("s211","");
        data.put("s212","");
        data.put("s213","");

        data.put("s221","");
        data.put("s222","");
        data.put("s223","");

        data.put("s231","");
        data.put("s232","");
        data.put("s233","");

        data.put("s311","");
        data.put("s312","");
        data.put("s313","");

        data.put("s321","");
        data.put("s322","");
        data.put("s323","");

        data.put("s331","");
        data.put("s332","");
        data.put("s333","");

        data.put("s341","");
        data.put("s342","");
        data.put("s343","");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        try {
            if(StringUtils.isNotBlank(reportData.getProcInsId3())){



                Map dataMap = flowTaskService.historicTaskList2(reportData.getProcInsId3());
                if(null != dataMap){
                    data.putAll(dataMap);
                }
//                for (Flow flow : flows) {
//                    HistoricActivityInstance histIns = flow.getHistIns();
//                    if(StringUtils.isNotBlank(histIns.getActivityName())){
//
//                        switch (histIns.getActivityName()){
//                            case "开始":
//                                if(StringUtils.isNotBlank(flow.getAssigneeName())){
//                                    data.put("firstAuditName",flow.getAssigneeName());
//                                    data.put("giveName",flow.getAssigneeName());
//                                }else{
//                                    data.put("firstAuditName","");
//                                }
//                                if(null != histIns.getEndTime()){
//                                    data.put("firstAuditDate",sdf.format(histIns.getEndTime()));
//                                }else{
//                                    data.put("firstAuditDate","    年  月  日");
//                                }
//                                break;
//                            case "二级复核":
//                                if(null != flow.getComment() && "success".equals(flow.getComment().getLevel())){
//                                    if(StringUtils.isNotBlank(flow.getAssigneeName())){
//                                        data.put("secondAuditName",flow.getAssigneeName());
//                                    }else{
//                                        data.put("secondAuditName","");
//                                    }
//                                    if(null != histIns.getEndTime()){
//                                        data.put("secondAuditDate",sdf.format(histIns.getEndTime()));
//                                    }else{
//                                        data.put("secondAuditDate","    年  月  日");
//                                    }
//                                }
//                                break;
//                            case "三级复核":
//                                if(null != flow.getComment() && "success".equals(flow.getComment().getLevel())){
//                                    if(StringUtils.isNotBlank(flow.getAssigneeName())){
//                                        UserDTO userDTO = UserUtils.getByName("潘中");
//                                        if(null != userDTO && StringUtils.isNotBlank(userDTO.getName())){
//                                            data.put("thirdlyAuditName",userDTO.getName());
//                                        }else{
//                                            data.put("thirdlyAuditName","");
//                                        }
//                                    }else{
//                                        data.put("thirdlyAuditName","");
//                                    }
//                                    if(null != histIns.getEndTime()){
//                                        data.put("thirdlyAuditDate",sdf.format(histIns.getEndTime()));
//                                    }else{
//                                        data.put("thirdlyAuditDate","    年  月  日");
//                                    }
//                                }
//                                break;
//                        }
//                    }
//                }
                //报告类型
                String reportType = SpringUtil.getBean ( IDictApi.class ).getDictLabel(reportData.getReportType(), "cw_report_title_type", "");
//                String reportType = DictUtils.getDictLabel(reportData.getReportType(), "cw_report_title_type", "");
                if(StringUtils.isNotBlank(reportType)){
                    data.put("type",reportType);
                }else{
                    data.put("type","");
                }
                //项目名称
                if(StringUtils.isNotBlank(reportData.getProjectName())){
                    data.put("projectName",reportData.getProjectName());
                }else{
                    data.put("projectName","");
                }
                //根据项目名称查询合同委托方名称
                if(StringUtils.isNotBlank(reportData.getProjectId())){
                    String servedUnitName = reportMapper.getServedUnitName(reportData.getProjectId());
                    if(StringUtils.isNotBlank(servedUnitName)){
                        data.put("servedUnitName",servedUnitName);
                    }else{
                        data.put("servedUnitName","");
                    }
                }else{
                    data.put("servedUnitName","");
                }
                //报告日期
                if(null != reportData.getReportDate()){
                    data.put("reportDate",sdf.format(reportData.getReportDate()));
                }else{
                    data.put("reportDate","    年  月  日");
                }
                //报告文号
                if(StringUtils.isNotBlank(reportData.getReportNo())){
                    data.put("reportNumber",reportData.getReportNo());
                }else{
                    data.put("reportNumber","");
                }
                //共印份数
                if(StringUtils.isNotBlank(reportData.getAllPrintNum())){
                    data.put("totalCount",reportData.getAllPrintNum());
                }else{
                    data.put("totalCount","");
                }
                //发出份数
                if(StringUtils.isNotBlank(reportData.getIssueNum())){
                    data.put("giveOutCount",reportData.getIssueNum());
                }else{
                    data.put("giveOutCount","");
                }
                //存档份数
                if(StringUtils.isNotBlank(reportData.getPlaceOnFileNum())){
                    data.put("archiveCount",reportData.getPlaceOnFileNum());
                }else{
                    data.put("archiveCount","");
                }
                //打印人签名
                if(StringUtils.isNotBlank(reportData.getPrintedBy())){
                    data.put("printName",reportData.getPrintedBy());
                }else{
                    data.put("printName","");
                }
                //校对人签名
                if(StringUtils.isNotBlank(reportData.getCheckAutograph())){
                    data.put("proofreadName",reportData.getCheckAutograph());
                }else{
                    data.put("proofreadName","");
                }
                //计算机文号
                if(StringUtils.isNotBlank(reportData.getComputerNo())){
                    data.put("pcNumber",reportData.getComputerNo());
                }else{
                    data.put("pcNumber","");
                }
                //一级复核需提请关注或修改的事项
                if(StringUtils.isNotBlank(reportData.getNeedUpdate1())){
                    data.put("s114",reportData.getNeedUpdate1());
                }else{
                    data.put("s114","");
                }
                //一级复核备注
                if(StringUtils.isNotBlank(reportData.getRemark1())){
                    data.put("s115",reportData.getRemark1());
                }else{
                    data.put("s115","");
                }
                //二级复核需提请关注或修改的事项
                if(StringUtils.isNotBlank(reportData.getNeedUpdate2())){
                    data.put("s214",reportData.getNeedUpdate2());
                }else{
                    data.put("s214","");
                }
                //二级复核备注
                if(StringUtils.isNotBlank(reportData.getRemark2())){
                    data.put("s215",reportData.getRemark2());
                }else{
                    data.put("s215","");
                }
                //三级复核需提请关注或修改的事项
                if(StringUtils.isNotBlank(reportData.getNeedUpdate3())){
                    data.put("s314",reportData.getNeedUpdate3());
                }else{
                    data.put("s314","");
                }
                //三级复核备注
                if(StringUtils.isNotBlank(reportData.getRemark3())){
                    data.put("s315",reportData.getRemark3());
                }else{
                    data.put("s315","");
                }

                data.put("archiveName","");
                data.put("archiveDate","");
                List<CwProofreadDetail> details = reportData.getDetails();
                Map map = disposeViewList(details);
                data.putAll(map);

                if(StringUtils.isNotBlank(reportData.getReportId())){
                    //根据报告id查询归档信息
                    CwProjectReportArchiveDTO cwProjectReportArchiveDTO = cwProjectReportArchiveMapper.queryByReportId(reportData.getReportId());

                    if(null != cwProjectReportArchiveDTO){
                        if(null != cwProjectReportArchiveDTO.getAuditDate()){
                            data.put("archiveDate",sdf.format(cwProjectReportArchiveDTO.getAuditDate()));
                            data.put("giveDate",sdf.format(cwProjectReportArchiveDTO.getAuditDate()));
                        }else{
                            data.put("archiveDate","    年  月  日");
                        }
                    }

                    Map dataMap3 = flowTaskService.historicTaskList3(cwProjectReportArchiveDTO.getProcInsId());
                    data.putAll(dataMap3);
                }
            }


        }catch (Exception e){
            e.getMessage();
        }
        return data;
    }

    public Map disposeViewList(List<CwProofreadDetail> detailList){
        Map map = new HashMap();
        map.put("s111","");
        map.put("s112","");
        map.put("s113","");

        map.put("s121","");
        map.put("s122","");
        map.put("s123","");

        map.put("s131","");
        map.put("s132","");
        map.put("s133","");

        map.put("s141","");
        map.put("s142","");
        map.put("s143","");

        map.put("s151","");
        map.put("s152","");
        map.put("s153","");

        map.put("s161","");
        map.put("s162","");
        map.put("s163","");

        map.put("s171","");
        map.put("s172","");
        map.put("s173","");

        map.put("s181","");
        map.put("s182","");
        map.put("s183","");

        map.put("s191","");
        map.put("s192","");
        map.put("s193","");

        map.put("s1101","");
        map.put("s1102","");
        map.put("s1103","");

        map.put("s211","");
        map.put("s212","");
        map.put("s213","");

        map.put("s221","");
        map.put("s222","");
        map.put("s223","");

        map.put("s231","");
        map.put("s232","");
        map.put("s233","");

        map.put("s311","");
        map.put("s312","");
        map.put("s313","");

        map.put("s321","");
        map.put("s322","");
        map.put("s323","");

        map.put("s331","");
        map.put("s332","");
        map.put("s333","");

        map.put("s341","");
        map.put("s342","");
        map.put("s343","");
        if(detailList.size()>0){
            for (CwProofreadDetail info : detailList) {
                switch (info.getTypeName()){
                    case "已在现场进行技术性的逐张、详细复核且修改完善，并保证数据的正确性":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s111","√");
                                    break;
                                case "2":
                                    map.put("s112","√");
                                    break;
                                case "3":
                                    map.put("s113","√");
                                    break;
                            }
                        }
                        break;
                    case "复核后 已填列 “完成业务工作核对清单”":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s121","√");
                                    break;
                                case "2":
                                    map.put("s122","√");
                                    break;
                                case "3":
                                    map.put("s123","√");
                                    break;
                            }
                        }
                        break;
                    case "重要审验程序是否适当，是否得以较好地实施，是否实现了审验目标":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s131","√");
                                    break;
                                case "2":
                                    map.put("s132","√");
                                    break;
                                case "3":
                                    map.put("s133","√");
                                    break;
                            }
                        }
                        break;
                    case "重点审验项目的证据是否充分、适当":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s141","√");
                                    break;
                                case "2":
                                    map.put("s142","√");
                                    break;
                                case "3":
                                    map.put("s143","√");
                                    break;
                            }
                        }
                        break;
                    case "审验范围是否充分":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s151","√");
                                    break;
                                case "2":
                                    map.put("s152","√");
                                    break;
                                case "3":
                                    map.put("s153","√");
                                    break;
                            }
                        }
                        break;
                    case "建议调整的不符事项和未调整不符事项的处理是否恰当":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s161","√");
                                    break;
                                case "2":
                                    map.put("s162","√");
                                    break;
                                case "3":
                                    map.put("s163","√");
                                    break;
                            }
                        }
                        break;
                    case "工作底稿中重要的勾稽关系是否正确":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s171","√");
                                    break;
                                case "2":
                                    map.put("s172","√");
                                    break;
                                case "3":
                                    map.put("s173","√");
                                    break;
                            }
                        }
                        break;
                    case "执业过程中发现的问题及其对会计报表和业务报告的影响，项目组对这些问题的处理是否恰当":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s181","√");
                                    break;
                                case "2":
                                    map.put("s182","√");
                                    break;
                                case "3":
                                    map.put("s183","√");
                                    break;
                            }
                        }
                        break;
                    case "已审会计报表总体上是否合理、可信":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s191","√");
                                    break;
                                case "2":
                                    map.put("s192","√");
                                    break;
                                case "3":
                                    map.put("s193","√");
                                    break;
                            }
                        }
                        break;
                    case "校对业务报告及附送资料的文字表述无误":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s1101","√");
                                    break;
                                case "2":
                                    map.put("s1102","√");
                                    break;
                                case "3":
                                    map.put("s1103","√");
                                    break;
                            }
                        }
                        break;

                    case "对审验过程中的重大会计审计问题，重大调整事项及重要的工作底稿进行复核无误":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s211","√");
                                    break;
                                case "2":
                                    map.put("s212","√");
                                    break;
                                case "3":
                                    map.put("s213","√");
                                    break;
                            }
                        }
                        break;
                    case "对前两级复核人所认同的事项提出质疑":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s221","√");
                                    break;
                                case "2":
                                    map.put("s222","√");
                                    break;
                                case "3":
                                    map.put("s223","√");
                                    break;
                            }
                        }
                        break;
                    case "与项目组沟通，能以所收集的证据来证明其所根据具体的审验环境和审验证据得出的结论和意见是恰当的":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s231","√");
                                    break;
                                case "2":
                                    map.put("s232","√");
                                    break;
                                case "3":
                                    map.put("s233","√");
                                    break;
                            }
                        }
                        break;

                    case "审验程序的恰当性":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s311","√");
                                    break;
                                case "2":
                                    map.put("s312","√");
                                    break;
                                case "3":
                                    map.put("s313","√");
                                    break;
                            }
                        }
                        break;
                    case "工作底稿的充分性":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s321","√");
                                    break;
                                case "2":
                                    map.put("s322","√");
                                    break;
                                case "3":
                                    map.put("s323","√");
                                    break;
                            }
                        }
                        break;
                    case "审验过程中是否存在重大遗漏":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s331","√");
                                    break;
                                case "2":
                                    map.put("s332","√");
                                    break;
                                case "3":
                                    map.put("s333","√");
                                    break;
                            }
                        }
                        break;
                    case "审验工作是否符合的质量要求":
                        if(StringUtils.isNotBlank(info.getReviewComments())){
                            switch (info.getReviewComments()){
                                case "1":
                                    map.put("s341","√");
                                    break;
                                case "2":
                                    map.put("s342","√");
                                    break;
                                case "3":
                                    map.put("s343","√");
                                    break;
                            }
                        }
                        break;
                }
            }
        }
        return map;
    }

    public ResponseEntity deleteByIds(String ids) {
        String idArray[] =ids.split(",");
        //删除 cw_project_report_new_line表信息  cw_project_report_file信息  work_attachment_id表信息
        //先根据ids找到cw_project_report_new_line表的id，根据id去work_attachment_id表中查出id信息删除cw_project_report_file信息
        CwProjectInfoData infoData = infoMapper.selectIdByReportId(ids);
        if (null != infoData ){
            //将report_no放入到cw_project_report_cancel报废表中
            CwProjectReportCancel cancel = new CwProjectReportCancel();
            cancel.setId(UUID.randomUUID().toString().replace("-", ""));
            cancel.setReportNo(infoData.getReportNo());
            cancelMapper.insert(cancel);
            //删除被服务单位信息
            infoMapper.deleteById(infoData.getId());
            //查询保存的附件信息
            List<WorkAttachmentInfo> infoList = reportMapper.findFileList(ids);
            //删除附件信息
            infoList.forEach(in->{
                //删除新建行文件表id
                List<String> fileId = attachmentMapper.getFileId(in.getId());
                fileId.forEach(fid->{
                    attachmentMapper.deleteById(fid);
                });
//                ossServiceMapper.deleteById(in.getId());
                SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(in.getId());
            });

            /*idList.forEach(info->{
                List<String> attachmentId = attachmentMapper.getIdByAttachmentId(info.getId());
                //根据这个id删除cw_project_report_file信息
                attachmentId.forEach(atId->{
                    attachmentMapper.deleteByRepotyId(atId);
                });
                //删除work_attachment_id信息
                attachmentMapper.deleteByAttachMnentId(info.getId());
                //删除cw_project_report_new_line表信息
                //删除前先将report_no放入到cw_project_report_cancel报废表中
                if (StringUtils.isNotEmpty(info.getReportNo())){
                    CwProjectReportCancel cancel = new CwProjectReportCancel();
                    cancel.setId(UUID.randomUUID().toString().replace("-", ""));
                    cancel.setReportNo(info.getReportNo());
                    cancelMapper.insert(cancel);
                }
                infoMapper.deleteById(info.getId());
            });*/
        }
        this.removeByIds (Lists.newArrayList (idArray));
        return ResponseEntity.ok ("删除成功");
    }

    public IPage<CwWorkClientBaseDTO> findClineList(Page<CwWorkClientBaseDTO> page, CwWorkClientBaseDTO cwWorkClientBaseDTO, String projectId) throws Exception{
        QueryWrapper<CwWorkClientBase> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( CwWorkClientBaseWrapper.INSTANCE.toEntity(cwWorkClientBaseDTO), CwWorkClientBase.class );
        queryWrapper.eq("cw_wcb.del_flag","0");
        queryWrapper.eq("cw_pro.id",projectId);

        if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO)) {
            if (ArrayUtil.isNotEmpty(cwWorkClientBaseDTO.getCreateDates())) {
                queryWrapper.between("cw_wcb.create_time", cwWorkClientBaseDTO.getCreateDates()[0], cwWorkClientBaseDTO.getCreateDates()[1]);
            }
            if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO.getCwWorkClientTypeDTO())){
                if (StringUtils.isNotBlank(cwWorkClientBaseDTO.getCwWorkClientTypeDTO().getOwnershipType())) {
                    queryWrapper.eq("cw_wct.ownership_type",cwWorkClientBaseDTO.getCwWorkClientTypeDTO().getOwnershipType());
                }
            }
        }
        if (StringUtils.isNotEmpty(cwWorkClientBaseDTO.getName())){
            queryWrapper.like("cw_wcb.name", cwWorkClientBaseDTO.getName());
        }
        if (StringUtils.isNotEmpty(cwWorkClientBaseDTO.getNo())){
            queryWrapper.like("cw_wcb.no", cwWorkClientBaseDTO.getNo());
        }
        queryWrapper.orderByDesc("cw_wcb.create_time");
        IPage<CwWorkClientBaseDTO> list = reportMapper.findClineList(page, queryWrapper);
        return list;
    }

    /**
     * 生成并保存签章contractId 信息
     * @param projectReportData
     * @return
     */
    public Map<String,Object> createSignatureContractId(CwProjectReportData projectReportData){
        Map<String,Object> map = new HashMap<String,Object>();
        //查询报告文件信息（电子章）
        //List<WorkAttachmentInfo> fileList = attachmentMapper.selectWorkAttachmentByReportId(projectReportData.getId());
        List<WorkAttachmentInfo> fileList = SpringUtil.getBean ( IWorkAttachmentApi.class ).selectWorkAttachmentByAttachmentId(projectReportData.getId());
        if(fileList.size()>0){

            //下载审定单文件
            String path = null;
            if(System.getProperty("os.name").toLowerCase().contains("win")){
                path = "D:/attachment-file/";
            }else{
                path = "/attachment-file/";
            }
            String aliyunUrl = "http://cdn.gangwaninfo.com";
            String aliDownloadUrl = "http://oss.gangwaninfo.com";

            //获取文件生成的documentId
            List<String> documentList = Lists.newArrayList();

            for (WorkAttachmentInfo workattachment : fileList) {
                String deleteFile = null;
                try{
                    if(StringUtils.isBlank(workattachment.getUrl())){
                        map.put("success",false);
                        map.put("message","审定单文件存储路径为空，无法进行签章操作，请驳回后重新上传审定单");
                        return map;
                    }

                    String file = aliyunUrl + workattachment.getUrl();
                    file = file.replace("amp;","");
                    String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
                    String cons = "";
                    if (file.contains(aliyunUrl)){
                        cons = aliyunUrl;
                    }else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
                        cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
                    }else {
                        cons = aliDownloadUrl;
                    }
                    String ossKey = file.split(cons+"/")[1];
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).downByStreamSaveLocal(ossKey,fileName,path+fileName);
//                    ossClientService.downByStreamSaveLocal(ossKey,fileName,path+fileName);
                    //将下载下来的文件转换为file文件
                    File srcFile = new File(path+fileName);
                    deleteFile = path+fileName;

                    //截取文件名称
                    String srcFileName = srcFile.getName().substring(0,srcFile.getName().lastIndexOf("."));
                    //截取文件后缀名
                    String substring = srcFile.getName().substring(srcFile.getName().lastIndexOf(".")+1, srcFile.getName().length());
                    if(!"doc".equals(substring.toLowerCase()) && !"docx".equals(substring.toLowerCase()) && !"pdf".equals(substring.toLowerCase())){
                        map.put("success",false);
                        map.put("message","请上传doc、docx或者pdf的文件进行签章操作");
                        return map;
                    }
                    //获取真签单的documentId
                    HashMap hashMap = new SignaturePostUtil().getDocument(srcFile);
                    String code = hashMap.get("code").toString();
                    String documentId = "";
                    if("0".equals(code)){
                        String result = hashMap.get("result").toString();
                        HashMap documentIdMap = JSON.parseObject(result, HashMap.class);
                        documentId =  documentIdMap.get("documentId").toString();
                        if("".equals(documentId)){
                            map.put("success",false);
                            map.put("message","签章文件创建失败");
                            return map;
                        }
                    }else{
                        String message = hashMap.get("message").toString();
                        map.put("success",false);
                        map.put("message",message);
                        return map;
                    }

                    documentList.add(documentId);

                }catch (Exception e){

                }finally {
                    if(StringUtils.isNotBlank(deleteFile)){
                        //根据路径创建文件对象
                        File file = new File(deleteFile);
                        //路径是个文件且不为空时删除文件
                        if(file.isFile()&&file.exists()){
                            file.delete();
                        }
                    }
                }

            }


            //将documentId存入数据库中
            projectReportData.setSignatureDocumentId(String.join(",", documentList));
            //根据项目id 和 documentId生成合同id
            HashMap contractIdHashMap = this.getSignatureContractIdByPageSign(projectReportData.getId(), documentList);
            String contractIdCode = contractIdHashMap.get("code").toString();
            String contractId = "";
            if("0".equals(contractIdCode)){
                contractId = contractIdHashMap.get("contractId").toString();
                if("".equals(contractId)){
                    map.put("success",false);
                    map.put("message","签章文件创建失败");
                    return map;
                }
                projectReportData.setSignatureContractId(contractId);
                this.updateSignatureInfo(projectReportData);
//                map.put("contractId",contractId);
                //修改签章对应信息文件
                //contractUrl = ruralProjectMessageService.getSignatureContractUrl(contractId);
                //System.out.println(contractUrl);

            }else{
                map.put("success",false);
                map.put("message",contractIdHashMap.get("message").toString());
                return map;
            }

        }else{
            map.put("success",false);
            map.put("message","审定单文件未找到，无法进行签章操作");
            return map;
        }
        map.put("success",true);
        map.put("message","生成签章contractId成功");
        return map;
    }

    /**
     * 根据项目报告id 和 documentId生成合同id(页面签署生成)
     * 个人签字章功能
     * @param projectReportDataId
     * @param documentList
     * @return
     */
    public HashMap getSignatureContractIdByPageSign(String projectReportDataId, List<String> documentList){
        HashMap hashMap = new HashMap();
        Set<String> serialIdSet = new HashSet<>();
        //根据项目id查询项目信息
        CwProjectReportData projectReportData = reportMapper.queryById(projectReportDataId);
        //创建签署方信息
        List<Action> actions = Lists.newArrayList();
        Action companyAction = new Action();
        companyAction.setType("CORPORATE");
        companyAction.setName("公司印章");
        if(StringUtils.isNotBlank(projectReportData.getSignatureType()) && "2".equals(projectReportData.getSignatureType())){
            companyAction.setSerialNo("3");
        }else{
            companyAction.setSerialNo("1");
        }
        //公司圆章-竖
        //serialIdSet.add(COMPANYROUNDSEALIDVERTICAL);
        //添加盖章位置
        List<Location> locations = Lists.newArrayList();
        /*for (String documentId: documentList) {
            Location location = new Location();
            location.setSealId(COMPANYROUNDSEALIDVERTICAL);
            location.setDocumentId(documentId);
            location.setPage("0");
            location.setRectType("SEAL_CORPORATE");
            location.setKeywordIndex(-1);
            location.setOffsetX("0.5264");
            location.setOffsetY("0.6787");
            locations.add(location);
        }*/

        //根据角色信息录入签署方信息
        //负责人
        List<UserDTO> userInfoByRoleNameList = SpringUtil.getBean(IUserApi.class).getUserInfoByEnName("qzglr");
//        List<UserDTO> userInfoByRoleNameList = userService.getUserInfoByEnName("qzglr");
        if(userInfoByRoleNameList.size()>0){

            UserDTO user = SpringUtil.getBean ( IUserApi.class ).getById(userInfoByRoleNameList.get(0).getId());

            if(null != user){
                //获取成员印章id信息
                long s1=System.currentTimeMillis();
                String userSealId = SignaturePostUtil.getUserSealByMobile(user.getMobile(),"","江苏兴光会计事务所公章");
                long s2=System.currentTimeMillis();
                System.out.println("第二个人员印章获取时间：" + (s2 - s1));

                if(StringUtils.isNotBlank(userSealId)){
                    for (String documentId: documentList) {
                        //添加盖章位置
                        Location principalLocation = new Location();
                        serialIdSet.add(userSealId);
                        principalLocation.setSealId(userSealId);
                        principalLocation.setDocumentId(documentId);
                        principalLocation.setPage("0");
                        principalLocation.setRectType("SEAL_CORPORATE");
                        principalLocation.setKeywordIndex(-1);
                        principalLocation.setOffsetX("0.7758");
                        principalLocation.setOffsetY("0.7339");
                        locations.add(principalLocation);
                    }

                }else{
                    hashMap.put("code","2");
                    hashMap.put("message","查询不到江苏兴光会计事务所公章 的印章信息！请联系管理员");
                    return hashMap;
                }
            }else{
                hashMap.put("code","2");
                hashMap.put("message","查询不到江苏兴光会计事务所公章 的印章信息！请联系管理员");
                return hashMap;
            }
        }else{
            hashMap.put("code","2");
            hashMap.put("message","查询不到公章盖章人员信息！请联系管理员");
            return hashMap;
        }

        List<String> serialIdList = new ArrayList<String>(serialIdSet);
        companyAction.setSealIds("[" + String.join(",", serialIdList) + "]");
        //判定该action是否采用自动签署
        companyAction.setAutoSign("false");
        companyAction.setLocations(locations);
        actions.add(companyAction);

        // 根据签章类型判断签章人员信息（即是否添加执业章签章）
        // 签章类型 1：公章；2：公章+执业章
        if(StringUtils.isNotBlank(projectReportData.getSignatureType()) && "2".equals(projectReportData.getSignatureType())){
            //判定签字注师1参数是否为空
            if(StringUtils.isNotBlank(projectReportData.getSignatureAnnotator1())){
                UserDTO signatureAnnotator1 = SpringUtil.getBean ( IUserApi.class ).getById(projectReportData.getSignatureAnnotator1());
                if(null != signatureAnnotator1){

                    //创建个人职业章参数（签字注师1）
                    Action professionalChapterAction = new Action();
                    professionalChapterAction.setType("PRACTICE");
                    professionalChapterAction.setName(signatureAnnotator1.getName() + "个人职业章");
                    professionalChapterAction.setSerialNo("1");

                    //添加盖章位置
                    List<Location> professionalChapterLocations = Lists.newArrayList();

                    Set<String> professionalChapterSerialIdSet = new HashSet<>();

                    //添加个人职业章人员信息
                    ActionOperatorInfo actionOperatorInfo = new ActionOperatorInfo();
                    actionOperatorInfo.setOperatorContact(signatureAnnotator1.getMobile());//个人职业章盖章人的手机号
                    List<ActionOperatorInfo> actionOperators = Lists.newArrayList();
                    actionOperators.add(actionOperatorInfo);
                    professionalChapterAction.setActionOperators(actionOperators);

                    //获取成员印章id信息
                    long s1=System.currentTimeMillis();
                    String userSealId = SignaturePostUtil.getUserSealByMobile(signatureAnnotator1.getMobile(),"",signatureAnnotator1.getName() + "个人签名");
                    long s2=System.currentTimeMillis();
                    System.out.println("第三个人员印章获取时间：" + (s2 - s1));
                    if(StringUtils.isNotBlank(userSealId)){
                    }else{
                        hashMap.put("code","2");
                        hashMap.put("message","查询不到签字注师1 的印章信息！请联系管理员");
                        return hashMap;
                    }

                    List<String> serialIdsList = new ArrayList<String>(professionalChapterSerialIdSet);
                    professionalChapterAction.setSealIds("[" + String.join(",", serialIdsList) + "]");
                    professionalChapterAction.setLocations(professionalChapterLocations);
                    net.sf.json.JSONObject professionalChapterJson = net.sf.json.JSONObject.fromObject(professionalChapterAction);
                    System.out.println(professionalChapterJson.toString());
                    actions.add(professionalChapterAction);
                }else{
                    hashMap.put("code","2");
                    hashMap.put("message","查询不到签字注师1 的印章信息！请联系管理员");
                    return hashMap;
                }
            }else{
                hashMap.put("code","2");
                hashMap.put("message","查询不到签字注师1 的印章信息！请联系管理员");
                return hashMap;
            }

            //判定签字注师1参数是否为空
            if(StringUtils.isNotBlank(projectReportData.getSignatureAnnotator1())){
                UserDTO signatureAnnotator2 = SpringUtil.getBean ( IUserApi.class ).getById(projectReportData.getSignatureAnnotator2());
                if(null != signatureAnnotator2){

                    //创建个人职业章参数（签字注师1）
                    Action professionalChapterAction = new Action();
                    professionalChapterAction.setType("PRACTICE");
                    professionalChapterAction.setName(signatureAnnotator2.getName() + "个人职业章");
                    professionalChapterAction.setSerialNo("2");

                    //添加盖章位置
                    List<Location> professionalChapterLocations = Lists.newArrayList();

                    Set<String> professionalChapterSerialIdSet = new HashSet<>();

                    //添加个人职业章人员信息
                    ActionOperatorInfo actionOperatorInfo = new ActionOperatorInfo();
                    actionOperatorInfo.setOperatorContact(signatureAnnotator2.getMobile());//个人职业章盖章人的手机号
                    List<ActionOperatorInfo> actionOperators = Lists.newArrayList();
                    actionOperators.add(actionOperatorInfo);
                    professionalChapterAction.setActionOperators(actionOperators);

                    //获取成员印章id信息
                    long s1=System.currentTimeMillis();
                    String userSealId = SignaturePostUtil.getUserSealByMobile(signatureAnnotator2.getMobile(),"",signatureAnnotator2.getName() + "个人签名");
                    long s2=System.currentTimeMillis();
                    System.out.println("第三个人员印章获取时间：" + (s2 - s1));
                    if(StringUtils.isNotBlank(userSealId)){
                    }else{
                        hashMap.put("code","2");
                        hashMap.put("message","查询不到签字注师2 的印章信息！请联系管理员");
                        return hashMap;
                    }

                    List<String> serialIdsList = new ArrayList<String>(professionalChapterSerialIdSet);
                    professionalChapterAction.setSealIds("[" + String.join(",", serialIdsList) + "]");
                    professionalChapterAction.setLocations(professionalChapterLocations);
                    net.sf.json.JSONObject professionalChapterJson = net.sf.json.JSONObject.fromObject(professionalChapterAction);
                    System.out.println(professionalChapterJson.toString());
                    actions.add(professionalChapterAction);
                }else{
                    hashMap.put("code","2");
                    hashMap.put("message","查询不到签字注师2 的印章信息！请联系管理员");
                    return hashMap;
                }
            }else{
                hashMap.put("code","2");
                hashMap.put("message","查询不到签字注师2 的印章信息！请联系管理员");
                return hashMap;
            }
        }



        //创建签署方信息表
        List<SignatorieInfo> signatories = Lists.newArrayList();
        SignatorieInfo signatorieInfo1 = new SignatorieInfo();
        signatorieInfo1.setSerialNo("1");
        signatorieInfo1.setTenantName("江苏兴光项目管理有限公司");
        signatorieInfo1.setTenantType("COMPANY");
        signatorieInfo1.setActions(actions);
        signatories.add(signatorieInfo1);
        SignatureContract signatureContract = new SignatureContract();
        signatureContract.setDocuments(documentList);
        //审定单用印流程id
        signatureContract.setCategoryId(APPROVALCATEGORYID);
        signatureContract.setSend(true);
        signatureContract.setSignatories(signatories);
        signatureContract.setSn("");
        signatureContract.setSubject(projectReportData.getProjectName());//添加项目名称
        net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(signatureContract);
        System.out.println(json.toString());
        long s5=System.currentTimeMillis();
        System.out.println(json.toString());
        String contractIdMapStr = SignaturePostUtil.sendPostApplicationJson(HTTPTOP + "/contract/createbycategory", json.toString());
        long s6=System.currentTimeMillis();
        System.out.println("获取合同id获取时间：" + (s6 - s5));
        hashMap = JSON.parseObject(contractIdMapStr, HashMap.class);

        return hashMap;
    }

    public CwProjectReportData queryBySignatureId(String signatureId) {
        CwProjectReportSignature cwProjectReportSignature = cwProjectReportSignatureMapper.getInfoById(signatureId);
        if (ObjectUtil.isNotEmpty(cwProjectReportSignature)){
            if (StringUtils.isNotBlank(cwProjectReportSignature.getReportId())){
                return this.queryById(cwProjectReportSignature.getReportId());
            }
        }
        return new CwProjectReportData();
    }

    public CwProjectReportSignature findBySignatureId(String signatureId) {
        return cwProjectReportSignatureMapper.getInfoById(signatureId);
    }

    public String updateSignatureStatusById(CwProjectReportSignatureDTO data) {
        CwProjectReportSignature cwProjectReportSignature = new CwProjectReportSignature();
        cwProjectReportSignature.setId(data.getId());
        cwProjectReportSignature.setStatus(data.getStatus());
        //用于驳回后状态改变
        if("4".equals(data.getStatus()) || "0".equals(data.getStatus())){
            cwProjectReportSignature.setSignatureAnnotator1Status("0");
            cwProjectReportSignature.setSignatureAnnotator2Status("0");
            cwProjectReportSignature.setSealAdminStatus("0");
        }
        //判断是否是撤回签章
        if ("3".equals(data.getStatus())){
            //获取当前登录人角色是否是苏州报告签字盖章代办
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
                for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                    RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                    if ("szbgqzgzdb".equals(dtoById.getEnName())){
                        //根据id查询procInsId
                        CwProjectReportSignature signature = this.findBySignatureId(data.getId());
                        if (ObjectUtil.isNotEmpty(signature)){
                            //根据procInsId查找taskId
                            String taskIdByprocInstId = flowTaskService.getTaskIdByprocInstId(signature.getProcInsId());
                            //根据taskid将通知表中的该条记录进行删除
                            cwProjectReportSignatureMapper.deleteByTaskId(taskIdByprocInstId);
                        }
                    }
                }
            }
        }
        cwProjectReportSignatureMapper.updateInfoById(cwProjectReportSignature);



        return "操作成功";
    }

    public String getSignature (CwProjectReportData cwProjectReportData){
        CwProjectReportData cwProjectReportData1 = this.queryById(cwProjectReportData.getId());
        String signatureType = cwProjectReportData.getSignatureType();
        CwProjectReportSignature cwProjectReportSignature = cwProjectReportSignatureMapper.selectOne(new QueryWrapper<CwProjectReportSignature>().lambda()
                .eq(CwProjectReportSignature::getReportId, cwProjectReportData.getId())
                .eq(CwProjectReportSignature::getType, signatureType)
        );
        cwProjectReportSignature.setStatus("2");
        cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
        //修改盖章类型
        reportMapper.updateSignatureTypeById(cwProjectReportData);
        return cwProjectReportSignature.getId();
    }

    /**
     * 将签章表中的流程状态调整为已完成状态
     * @param cwProjectReportData
     * @return
     */
    public String modifySignatureStatus (CwProjectReportData cwProjectReportData,String status){
        String signatureType = cwProjectReportData.getSignatureType();
        CwProjectReportSignature cwProjectReportSignature = cwProjectReportSignatureMapper.selectOne(new QueryWrapper<CwProjectReportSignature>().lambda()
                .eq(CwProjectReportSignature::getReportId, cwProjectReportData.getId())
                .eq(CwProjectReportSignature::getType, signatureType)
        );
        cwProjectReportSignature.setStatus(status);
        if("4".equals(status)){
            cwProjectReportSignature.setSealAdminStatus("0");
            cwProjectReportSignature.setSignatureAnnotator1Status("0");
            cwProjectReportSignature.setSignatureAnnotator2Status("0");
        }
        cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
        return cwProjectReportSignature.getId();
    }

    public CwProjectReportData queryByContractId(String contractId){
        CwProjectReportData reportData = reportMapper.queryByContractId(contractId);
        return reportData;
    }


    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<ProjectReportWorkAttachmentDTO> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (ProjectReportWorkAttachmentDTO dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = reportMapper.findFileList(id);
        if (CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                    List<String> fileId = attachmentMapper.getFileId(i.getId());
                    fileId.forEach(fid->{
                        attachmentMapper.deleteById(fid);
                    });
                }
            }
        }
        //保存信息
        for (ProjectReportWorkAttachmentDTO dto : list) {
            //判断是否存在
            Integer isExit = reportMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
                i.setCreateById(userDTO.getId());
                i.setCreateTime(new Date());
                i.setUpdateById(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);
//                ossServiceMapper.insertWorkAttachment(i, userDTO);

                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);

                CwProjectReportFile reportFile = new CwProjectReportFile();
                BeanUtils.copyProperties(dto, reportFile);
                reportFile.setReportFileId(i.getId());
                attachmentMapper.insert(reportFile);
                j++;
            } else {
                attachmentMapper.updateFileInfo(dto);
            }
        }
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSignatureFiles(List<ProjectReportWorkAttachmentDTO> list, UserDTO userDTO, String id) {
        System.out.println("进入service1");
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (ProjectReportWorkAttachmentDTO dto : list) {
            names = names + "," +dto.getUrl();
        }
        System.out.println("进入service2");
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = reportMapper.findFileListOnAttachmentFlag(id,"cw_project_report_file_signature");
        System.out.println("进入service3");
        if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
//                    ossServiceMapper.deleteById(i.getId());
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                    List<String> fileId = attachmentMapper.getFileId(i.getId());
                    fileId.forEach(fid->{
                        attachmentMapper.deleteById(fid);
                    });

                }
            }
        }
        System.out.println("进入service4");
        reportMapper.deleteAttachement(id,"cwReportSignature");
        System.out.println("进入service5");
        //保存信息
        for (ProjectReportWorkAttachmentDTO dto : list) {
            WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
                if(infoList.size()>0){
                    userDTO = SpringUtil.getBean ( IUserApi.class ).getById(infoList.get(0).getCreateById());
                    i.setCreateTime(infoList.get(0).getCreateTime());
                    i.setUpdateTime(infoList.get(0).getUpdateTime());
                }else{
                    i.setCreateById(userDTO.getId());
                    i.setUpdateById(userDTO.getId());
                    i.setCreateTime(new Date());
                    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("cwReportSignature");
                i.setFileSize(dto.getSize());
                i.setSort(j);
//                ossServiceMapper.insertWorkAttachment(i, userDTO);

                /*Map<String,String> map = new HashMap<>();
                String workAttachment = JSON.toJSONString((i));
                String userDTOInfo = JSON.toJSONString((userDTO));
                map.put("workAttachment",workAttachment);
                map.put("userDTO",userDTOInfo);*/
                //附件信息保存
                attachmentMapper.insertWorkAttachment(i,userDTO);
                //SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);

                CwProjectReportFile reportFile = new CwProjectReportFile();
                BeanUtils.copyProperties(dto, reportFile);
                reportFile.setReportFileId(i.getId());
                if(infoList.size()>0){
                    reportFile.setCreateById(infoList.get(0).getCreateById());
                    reportFile.setUpdateById(infoList.get(0).getUpdateById());
                    reportFile.setCreateTime(infoList.get(0).getCreateTime());
                    reportFile.setUpdateTime(infoList.get(0).getUpdateTime());
                }
                attachmentMapper.insert(reportFile);
                j++;
        }
        System.out.println("进入service6");
    }

    /**
     * 根据报告签章id查询签章审核节点信息
     * @param
     * @return
     */
    public Map<String,Object> getAuditNodeByReportId(String id){
        Map<String,Object> map = new HashMap<>();
        //查询流程id
        String processInstanceId = reportMapper.getProcessInstanceIdById(id);
        if(StringUtils.isNotBlank(processInstanceId)){
            //根据流程id查询流程当前节点信息
            String currentTask = flowTaskService.getCurrentTaskName(processInstanceId);
            if(StringUtils.isNotEmpty(currentTask)){
                map.put("success", true);
                map.put("message", "获取签章流程成功");
                map.put("signatureType", currentTask);
            }else{
                map.put("success", false);
                map.put("message", "获取签章流程失败");
                map.put("signatureType", "");
            }
        }else{
            map.put("success", false);
            map.put("message", "获取签章流程失败");
            map.put("signatureType", "");
        }

        return map;
    }

    /**
     * 修改签章流程节点状态
     * @param reportSignature
     */
    public void updateSignatureType(CwProjectReportSignature reportSignature){
        reportMapper.updateSignatureType(reportSignature);
    }

    /**
     * 根据签章节点获取签章状态数据信息
     * @param id
     * @param signatureType
     * @return
     */
    public Map<String,Object> getSignatureTypeById(String id,String signatureType){
        Map<String,Object> map = new HashMap<>();
        CwProjectReportSignature reportSignatureInfo = reportMapper.getReportSignatureById(id);
        if(null != reportSignatureInfo){
            switch (signatureType){
                case "签字注师1审核":
                    map.put("signatureType", reportSignatureInfo.getSignatureAnnotator1Status());
                    break;
                case "签字注师2审核":
                    map.put("signatureType", reportSignatureInfo.getSignatureAnnotator2Status());
                    break;
                case "签章管理员审核":
                case "三级复核及签章":
                    map.put("signatureType", reportSignatureInfo.getSealAdminStatus());
                    break;
            }
            map.put("success", true);
            map.put("message", "获取签章完成情况成功");
        }else{
            map.put("success", false);
            map.put("message", "获取签章完成情况失败");
            map.put("signatureType", "0");
        }
        return map;
    }

    /**
     * 新增签章附件信息
     * @param cwProjectReportFile
     */
    public void insertProjectReportFile(CwProjectReportFile cwProjectReportFile){
        reportMapper.insertProjectReportFile(cwProjectReportFile);
    }

    public List<CwProjectReport> getIdByProjectId(String projectId, CwProjectReport cwProjectReport) throws Exception{
        if(StringUtils.isNotBlank(projectId)){
            List<String> idByProjectId = reportMapper.getIdByProjectId(projectId);
            if (CollectionUtil.isNotEmpty(idByProjectId)){
                QueryWrapper<CwProjectReport> queryWrapper = new QueryWrapper<>();
                if (ObjectUtil.isNotEmpty(cwProjectReport)) {
                    if (StringUtils.isNotBlank(cwProjectReport.getReportNo())) {
                        queryWrapper.like("cw_prnl.report_no", cwProjectReport.getReportNo());
                    }
                    if (StringUtils.isNotBlank(cwProjectReport.getProjectName())) {
                        queryWrapper.like("cw_pro.project_name", cwProjectReport.getProjectName());
                    }
                    if (StringUtils.isNotBlank(cwProjectReport.getProjectNumber())) {
                        queryWrapper.like("cw_pro.project_number", cwProjectReport.getProjectNumber());
                    }
                }
                queryWrapper.in("cw_pr.id", idByProjectId);
                queryWrapper.eq("cw_pr.del_flag","0");
                queryWrapper.eq("cw_pr.status","5"); // 报告申请流程已通过
                queryWrapper.orderByDesc("cw_pr.create_time");
                return reportMapper.getByIds(queryWrapper);
            }
        }
        return new ArrayList<>();
    }

    public List<CwProjectReport> getIdByProjectId2(String projectId, CwProjectReport cwProjectReport) throws Exception{
        if(StringUtils.isNotBlank(projectId)){
            List<String> idByProjectId = reportMapper.getIdByProjectId(projectId);
            if (CollectionUtil.isNotEmpty(idByProjectId)){
                QueryWrapper<CwProjectReport> queryWrapper = new QueryWrapper<>();
                if (ObjectUtil.isNotEmpty(cwProjectReport)) {
                    if (StringUtils.isNotBlank(cwProjectReport.getReportNo())) {
                        queryWrapper.like("cw_prnl.report_no", cwProjectReport.getReportNo());
                    }
                    if (StringUtils.isNotBlank(cwProjectReport.getProjectName())) {
                        queryWrapper.like("cw_pro.project_name", cwProjectReport.getProjectName());
                    }
                    if (StringUtils.isNotBlank(cwProjectReport.getProjectNumber())) {
                        queryWrapper.like("cw_pro.project_number", cwProjectReport.getProjectNumber());
                    }
                }
                queryWrapper.in("cw_pr.id", idByProjectId);
                queryWrapper.eq("cw_pr.del_flag","0");
                queryWrapper.orderByDesc("cw_pr.create_time");
                return reportMapper.getByIds(queryWrapper);
            }
        }
        return new ArrayList<>();
    }

    public List<CwProjectReport> getIdByClientId(String clientId, CwProjectReport cwProjectReport) throws Exception{
        if(StringUtils.isNotBlank(clientId)){
            List<String> idByClientId = reportMapper.getIdByClientId(clientId);
            if (CollectionUtil.isNotEmpty(idByClientId)){
                QueryWrapper<CwProjectReport> queryWrapper = new QueryWrapper<>();
                if (ObjectUtil.isNotEmpty(cwProjectReport)) {
                    if (StringUtils.isNotBlank(cwProjectReport.getReportNo())) {
                        queryWrapper.like("cw_prnl.report_no", cwProjectReport.getReportNo());
                    }
                    if (StringUtils.isNotBlank(cwProjectReport.getProjectName())) {
                        queryWrapper.like("cw_pro.project_name", cwProjectReport.getProjectName());
                    }
                    if (StringUtils.isNotBlank(cwProjectReport.getProjectNumber())) {
                        queryWrapper.like("cw_pro.project_number", cwProjectReport.getProjectNumber());
                    }
                }
                queryWrapper.in("cw_pr.id", idByClientId);
                queryWrapper.eq("cw_pr.del_flag","0");
                queryWrapper.eq("cw_pr.status","5"); // 报告申请流程已通过
                queryWrapper.orderByDesc("cw_pr.create_time");
                return reportMapper.getByIds(queryWrapper);
            }
        }
        return new ArrayList<>();
    }

    public List<CwProjectReport> getIdByContractId(String contractId, CwProjectReport cwProjectReport) throws Exception{
        if(StringUtils.isNotBlank(contractId)){
            List<String> idByContractId = reportMapper.getIdByContractId(contractId);
            if (CollectionUtil.isNotEmpty(idByContractId)){
                QueryWrapper<CwProjectReport> queryWrapper = new QueryWrapper<>();
                if (ObjectUtil.isNotEmpty(cwProjectReport)) {
                    if (StringUtils.isNotBlank(cwProjectReport.getReportNo())) {
                        queryWrapper.like("cw_prnl.report_no", cwProjectReport.getReportNo());
                    }
                    if (StringUtils.isNotBlank(cwProjectReport.getProjectName())) {
                        queryWrapper.like("cw_pro.project_name", cwProjectReport.getProjectName());
                    }
                    if (StringUtils.isNotBlank(cwProjectReport.getProjectNumber())) {
                        queryWrapper.like("cw_pro.project_number", cwProjectReport.getProjectNumber());
                    }
                }
                queryWrapper.in("cw_pr.id", idByContractId);
                queryWrapper.eq("cw_pr.del_flag","0");
                queryWrapper.eq("cw_pr.status","5"); // 报告申请流程已通过
                queryWrapper.orderByDesc("cw_pr.create_time");
                return reportMapper.getByIds(queryWrapper);
            }
        }
        return new ArrayList<>();
    }

    public void saveReportArchive (String reportId) throws Exception {
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        //根据报告Id查询归档数据
        CwProjectReportArchiveDTO cwProjectReportArchiveDTO = cwProjectReportArchiveMapper.queryByReportId(reportId);
        //已经存在归档数据的话，直接跳过
        if(cwProjectReportArchiveDTO== null){
            CwProjectReport cwProjectReport = cwProjectReportService.getCwProjectReportById(reportId);
            CwProjectReportArchive cwProjectReportArchive = new CwProjectReportArchive();
            cwProjectReportArchive.setStatus("0");
            cwProjectReportArchive.setReportId(reportId);
            cwProjectReportArchive.setCreateById(cwProjectReport.getCreateById());
            cwProjectReportArchive.setProjectId(cwProjectReport.getProjectId());
            String fileNumber = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), CwProjectReportArchiveDTO.BIZ_CODE,TokenProvider.getCurrentToken());
//        String fileNumber = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), CwProjectReportArchiveDTO.BIZ_CODE);
            cwProjectReportArchive.setFileNumber(fileNumber);
            cwProjectReportArchiveMapper.insert(cwProjectReportArchive);
        }
    }

    /**
     * 根据报告id，撤回签章
     * @param reportId
     */
    public void rebackSign (String reportId) {
        // 通过报告id获取签章数据
        List<CwProjectReportSignature> signList = cwProjectReportSignatureMapper.selectList(new QueryWrapper<CwProjectReportSignature>().lambda().eq(CwProjectReportSignature::getReportId, reportId));
        // 将签章数据的状态改为初始值
        if (CollectionUtil.isNotEmpty(signList)) {
            signList.stream().forEach(item -> {
                item.setStatus("0"); // 签章流程的状态改为：未发起
                item.setSignatureAnnotator1Status("0"); // 签字注师1签章状态改为：未签章
                item.setSignatureAnnotator2Status("0"); // 签字注师2签章状态改为：未签章
                item.setSealAdminStatus("0"); // 盖章管理员签章状态改为：未签章
                cwProjectReportSignatureMapper.updateById(item); // 将修改的数据保存
            });
        }
        // 删除已盖章的附件
        // 1. 查询到当前报告的附件
//        List<WorkAttachmentInfo> workAttachments = ossServiceMapper.selectList(new LambdaQueryWrapper<WorkAttachmentInfo>().eq(WorkAttachmentInfo::getAttachmentId, reportId));
        List<WorkAttachmentInfo> workAttachments = SpringUtil.getBean(IWorkAttachmentApi.class).selectListByAttachmentId(reportId);
        // 2. 查询哪些附件是已盖章的
        List<String> delIds = new ArrayList<>();
        workAttachments.stream().forEach(item -> {
            int i = reportMapper.checkIsSign(item.getId());
            if (i != 0) {
                delIds.add(item.getId());
            }
        });
        // 3. 删除已盖章的附件(报告签章附件关联表  cw_project_report_file)
        workAttachments.stream().forEach(item -> {
            reportMapper.deleteIsSign(item.getId());  // 物理删除
        });
        // 4. 删除已盖章的附件(附件表 work_attachment)
        if (CollectionUtil.isNotEmpty(delIds)) {
            SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByIds(JSON.toJSONString(delIds));
//            ossServiceMapper.deleteBatchIds(delIds);  // 逻辑删除
        }
        // 5. 根据报告id删除报告归档信息  // 逻辑删除
        cwProjectReportArchiveMapper.delete(new LambdaQueryWrapper<CwProjectReportArchive>().eq(CwProjectReportArchive::getReportId, reportId));
        //删除通知表中的对应通知数据 物理删除
        for (CwProjectReportSignature cwProjectReportSignature : signList) {
                //获取当前登录人角色是否是苏州报告签字盖章代办
                UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
                if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
                    for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                        RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                        if ("szbgqzgzdb".equals(dtoById.getEnName())){
                            //根据procInsId查找taskId
                            String taskIdByprocInstId = flowTaskService.getTaskIdByprocInstId(cwProjectReportSignature.getProcInsId());
                            //根据taskid将通知表中的该条记录进行删除
                            cwProjectReportSignatureMapper.deleteByTaskId(taskIdByprocInstId);
                        }
                    }
                }
        }
    }

    /**
     * 根据报告id，撤回复核签章
     * @param reportId
     */
    public void rebackReviewSign (String reportId) {
        // 通过报告id获取签章数据
        List<CwProjectReportSignature> signList = cwProjectReportSignatureMapper.selectList(new QueryWrapper<CwProjectReportSignature>().lambda().eq(CwProjectReportSignature::getReportId, reportId));
        // 将签章数据的状态改为初始值
        if (CollectionUtil.isNotEmpty(signList)) {
            signList.stream().forEach(item -> {
                item.setStatus("0"); // 签章流程的状态改为：未发起
                item.setSignatureAnnotator1Status("0"); // 签字注师1签章状态改为：未签章
                item.setSignatureAnnotator2Status("0"); // 签字注师2签章状态改为：未签章
                item.setSealAdminStatus("0"); // 盖章管理员签章状态改为：未签章
                cwProjectReportSignatureMapper.updateById(item); // 将修改的数据保存
            });
        }
        // 删除已盖章的附件
        // 1. 查询到当前报告的附件
//        List<WorkAttachmentInfo> workAttachments = ossServiceMapper.selectList(new LambdaQueryWrapper<WorkAttachmentInfo>().eq(WorkAttachmentInfo::getAttachmentId, reportId));
        List<WorkAttachmentInfo> workAttachments = SpringUtil.getBean(IWorkAttachmentApi.class).selectListByAttachmentId(reportId);
        // 2. 查询哪些附件是已盖章的
        List<String> delIds = new ArrayList<>();
        workAttachments.stream().forEach(item -> {
            int i = reportMapper.checkIsSign(item.getId());
            if (i != 0) {
                delIds.add(item.getId());
            }
        });
        // 3. 删除已盖章的附件(报告签章附件关联表  cw_project_report_file)
        workAttachments.stream().forEach(item -> {
            reportMapper.deleteIsSign(item.getId());  // 物理删除
        });
        // 4. 删除已盖章的附件(附件表 work_attachment)
        if (CollectionUtil.isNotEmpty(delIds)) {
            SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByIds(JSON.toJSONString(delIds));
//            ossServiceMapper.deleteBatchIds(delIds);  // 逻辑删除
        }
        // 5. 根据报告id删除报告归档信息  // 逻辑删除
        cwProjectReportArchiveMapper.delete(new LambdaQueryWrapper<CwProjectReportArchive>().eq(CwProjectReportArchive::getReportId, reportId));

        //6.修改质量复核流程信息
        mapper.updateReviewStatusByReportId("0",reportId);
        //删除通知表中的对应通知数据 物理删除
        for (CwProjectReportSignature cwProjectReportSignature : signList) {
            //获取当前登录人角色是否是苏州报告签字盖章代办
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
            if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
                for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                    RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                    if ("szbgqzgzdb".equals(dtoById.getEnName())){
                        //根据procInsId查找taskId
                        String taskIdByprocInstId = flowTaskService.getTaskIdByprocInstId(cwProjectReportSignature.getProcInsId());
                        //根据taskid将通知表中的该条记录进行删除
                        cwProjectReportSignatureMapper.deleteByTaskId(taskIdByprocInstId);
                    }
                }
            }
        }
    }

    /**
     * 根据报告id修改签字注师1、2,所属行业以及业务对象的值
     * @param cwProjectReport
     */
    public void updateAnnotatorById(CwProjectReport cwProjectReport) {
        reportMapper.updateAnnotatorById(cwProjectReport);
    }

    public CwProjectReportData queryContainDelById(String id) {

        CwProjectReportData reportData = reportMapper.queryById(id);

        //将新增行数据查询出来放入到cwProjectInfoList中
        CwProjectInfoData cwProjectInfoData = infoMapper.selectByReportId(id);
        if (null != cwProjectInfoData){
            reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
            reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
            reportData.setReportDate(cwProjectInfoData.getReportDate());
            reportData.setReportType(cwProjectInfoData.getReportType());
            reportData.setReportNumber(cwProjectInfoData.getReportNumber());
            reportData.setReportNo(cwProjectInfoData.getReportNo());
            reportData.setSealType(cwProjectInfoData.getSealType());
        }

//        List<CwProjectInfoData> infoData = new ArrayList<>();

        List<ProjectReportWorkAttachmentDTO> dtoList = new ArrayList<>();
        List<ProjectReportWorkAttachmentDTO> signatureList = new ArrayList<>();
        if ( null != reportData){
            List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
            if (null != dtos){

                Iterator<ProjectReportWorkAttachmentDTO> it = dtos.iterator();
                while(it.hasNext()){
                    ProjectReportWorkAttachmentDTO d = it.next();
                    //根据id查出cw_project_report_file文件表的其他信息
                    //未签章附件
                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                    if (null != file) {
                        d.setFileType(file.getFileType());
                        d.setSealType(file.getSealType());
                        d.setSealedFile(file.getSealedFile());
                        d.setSealUser(file.getSealUser());
                        d.setSealDate(file.getSealDate());
                        d.setRemarks(file.getRemarks());
                        UserDTO userDTO = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name = reportMapper.getUserNameById(file.getCreateById());
                        userDTO.setId(file.getCreateById());
                        userDTO.setName(name);
                        d.setCreateBy(userDTO);
                        d.setCreateTime(file.getCreateTime());
                        dtoList.add(d);
                        it.remove();
                    }

                    //已签章附件
                    CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                    if (null != signatureFile){
                        d.setFileType(signatureFile.getFileType());
                        d.setSealType(signatureFile.getSealType());
                        d.setSealedFile(signatureFile.getSealedFile());
                        d.setSealUser(signatureFile.getSealUser());
                        d.setSealDate(signatureFile.getSealDate());
                        d.setRemarks(signatureFile.getRemarks());
                        UserDTO userDTO2 = new UserDTO();
                        //根据创建人id查出创建人名称
                        String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                        userDTO2.setId(signatureFile.getCreateById());
                        userDTO2.setName(name2);
                        d.setCreateBy(userDTO2);
                        d.setCreateTime(signatureFile.getCreateTime());
                        signatureList.add(d);
                        it.remove();
                    }
                }
                reportData.setCwFileInfoList(dtoList);
                reportData.setSignatureFileList(signatureList);
            }

            //将附件信息查出
            // 查询附件信息
            List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(id);
            List<WorkAttachmentInfo> reportFileList = Lists.newArrayList();
            if(CollectionUtils.isNotEmpty(dtos) && CollectionUtils.isNotEmpty(fileInfo2)){
                for (ProjectReportWorkAttachmentDTO dto : dtos) {
                    for (WorkAttachmentInfo workAttachmentDto : fileInfo2) {
                        if(dto.getId().equals(workAttachmentDto.getId())){
                            reportFileList.add(workAttachmentDto);
                        }
                    }
                }
            }

            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : reportFileList) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            reportData.setCwFileInfoList2(reportFileList);
            //设置历史报告列表
            //根据项目id查出所有的信息
            List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
            List<CwProjectInfoData> dataInfoList = new ArrayList<>();
            if (null != byProjectList) {
                CwProjectReportData finalReportData1 = reportData;
                byProjectList.forEach(pro->{
                    //根据reportid查出新增行数据
                    CwProjectInfoData infoData = infoMapper.getByReportId(pro.getId());
                    //根据reportid查出所有的附件信息
                    List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                    List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData1.getId());
                    //历史的附件信息是否是查改reportid对应的所有附件
                    if (null != cwFileInfoList){
                        cwFileInfoList.forEach(fi->{
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                            if (null != file) {
                                fi.setFileType(file.getFileType());
                                fi.setSealType(file.getSealType());
                                fi.setSealedFile(file.getSealedFile());
                                fi.setSealUser(file.getSealUser());
                                fi.setSealDate(file.getSealDate());
                                fi.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                fi.setCreateBy(userDTO);
                                fi.setCreateTime(file.getCreateTime());
                                fileList.add(fi);
                            }
                        });
                        //设置附件信息
                        infoData.setCwFileInfoList(fileList);
                        if (pro.getStatus().equals("5")) {
                            infoData.setDocumentStatus("已完成");
                        }
                        dataInfoList.add(infoData);
                    }
                });
            }

            reportData.setCwWorkClientContactDTOList(dataInfoList);

            //将复核数据查出来
            CwProjectReview review = reviewMapper.selectByReportId(reportData.getId());
            if ( null != review) {
                reportData.setReviewStatus(review.getReviewStatus());
                reportData.setAllPrintNum(review.getAllPrintNum());
                reportData.setIssueNum(review.getIssueNum());
                reportData.setPlaceOnFileNum(review.getPlaceOnFileNum());
                reportData.setPrintedBy(review.getPrintedBy());
                reportData.setCheckAutograph(review.getCheckAutograph());
                reportData.setReportTitleType(review.getReportTitleType());
                reportData.setNeedUpdate1(review.getNeedUpdate1());
                reportData.setNeedUpdate2(review.getNeedUpdate2());
                reportData.setNeedUpdate3(review.getNeedUpdate3());
                reportData.setRemark1(review.getRemark1());
                reportData.setRemark2(review.getRemark2());
                reportData.setRemark3(review.getRemark3());
                reportData.setComputerNo(review.getComputerNo());
                reportData.setReportReviewNo(review.getReportReviewNo());
                reportData.setReviewBy(review.getReviewBy());
                //将一级复核等填入数据查出
                List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                if (null != details) {
                    reportData.setDetails(details);
                }
            }
            //根据报告类型查询下一节点用户
            List<ReviewUser> stringList = new ArrayList<>();
            //如果是苏州分部，这里写死
            String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
            if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                stringList = reportMapper.getReviewByPost("质控-苏州分部");
            }else if (reportData.getReportType().equals("1")) {
                stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
            } else {
                stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
            }
            reportData.setReviewBys(stringList);
        } else {
            //传来的是复核表的id
            CwProjectReview review = reviewMapper.selectById(id);
            if (null != review) {
                reportData = reportMapper.queryById(review.getReportId());
                if ( null != reportData){
                    List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(reportData.getId());
                    if (null != dtos){
                        dtos.forEach(d->{
                            //根据id查出cw_project_report_file文件表的其他信息
                            //未签章附件
                            CwProjectReportFile file = attachmentMapper.selectInfoByFileId(d.getId(),"0");
                            if (null != file) {
                                d.setFileType(file.getFileType());
                                d.setSealType(file.getSealType());
                                d.setSealedFile(file.getSealedFile());
                                d.setSealUser(file.getSealUser());
                                d.setSealDate(file.getSealDate());
                                d.setRemarks(file.getRemarks());
                                UserDTO userDTO = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name = reportMapper.getUserNameById(file.getCreateById());
                                userDTO.setId(file.getCreateById());
                                userDTO.setName(name);
                                d.setCreateBy(userDTO);
                                d.setCreateTime(file.getCreateTime());
                                dtoList.add(d);
                            }

                            //已签章附件
                            CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                            if (null != signatureFile){
                                d.setFileType(signatureFile.getFileType());
                                d.setSealType(signatureFile.getSealType());
                                d.setSealedFile(signatureFile.getSealedFile());
                                d.setSealUser(signatureFile.getSealUser());
                                d.setSealDate(signatureFile.getSealDate());
                                d.setRemarks(signatureFile.getRemarks());
                                UserDTO userDTO2 = new UserDTO();
                                //根据创建人id查出创建人名称
                                String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                                userDTO2.setId(signatureFile.getCreateById());
                                userDTO2.setName(name2);
                                d.setCreateBy(userDTO2);
                                d.setCreateTime(signatureFile.getCreateTime());
                                signatureList.add(d);
                            }
                        });
                        reportData.setCwFileInfoList(dtoList);
                        reportData.setSignatureFileList(signatureList);
                    }
                    // 查询附件信息
                    List<WorkAttachmentInfo> fileInfo2 = reportMapper.findDtos(reportData.getId());
                    if (CollectionUtils.isNotEmpty(dtos)) {
                        for (WorkAttachmentInfo i : fileInfo2) {
                            i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                        }
                    }
                    reportData.setCwFileInfoList2(fileInfo2);
                    //设置历史报告列表
                    //根据项目id查出所有的信息
                    List<CwProjectReportData> byProjectList = reportMapper.getByProjectId(reportData.getProjectId());
                    List<CwProjectInfoData> dataInfoList = new ArrayList<>();
                    if (null != byProjectList) {
                        CwProjectReportData finalReportData = reportData;
                        byProjectList.forEach(pro->{
                            //根据reportid查出新增行数据
                            CwProjectInfoData infoData = infoMapper.getContainDelByReportId(pro.getId());
                            //根据reportid查出所有的附件信息
                            List<ProjectReportWorkAttachmentDTO> fileList = new ArrayList<>();
                            List<ProjectReportWorkAttachmentDTO> cwFileInfoList = attachmentMapper.selectByInfoIdAndNewLineId(finalReportData.getId());
                            //历史的附件信息是否是查改reportid对应的所有附件
                            if (null != cwFileInfoList){
                                cwFileInfoList.forEach(fi->{
                                    //未签章附件
                                    CwProjectReportFile file = attachmentMapper.selectInfoByFileId(fi.getId(),"0");
                                    if (null != file) {
                                        fi.setFileType(file.getFileType());
                                        fi.setSealType(file.getSealType());
                                        fi.setSealedFile(file.getSealedFile());
                                        fi.setSealUser(file.getSealUser());
                                        fi.setSealDate(file.getSealDate());
                                        fi.setRemarks(file.getRemarks());
                                        UserDTO userDTO = new UserDTO();
                                        //根据创建人id查出创建人名称
                                        String name = reportMapper.getUserNameById(file.getCreateById());
                                        userDTO.setId(file.getCreateById());
                                        userDTO.setName(name);
                                        fi.setCreateBy(userDTO);
                                        fi.setCreateTime(file.getCreateTime());
                                        fileList.add(fi);
                                    }
                                });
                                //设置附件信息
                                infoData.setCwFileInfoList(fileList);
                                if (pro.getStatus().equals("5")) {
                                    infoData.setDocumentStatus("已完成");
                                }
                                dataInfoList.add(infoData);
                            }
                        });
                    }

                    reportData.setCwWorkClientContactDTOList(dataInfoList);

                    //将复核数据查出来
//                CwProjectReview review = reviewMapper.selectByReportId(reportData.getId());
//                    if ( null != review) {
//
//                    }
                    reportData.setReviewStatus(review.getReviewStatus());
                    reportData.setAllPrintNum(review.getAllPrintNum());
                    reportData.setIssueNum(review.getIssueNum());
                    reportData.setPlaceOnFileNum(review.getPlaceOnFileNum());
                    reportData.setPrintedBy(review.getPrintedBy());
                    reportData.setCheckAutograph(review.getCheckAutograph());
                    reportData.setReportTitleType(review.getReportTitleType());
                    reportData.setNeedUpdate1(review.getNeedUpdate1());
                    reportData.setNeedUpdate2(review.getNeedUpdate2());
                    reportData.setNeedUpdate3(review.getNeedUpdate3());
                    reportData.setRemark1(review.getRemark1());
                    reportData.setRemark2(review.getRemark2());
                    reportData.setRemark3(review.getRemark3());
                    reportData.setComputerNo(review.getComputerNo());
                    reportData.setReviewBy(review.getReviewBy());

                    //将一级复核等填入数据查出
                    List<CwProofreadDetail> details = detailMapper.findByReportInfoId(review.getId());
                    if (null != details) {
                        reportData.setDetails(details);
                    }
                    //根据报告类型查询下一节点用户
                    List<ReviewUser> stringList = new ArrayList<>();
                    //如果是苏州分部，这里写死
                    String officeId = reportMapper.getCorrelationOfficeIdByName("苏州分公司");
                    if (StringUtils.isNotBlank(officeId) && officeId.contains(reportData.getOfficeId())){
                        stringList = reportMapper.getReviewByPost("质控-苏州分部");
                    }else if (reportData.getReportType().equals("1")) {
                        stringList = reportMapper.getReviewByPost("质控-财务-苏兴会基字");
                    } else {
                        stringList = reportMapper.getReviewByPost("质控-财务-非苏兴会基字");
                    }
                    reportData.setReviewBys(stringList);
                    //将新增行数据查询出来放入到cwProjectInfoList中
                    cwProjectInfoData = infoMapper.selectByReportId(reportData.getId());
                    if (null != cwProjectInfoData){
                        reportData.setServedUnitName(cwProjectInfoData.getServedUnitName());
                        reportData.setServedUnitId(cwProjectInfoData.getServedUnitId());
                        reportData.setReportDate(cwProjectInfoData.getReportDate());
                        reportData.setReportType(cwProjectInfoData.getReportType());
                        reportData.setReportNumber(cwProjectInfoData.getReportNumber());
                        reportData.setReportNo(cwProjectInfoData.getReportNo());
                        reportData.setSealType(cwProjectInfoData.getSealType());
                    }
                }
            }

        }
        return reportData;
    }

    public void updateCwProjectReportDataById(CwProjectReport report){
        if(StringUtils.isNotBlank(report.getId())){
            reportMapper.updateCwProjectReportDataById(report);
        }
    }

    public CwProjectReport getCwProjectReportById(String id){
        return reportMapper.getById(id);
    }


    /**
     * 数据导入(处理项目的项目规模和报告的审计收费)
     * @param listA
     * @return
     */
    public String importDecide(List<CwProjectReportDTO> listA) {
        List<String> projectNoList = Lists.newArrayList();
        //遍历获取所有报告号信息
        for (CwProjectReportDTO cwProjectReport : listA) {
            projectNoList.add(cwProjectReport.getReportNo());
        }
        List<CwProjectReport> reportInfoByNoList = Lists.newArrayList();
        if(projectNoList.size()>0){
            //数据库查询报告号信息，将存在的报告号信息进行筛选出来
            reportInfoByNoList = reportMapper.getReportInfoByNoList(projectNoList);

        }
        //数据循环遍历对有效数据进行修改审计收费
        for (CwProjectReportDTO dto : listA) {
            for (CwProjectReport reportByReportNo: reportInfoByNoList) {
                if (ObjectUtil.isNotEmpty(reportByReportNo) && dto.getReportNo().equals(reportByReportNo.getReportNo())){
                    if (StringUtils.isNotEmpty(dto.getAuditFees())){
                        try {
                            CwProjectReportArchive cwProjectReportArchive = new CwProjectReportArchive();
                            cwProjectReportArchive.setReportId(reportByReportNo.getId());
                            BigDecimal b = new BigDecimal(dto.getAuditFees());
                            BigDecimal multiply = b.multiply(new BigDecimal(10000));
                            String result = multiply.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                            cwProjectReportArchive.setAuditMoney(result);
                            cwProjectReportArchiveMapper.updateAuditMoneyByReportId(cwProjectReportArchive);
                        }catch (Exception e){

                        }
                    }else {
                        continue;
                    }
                    //修改项目规模
                    if (StringUtils.isNotEmpty(dto.getAuditFees())){
                        try {
                            CwProjectRecords projectRecords = new CwProjectRecords();
                            projectRecords.setId(reportByReportNo.getProjectId());
                            BigDecimal b = new BigDecimal(dto.getProjectMoney());
                            BigDecimal multiply = b.multiply(new BigDecimal(10000));
                            String result = multiply.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                            projectRecords.setProjectMoney(result);
                            cwProjectRecordsService.updateById(projectRecords);
                        }catch (Exception e){

                        }
                    }else {
                        continue;
                    }

                }else {
                    continue;
                }
            }
        }


        /*for (CwProjectReport dto : listA) {
            CwProjectReport reportByReportNo = reportMapper.getReportByReportNo(dto.getReportNo());
            if (ObjectUtil.isNotEmpty(reportByReportNo)){
                CwProjectRecords records = cwProjectRecordsService.getById(reportByReportNo.getProjectId());
                if (StringUtils.isNotEmpty(dto.getSignatureAnnotator1Name())){
                    UserDTO name = SpringUtil.getBean(IUserApi.class).getByLoginNameNotTenantId(dto.getSignatureAnnotator1Name());
                    reportByReportNo.setSignatureAnnotator1(name.getId());
                    records.setProjectMasterId(name.getId());
                    cwProjectRecordsService.updateById(records);
                }else {
                    continue;
                }
                if (StringUtils.isNotEmpty(dto.getSignatureAnnotator2Name())){
                    UserDTO name1 = SpringUtil.getBean(IUserApi.class).getByLoginNameNotTenantId(dto.getSignatureAnnotator2Name());
                    reportByReportNo.setSignatureAnnotator2(name1.getId());
                    records.setProjectLeaderId(name1.getId());
                    cwProjectRecordsService.updateById(records);
                }else {
                    continue;
                }
                if (StringUtils.isNotEmpty(dto.getAuditFees())){
                    try {
                        float v = Float.parseFloat(dto.getAuditFees());
                        String result = Float.toString(v * 10000);
                        reportByReportNo.setAuditFees(result);
                    }catch (Exception e){

                    }
                }else {
                    continue;
                }
            }else {
                continue;
            }
            reportMapper.updateById(reportByReportNo);

        }*/
        return "修改成功";
    }

    /**
     * 通过报告id查找修改签字注师历史记录
     * @param reportId
     * @return
     */
    public List<CwSignatureAnnotator> getSignatureAnnotatorList(String reportId) {
        return cwProjectReportSignatureMapper.getSignatureAnnotatorList(reportId);
    }

    /**
     * 修改签字注师并保存记录
     * @param reportData
     * @return
     */
    public String saveSignatureAnnotator(CwProjectReportData reportData) {
        CwProjectReport report = cwProjectReportService.getById(reportData.getId());
        if (ObjectUtil.isNotEmpty(report)){
            //将获取到的报告信息转为json格式存到历史记录表中
            String jsonString = JSON.toJSONString(report);
            //修改报告表中的签字注师
            report.setSignatureAnnotatorStatus(reportData.getSignatureAnnotatorStatus());
            report.setSignatureAnnotator1(reportData.getSignatureAnnotator1());
            report.setSignatureAnnotator2(reportData.getSignatureAnnotator2());
            reportMapper.updatesigStatusById(report);
            //将信息添加到签字注师记录表中
            CwSignatureAnnotator cwSignatureAnnotator = new CwSignatureAnnotator();
            //生成id
            String detailId = UUID.randomUUID().toString().replace("-", "");
            cwSignatureAnnotator.setId(detailId);
            cwSignatureAnnotator.setReportId(reportData.getId());
            cwSignatureAnnotator.setSignatureAnnotator1(reportData.getSignatureAnnotator1());
            cwSignatureAnnotator.setSignatureAnnotator2(reportData.getSignatureAnnotator2());
            cwSignatureAnnotator.setUpdateUser(report.getCreateName());
            cwSignatureAnnotator.setJsonData(jsonString);
            cwSignatureAnnotator.setStatus(reportData.getSignatureAnnotatorStatus());
            cwSignatureAnnotator.setReason(reportData.getSigReason());
            cwSignatureAnnotatorMapper.insert(cwSignatureAnnotator);
            return detailId;
        }else {
            return "";
        }

    }

    /**
     * 签字注师  驳回
     * @param data
     * @return
     */
    public String updateSigStatusById(CwProjectReport data) {
        reportMapper.updatesigStatusById(data);
        CwSignatureAnnotator sigById = cwSignatureAnnotatorMapper.getSigById(data.getId());
        cwSignatureAnnotatorMapper.updateStatusBySigId("4",sigById.getId());
        return "修改成功";
    }

    /**
     * 修改签字注师  同意
     * @param report
     * @return
     */
    public String updateAgree(CwProjectReport report) {
        //修改报告表中的签字注师状态
        reportMapper.updatesigStatusById(report);
        //修改签字注师记录表中的状态
        CwSignatureAnnotator sig = cwSignatureAnnotatorMapper.getSigById(report.getId());
        sig.setStatus(report.getSignatureAnnotatorStatus());
        sig.setReason(report.getSigReason());
        sig.setSignatureAnnotator1(report.getSignatureAnnotator1());
        sig.setSignatureAnnotator2(report.getSignatureAnnotator2());
        cwSignatureAnnotatorMapper.updateStatusById(sig);
        return sig.getId();
    }

    public CwSignatureAnnotator getSigById(String id) {
        CwSignatureAnnotator cwSignatureAnnotator=cwSignatureAnnotatorMapper.selectById(id);
        return cwSignatureAnnotator;
    }


    public void updateStatusByIdSig(CwProjectReport report) {
        CwSignatureAnnotator sigById = cwSignatureAnnotatorMapper.getSigById(report.getId());
        cwSignatureAnnotatorMapper.updateStatusBySigId(report.getSignatureAnnotatorStatus(),sigById.getId());
        //获取记录表中的json数据
        CwProjectReport reportData = JSON.parseObject(sigById.getJsonData(), CwProjectReport.class);
        reportData.setSignatureAnnotatorStatus(report.getSignatureAnnotatorStatus());
        //将报告表中的签字注师还原
        reportMapper.updatesigStatusById(reportData);

    }

    public void returnRequest(String id) {
        CwSignatureAnnotator sigById = cwSignatureAnnotatorMapper.getSigById(id);
        //修改状态
        cwSignatureAnnotatorMapper.updateStatusBySigId("0",sigById.getId());
        //清空修改原因
        cwSignatureAnnotatorMapper.setClearReason(sigById.getId());
        //获取记录表中的json数据
        CwProjectReport reportData = JSON.parseObject(sigById.getJsonData(), CwProjectReport.class);
        reportData.setSignatureAnnotatorStatus("0");
        //将报告表中的签字注师还原
        reportMapper.updatesigStatusById(reportData);


    }
    /**
     * 根据报告id查询已签章文件信息
     * @param id
     * @return
     */
    public List<ProjectReportWorkAttachmentDTO> getSignatureFileInfoList (String id) {
        List<ProjectReportWorkAttachmentDTO> signatureList = new ArrayList<>();

        List<ProjectReportWorkAttachmentDTO> dtos = attachmentMapper.selectByInfoId(id);
        if (null != dtos){

            Iterator<ProjectReportWorkAttachmentDTO> it = dtos.iterator();
            while(it.hasNext()){
                ProjectReportWorkAttachmentDTO d = it.next();
                //已签章附件
                CwProjectReportFile signatureFile = attachmentMapper.selectInfoByFileId(d.getId(),"1");
                if (null != signatureFile){
                    d.setFileType(signatureFile.getFileType());
                    d.setSealType(signatureFile.getSealType());
                    d.setSealedFile(signatureFile.getSealedFile());
                    d.setSealUser(signatureFile.getSealUser());
                    d.setSealDate(signatureFile.getSealDate());
                    d.setRemarks(signatureFile.getRemarks());
                    UserDTO userDTO2 = new UserDTO();
                    //根据创建人id查出创建人名称
                    String name2 = reportMapper.getUserNameById(signatureFile.getCreateById());
                    userDTO2.setId(signatureFile.getCreateById());
                    userDTO2.setName(name2);
                    d.setCreateBy(userDTO2);
                    d.setCreateTime(signatureFile.getCreateTime());
                    signatureList.add(d);
                    it.remove();
                }
            }
        }
        return signatureList;
    }

    /**
     * 已盖章文件下载并压缩
     * @param listAll
     * @return
     */
    public String getSignatureFileZipUrl (List<ProjectReportWorkAttachmentDTO> listAll) {
        long timestamp = System.currentTimeMillis();
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        String filePath = null;
        if(System.getProperty("os.name").toLowerCase().contains("win")){
            filePath = "D:/attachment-file/" + userDTO.getName() + timestamp;
        }else{
            filePath = "/attachment-file/" + userDTO.getName() + timestamp;
        }

        File folder = new File(filePath);
        if (!folder.exists()) {
            if (folder.mkdirs()) {
                System.out.println("文件夹创建成功！");
            } else {
                System.out.println("文件夹创建失败！");
            }
        } else {
            System.out.println("文件夹已存在！");
        }
        String path = filePath + "/";

        try{
            //文件下载到指定文件夹
            for (ProjectReportWorkAttachmentDTO info : listAll) {
                String aliyunUrl = "http://cdn.gangwaninfo.com";
                String aliDownloadUrl = "http://oss.gangwaninfo.com";


                String file = aliyunUrl + info.getUrl();
                file = file.replace("amp;","");
                String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
                String cons = "";
                if (file.contains(aliyunUrl)){
                    cons = aliyunUrl;
                }else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
                    cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
                }else {
                    cons = aliDownloadUrl;
                }
                String ossKey = file.split(cons+"/")[1];
                SpringUtil.getBean ( IWorkAttachmentApi.class ).downByStreamSaveLocal(ossKey,fileName,path+fileName);
            }

            //文件打包压缩成zip
            FileUtil.zipFolder(filePath, filePath+".zip");

        }catch (Exception e){
            e.printStackTrace();
        }

        return filePath;
    }


    /**
     * 保存或修改撤回签章流程
     * @param reportData
     * @return
     */
    public String saveRevocation(CwProjectReportData reportData) {
        String id="";
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if(StringUtils.isNotBlank(reportData.getRevocationId())){
            CwRevocationSignature cwRevocationSignature = new CwRevocationSignature();
            cwRevocationSignature.setUpdateById(userDTO.getId());
            cwRevocationSignature.setUpdateTime(new Date());
            cwRevocationSignature.setId(reportData.getRevocationId());
            cwRevocationSignature.setReason(reportData.getRebackReason());
            cwRevocationSignature.setStatus(reportData.getRebackStatus());
            cwRevocationSignature.setReportId(reportData.getId());
            cwRevocationSignatureMapper.updateById(cwRevocationSignature);
            if ("5".equals(reportData.getRebackStatus())){
                //重新复核
                this.rebackReviewSign(reportData.getId());
            }
            id=reportData.getRevocationId();
        }else {
            String detailId = UUID.randomUUID().toString().replace("-", "");
            CwRevocationSignature cwRevocationSignature = new CwRevocationSignature();
            cwRevocationSignature.setId(detailId);
            cwRevocationSignature.setReason(reportData.getRebackReason());
            cwRevocationSignature.setStatus(reportData.getRebackStatus());
            cwRevocationSignature.setReportId(reportData.getId());
            cwRevocationSignatureMapper.insert(cwRevocationSignature);
            id=detailId;
        }
        return id;
    }

    /**
     * 撤回签章  根据id修改状态
     * @param data
     * @return
     */
    public String updateStatusByIdRe(CwProjectReportData data) {
        CwRevocationSignature cwRevocationSignature = new CwRevocationSignature();
        cwRevocationSignature.setId(data.getRevocationId());
        cwRevocationSignature.setStatus(data.getRebackStatus());
        cwRevocationSignatureMapper.updateById(cwRevocationSignature);
        return "操作成功";
    }

    /**
     * 查询项目下的报告是否已经完成关联
     * @param id
     * @return
     */
    public boolean getCompleteReport(String id) {
        List<CwProjectReportData> reportData = reportMapper.getByProjectId(id);
        if (CollectionUtil.isNotEmpty(reportData)){
            for (CwProjectReportData data : reportData) {
                if (StringUtils.isNotBlank(data.getIsCompleteInvoice())){
                    if (!"0".equals(data.getIsCompleteInvoice())){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 根据发票编号查询报告
     * @param invoiceNumber
     * @return
     */
    public boolean getByInvoiceNumber(String invoiceNumber,String id) {
        CwProjectReportData reportData = reportMapper.getByInvoiceNumber(invoiceNumber,id);
        if (ObjectUtil.isNotEmpty(reportData)){
            return true;
        }
        return false;
    }


    /**
     * 查询近1个月完成的财务报告和所有未完成的财务报告信息
     * @param projectReportData
     * @return
     * @throws Exception
     */
    public IPage<CwProjectReportData> findNotCompletedList( Page<CwProjectReportData> page, CwProjectReportData projectReportData) throws Exception{
        QueryWrapper<CwProjectReportData> queryWrapper = QueryWrapperGenerator.buildQueryCondition (projectReportData,CwProjectReportData.class);
        queryWrapper.eq("a.del_flag","0");
//        queryWrapper.orderByDesc("a.create_date");
        //条件
        if (StringUtils.isNotEmpty(projectReportData.getProjectNumber())) {
            queryWrapper.like("b.project_number", projectReportData.getProjectNumber());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectName())) {
            queryWrapper.like("b.project_name", projectReportData.getProjectName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getReportName())) {
            queryWrapper.like("a.report_name", projectReportData.getReportName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterId())) {
            queryWrapper.eq("b.project_master_id", projectReportData.getProjectMasterId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMaster2Id())) {
            queryWrapper.eq("b.real_header", projectReportData.getProjectMaster2Id());
        }
        if (StringUtils.isNotEmpty(projectReportData.getProjectMasterName())) { // 项目经理1筛选
            queryWrapper.like("e.id", projectReportData.getProjectMasterName()).or().like("e.name", projectReportData.getProjectMasterName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getRealHeaderName())) { // 项目经理2筛选
            queryWrapper.like("f.id", projectReportData.getRealHeaderName()).or().like("f.name", projectReportData.getRealHeaderName());
        }
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.and(wrapper -> wrapper.like("a.create_by_id", projectReportData.getCreateBy().getId())
                    .or()
                    .like("d.name", projectReportData.getCreateBy().getId()));
        }
        //4、签约时间（区间）
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_time", contractDates[0], contractDates[1]);
        }
        //5、报告文号
        if (StringUtils.isNotEmpty(projectReportData.getReportNo())) {
            queryWrapper.like("new_line.report_no", projectReportData.getReportNo());
        }
        //6、审计收费
        String[] contractAmounts = projectReportData.getContractAmounts();
        if (contractAmounts != null) {
            if (StringUtils.isNotEmpty(contractAmounts[0])) {
                queryWrapper.ge("a.audit_fees",contractAmounts[0]);
            }
            if (contractAmounts.length>1 && StringUtils.isNotEmpty(contractAmounts[1])) {
                queryWrapper.le("a.audit_fees", contractAmounts[1]);
            }
        }
        if(StringUtils.isNotEmpty(projectReportData.getApplyStatus()) && StringUtils.isNotEmpty(projectReportData.getReviewStatus())){
            if("-1".equals(projectReportData.getApplyStatus()) && "-1".equals(projectReportData.getReviewStatus())){
                queryWrapper.and(wrapper ->
                        wrapper.ne("cw_na.review_status", "5")
                                .or()
                                .ne("cw_rev.review_status", "5")
                );
            }
        }
//        if(StringUtils.isNotEmpty(projectReportData.getApplyStatus()) && StringUtils.isNotEmpty(projectReportData.getReviewStatus())){
//            if("-1".equals(projectReportData.getApplyStatus()) && "-1".equals(projectReportData.getReviewStatus())){
//                queryWrapper.and(wrapper ->
//                        wrapper.ne("cw_na.review_status", "5")
//                                .or()
//                                .ne("cw_rev.review_status", "5")
//                );
//            }
//        }
        if (StringUtils.isNotEmpty(projectReportData.getStatus1())) {
            queryWrapper.eq("cw_prs1.status", projectReportData.getStatus1());
        }
        if (StringUtils.isNotBlank(projectReportData.getFilingType())) {
            List<CwProjectRecords> projectList = cwProjectRecordsService.list(new LambdaQueryWrapper<CwProjectRecords>().eq(CwProjectRecords::getReportType, projectReportData.getFilingType()));
            List<String> projectIdList = projectList.stream().map(CwProjectRecords::getId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(projectIdList)) {
                queryWrapper.in("b.id", projectIdList);
            } else {
                return new Page<>();
            }
        }
        if (ArrayUtil.isNotEmpty(projectReportData.getCreateDates())) {
            queryWrapper.between("a.create_time", projectReportData.getCreateDates()[0], projectReportData.getCreateDates()[1]);
        }
        //报告日期
        if (ArrayUtil.isNotEmpty(projectReportData.getReportDates())) {
            queryWrapper.between("new_line.report_date", projectReportData.getReportDates()[0], projectReportData.getReportDates()[1]);
        }
        //项目分类
        if (StringUtils.isNotEmpty(projectReportData.getProjectClassification())) {
            queryWrapper.eq("b.project_classification", projectReportData.getProjectClassification());
        }
        //报告类型
        if (StringUtils.isNotEmpty(projectReportData.getReportType())) {
            queryWrapper.eq("new_line.report_type", projectReportData.getReportType());
        }

        String isBmzr = "0";
        StringBuilder officeIds = new StringBuilder();
        //UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        List<String> manageOfficeIdList= Lists.newArrayList();



        long l1 = System.currentTimeMillis();
        IPage<CwProjectReportData> list = null;
        long l2 = System.currentTimeMillis();
        System.out.println("报告列表查询service方法消耗时间:" + (l2-l1));

        //获取当前登录人角色是否是苏州报告签字盖章代办
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (CollectionUtil.isNotEmpty(userDTO.getRoleDTOList())){
            for (RoleDTO roleDTO : userDTO.getRoleDTOList()) {
                RoleDTO dtoById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
                if ("szbgqzgzdb".equals(dtoById.getEnName())){
                    list = reportMapper.findNotCompletedList2(page,isBmzr, officeIds.toString(), queryWrapper);
                    break;
                }
            }
        }

        if(null == list){
            list = reportMapper.findNotCompletedList(page,isBmzr, officeIds.toString(), queryWrapper);
        }

        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();
        }
        ArrayList<User> users = new ArrayList<>();
        List<UserDTO> finalAllUserInfo = allUserInfo;

        List<CwProjectReportData> records = list.getRecords();
        //获取查询的所有报告id
        List<String> reportIdList = Lists.newArrayList();

        for (CwProjectReportData record : records) {
            reportIdList.add(record.getId());
        }
        //根据报告id查询修改签字注师记录表信息
        List<CwSignatureAnnotator> sigByIdList = new ArrayList<CwSignatureAnnotator>();
        if(reportIdList.size()>0){
            sigByIdList = cwSignatureAnnotatorMapper.getSigByIdList(reportIdList);
        }

        List<CwSignatureAnnotator> finalSigByIdList = sigByIdList;
        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.isBlank(li.getRealHeaderName())) {
                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.isEmpty(li.getSignatureAnnotatorStatus())){
                li.setSignatureAnnotatorStatus("0");
            }
            /*CwSignatureAnnotator sigById = cwSignatureAnnotatorMapper.getSigById(li.getId());
            if (ObjectUtil.isNotEmpty(sigById)){
                li.setProcInsSigId(sigById.getProcInsId());
                li.setSigReason(sigById.getReason());
                li.setTaskSigId(sigById.getTaskId());
            }*/
            for (CwSignatureAnnotator annotator : finalSigByIdList) {
                if(li.getId().equals(annotator.getReportId())){
                    li.setProcInsSigId(annotator.getProcInsId());
                    li.setSigReason(annotator.getReason());
                    li.setTaskSigId(annotator.getTaskId());
                }
            }

            //如果质控审核已经完成且审核通过时间存在，则判断审核时间是否已经超过一天，若不超过，则可以重复发起质控审核
            if (null != li.getAuditTime() && "5".equals(li.getReviewStatus())){
                li.setRepetitionReviewFlag(getRepetitionReviewFlag(li.getAuditTime()));
            }

        });
        return list;

    }
}
