package com.jeeplus.test.cw.projectReport.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
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.google.common.collect.Maps;
import com.google.gson.Gson;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.model.Flow;
import com.jeeplus.flowable.service.FlowTaskService;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.service.UserService;
import com.jeeplus.sys.mapper.UserMapper;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.Global;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.common.FindUtils;
import com.jeeplus.test.cw.common.flowable.dto.CommitParamDTO;
import com.jeeplus.test.cw.contractRegistration.domain.ContractInfo;
import com.jeeplus.test.cw.invoice.domain.CwFinanceInvoice;
import com.jeeplus.test.cw.invoice.service.dto.CwFinanceInvoiceDTO;
import com.jeeplus.test.cw.invoice.service.mapstruct.CwFinanceInvoiceWrapper;
import com.jeeplus.test.cw.projectRecords.domain.CwProjectRecords;
import com.jeeplus.test.cw.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.test.cw.projectRecords.service.mapstruct.CwProjectRecordsWrapper;
import com.jeeplus.test.cw.projectReport.domain.*;
import com.jeeplus.test.cw.projectReport.mapper.*;
import com.jeeplus.test.cw.projectReport.service.dto.CwProjectReportDTO;
import com.jeeplus.test.cw.projectReport.service.dto.CwProjectReportSignatureDTO;
import com.jeeplus.test.cw.projectReport.service.dto.ProjectReportWorkAttachmentDTO;
import com.jeeplus.test.cw.projectReport.service.mapstruct.CwProjectReportFileWrapper;
import com.jeeplus.test.cw.workClientInfo.domain.CwWorkClientBase;
import com.jeeplus.test.cw.workClientInfo.service.dto.CwWorkClientBaseDTO;
import com.jeeplus.test.cw.workClientInfo.service.mapstruct.CwWorkClientBaseWrapper;
import com.jeeplus.test.mould.service.SerialnumTplService;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.mapper.OssServiceMapper;
import com.jeeplus.test.oss.service.OSSClientService;
import com.jeeplus.test.oss.service.OssService;
import com.jeeplus.test.signature.domain.*;
import com.jeeplus.test.signature.utils.SignaturePostUtil;
import com.jeeplus.test.workContract.service.dto.WorkAttachmentDto;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.collections4.CollectionUtils;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author: 王强
 * @create: 2022-11-16 14:17
 **/
@Service
@Transactional
public class CwProjectReportService extends ServiceImpl<CwProjectReportMapper, CwProjectReport> {

    private static final String HTTPTOP = Global.getConfig("signature_http_top");
    private static final String COMPANYROUNDSEALID = Global.getConfig("company_round_seal_id");
    private static final String COMPANYROUNDSEALIDVERTICAL = Global.getConfig("company_round_seal_id_vertical");
    private static final String COMPANYPARTIESSEALID = Global.getConfig("company_parties_seal_id");
    private static final String APPROVALCATEGORYID = Global.getConfig("approval_category_id");
    private static final String APPROVALYCCATEGORYID = Global.getConfig("approval_YC_category_id");
    private static final String REPORTCATEGORYID = Global.getConfig("report_category_id");
    private static final String REPORTYCCATEGORYID = Global.getConfig("report_YC_category_id");
    private static final String JUDGEMENTCATEGORYID = Global.getConfig("judgement_category_id");

    @Resource
    private CwProjectReportMapper reportMapper;

    @Resource
    private CwProofreadDetailMapper detailMapper;

    @Resource
    private CwProjectInfoMapper infoMapper;

    @Resource
    private ProjectReportWorkAttachmentMapper attachmentMapper;

    @Resource
    private SerialnumTplService serialnumTplService;

    @Resource
    private OssService ossService;

    @Resource
    private OssServiceMapper ossServiceMapper;

    @Resource
    private CwProjectReportCancelMapper cancelMapper;

    @Autowired
    private UserService userService;
    @Autowired
    private OSSClientService ossClientService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private CwProjectReportSignatureMapper cwProjectReportSignatureMapper;

    @Autowired
    private FlowTaskService flowTaskService;

    @Autowired
    private TaskService taskService;

    @Resource
    private CwProjectReportReviewMapper reviewMapper;

    @Resource
    private CwProjectReportReviewMapper mapper;

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

            CwProjectReport report = reportMapper.selectById(reportData.getId());
            if (report != null){
                reportData.setCreateBy(reportData.getCreateBy());
                return update(reportData);
            }
        }
        return add(reportData);

    }

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

        CwProjectReport report = new CwProjectReport();
        BeanUtils.copyProperties(reportData, report);
        report.setUpdateBy(userDTO.getId());
        report.setUpdateDate(new Date());
        reportMapper.updateById(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.setUpdateBy(UserUtils.getCurrentUserDTO().getId());
        infoData.setUpdateDate(new Date());
        infoMapper.updateById(infoData);

        //对上传的文件数据进行持久化操作
        List<ProjectReportWorkAttachmentDTO> cwFileInfoList = report.getCwFileInfoList();
        List<WorkAttachmentDto> cwFileInfoList2 = report.getCwFileInfoList2();
        if (CollectionUtils.isNotEmpty(cwFileInfoList2)) {
            updateFiles2(cwFileInfoList2, userDTO, report.getId());
        } else if (CollectionUtils.isNotEmpty(cwFileInfoList)) {
            updateFiles(cwFileInfoList, userDTO, report.getId());
        } else {
            //删除所有的文件信息
            List<String> ids = attachmentMapper.getIdByAttachmentId(report.getId());
            ids.forEach(id->{
                List<String> fileId = attachmentMapper.getFileId(id);
                fileId.forEach(fidId->{
                    attachmentMapper.deleteById(fidId);
                });

                ossServiceMapper.deleteById(id);
            });
        }

        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 = UserUtils.getCurrentUserDTO();
        if(StringUtils.isBlank(reportData.getId())){
            //单据编号生成
            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.getCreateBy())) {
                report.setCreateBy(UserUtils.getCurrentUserDTO().getId());
                String id = UUID.randomUUID().toString().replace("-", "");
                report.setId(id);
            }
        }
        //对新增行数据进行持久化操作
        CwProjectInfoData infoData = new CwProjectInfoData();
//        List<CwProjectInfoData> infoList = new ArrayList<>();
        infoData.setCreateBy(UserUtils.getCurrentUserDTO().getId());
        infoData.setCreateDate(new Date());
        infoData.setUpdateBy(UserUtils.getCurrentUserDTO().getId());
        infoData.setUpdateDate(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());
//        //报告文号生成
//        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<WorkAttachmentDto> fileInfoList2 = new ArrayList<>();
        if ( null !=report.getCwFileInfoList2()){
            fileInfoList2 = report.getCwFileInfoList2();
        }
        ossServiceMapper.delete(new QueryWrapper<WorkAttachment>().lambda().eq(WorkAttachment::getAttachmentId, report.getId()));

        AtomicInteger j2 = new AtomicInteger(1);
        if (fileInfoList2 != null){
            fileInfoList2.forEach(item -> {
                WorkAttachment i = new WorkAttachment();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
                i.setCreateDate(new Date());
                i.setUpdateDate(new Date());
                i.setDelFlag(0);
                i.setUrl(item.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(item.getName().split("\\."));
                if (CollectionUtils.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(report.getId());
                i.setAttachmentName(item.getName());
                i.setAttachmentFlag("cw_project_report");
                i.setFileSize(item.getSize());
                i.setSort(j2.get());
                ossServiceMapper.insertWorkAttachment(i, userDTO);
            });
        }

        //对上传的文件数据进行持久化操作
        List<ProjectReportWorkAttachmentDTO> fileInfoList = new ArrayList<>();
        if ( null !=report.getCwFileInfoList()){
            fileInfoList = report.getCwFileInfoList();
        }
//        ossServiceMapper.delete(new QueryWrapper<WorkAttachment>().lambda().eq(WorkAttachment::getAttachmentId, report.getId()));
        AtomicInteger j = new AtomicInteger(1);
        if (fileInfoList != null){
            fileInfoList.forEach(item -> {
                WorkAttachment i = new WorkAttachment();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
                i.setCreateDate(new Date());
                i.setUpdateDate(new Date());
                i.setDelFlag(0);
                i.setUrl(item.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(item.getName().split("\\."));
                if (CollectionUtils.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(report.getId());
                i.setAttachmentName(item.getName());
                i.setAttachmentFlag("cw_project_report_file");
                i.setFileSize(item.getSize());
                i.setSort(j.get());
                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.setCreateBy(userDTO.getId());
        info.setCreateDate(new Date());
        info.setUpdateBy(userDTO.getId());
        info.setUpdateDate(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.getProjectMasterId())) {
            queryWrapper.eq("b.project_master_id", projectReportData.getProjectMasterId());
        }
        if (StringUtils.isNotEmpty(projectReportData.getCreateBy().getId())) {
            queryWrapper.like("a.create_by", projectReportData.getCreateBy().getId());
        }
        //4、签约时间（区间）
        String[] contractDates = projectReportData.getContractDates();
        if (contractDates != null) {

            queryWrapper.between("a.create_date", 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 (StringUtils.isNotEmpty(contractAmounts[1])) {
                queryWrapper.le("a.audit_fees", contractAmounts[1]);
            }
        }
        String isBmzr = "0";
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        if (FindUtils.haveRoleCwBmzr()) {
            isBmzr = "1";
        } else {
            isBmzr = "0";
        }
        IPage<CwProjectReportData> list = reportMapper.findList(page,userDTO,isBmzr, queryWrapper);
        return list;

    }

    /**
     * 修改状态
     * @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);

        //将新增行数据查询出来放入到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.getCreateBy());
                        userDTO.setId(file.getCreateBy());
                        userDTO.setName(name);
                        d.setCreateBy(userDTO);
                        d.setCreateDate(file.getCreateDate());
                        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.getCreateBy());
                        userDTO2.setId(signatureFile.getCreateBy());
                        userDTO2.setName(name2);
                        d.setCreateBy(userDTO2);
                        d.setCreateDate(signatureFile.getCreateDate());
                        signatureList.add(d);
                    }
                });
                reportData.setCwFileInfoList(dtoList);
                reportData.setSignatureFileList(signatureList);
            }
            //将附件信息查出
            // 查询附件信息
            List<WorkAttachmentDto> fileInfo2 = reportMapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentDto i : fileInfo2) {
                    i.setCreateBy(UserUtils.get(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.getCreateBy());
                                userDTO.setId(file.getCreateBy());
                                userDTO.setName(name);
                                fi.setCreateBy(userDTO);
                                fi.setCreateDate(file.getCreateDate());
                                fileList.add(fi);
                            }
                        });
                        //设置附件信息
                        infoData.setCwFileInfoList(fileList);
                        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<>();
            if (reportData.getReportType().equals("1")) {
                stringList = reportMapper.getReviewByS("1");
            } else {
                stringList = reportMapper.getReviewByS("2");
            }
            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.getCreateBy());
                                userDTO.setId(file.getCreateBy());
                                userDTO.setName(name);
                                d.setCreateBy(userDTO);
                                d.setCreateDate(file.getCreateDate());
                                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.getCreateBy());
                                userDTO2.setId(signatureFile.getCreateBy());
                                userDTO2.setName(name2);
                                d.setCreateBy(userDTO2);
                                d.setCreateDate(signatureFile.getCreateDate());
                                signatureList.add(d);
                            }
                        });
                        reportData.setCwFileInfoList(dtoList);
                        reportData.setSignatureFileList(signatureList);
                    }
                    // 查询附件信息
                    List<WorkAttachmentDto> fileInfo2 = reportMapper.findDtos(id);
                    if (CollectionUtils.isNotEmpty(dtos)) {
                        for (WorkAttachmentDto i : fileInfo2) {
                            i.setCreateBy(UserUtils.get(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.getCreateBy());
                                        userDTO.setId(file.getCreateBy());
                                        userDTO.setName(name);
                                        fi.setCreateBy(userDTO);
                                        fi.setCreateDate(file.getCreateDate());
                                        fileList.add(fi);
                                    }
                                });
                                //设置附件信息
                                infoData.setCwFileInfoList(fileList);
                                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);
                    }
                    //将新增行数据查询出来放入到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 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<WorkAttachment> 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());
            });

            /*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);
        queryWrapper.orderByDesc("cw_wcb.create_date");
        if (ObjectUtil.isNotEmpty(cwWorkClientBaseDTO)) {
            if (ArrayUtil.isNotEmpty(cwWorkClientBaseDTO.getCreateDates())) {
                queryWrapper.between("cw_wcb.create_date", 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());
                }
            }
        }
        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<WorkAttachment> fileList = attachmentMapper.selectWorkAttachmentByReportId(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 = Global.getAliyunUrl();
            String aliDownloadUrl = Global.getAliDownloadUrl();

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

            for (WorkAttachment 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];
                    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 = 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 = userService.getUserInfoByRoleName("签章管理人");
        if(userInfoByRoleNameList.size()>0){

            UserDTO user = UserUtils.get(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 = UserUtils.get(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 = UserUtils.get(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.selectById(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.selectById(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");
        }
        cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
        return "操作成功";
    }

    public String getSignature (String reportId){
        CwProjectReportData cwProjectReportData1 = this.queryById(reportId);
        String signatureType = cwProjectReportData1.getSignatureType();
        CwProjectReportSignature cwProjectReportSignature = cwProjectReportSignatureMapper.selectOne(new QueryWrapper<CwProjectReportSignature>().lambda()
                .eq(CwProjectReportSignature::getReportId, reportId)
                .eq(CwProjectReportSignature::getType, signatureType)
        );
        cwProjectReportSignature.setStatus("2");
        cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
        return cwProjectReportSignature.getId();
    }

    public void commitFlowable(CwProjectReportData cwProjectReportData) {
        CwProjectReportData cwProjectReportDto = this.queryById(cwProjectReportData.getId());
        cwProjectReportData.getCommitParamDTO().setVars(cwProjectReportDto);
        CommitParamDTO<CwProjectReportData> commitParamDTO = cwProjectReportData.getCommitParamDTO();
        Map<String, Object> vars = Maps.newHashMap();
        Flow flow = new Flow();
        flow.setTaskId(commitParamDTO.getTaskId());
        flow.setTaskDefKey(commitParamDTO.getTaskDefKey());
        flow.setProcInsId(commitParamDTO.getProcInsId());
        flow.setProcDefId(commitParamDTO.getProcDefId());
        flow.setAssignee(commitParamDTO.getAssignee());
        flow.setComment(commitParamDTO.getComment());
        String var = JSON.toJSONString(commitParamDTO.getVars());
        Map<String, String> stringObjectMap = JSON.parseObject(var, new TypeReference<Map<String, String>>() {});
        for (Map.Entry<String, String> entry : stringObjectMap.entrySet()) {
            String value = entry.getValue();
            if("true".equals(value) || "false".equals(value)){
                vars.put(entry.getKey(), Boolean.valueOf(value).booleanValue());
            }else{
                vars.put(entry.getKey(), value);
            }
        }
        // 流程节点审核通过
        flowTaskService.auditSave(flow, vars);
        CwProjectReport report = this.getOne(new QueryWrapper<CwProjectReport>().lambda().eq(CwProjectReport::getId, cwProjectReportData.getId()));
        // 指定下一步处理人
        Task task = taskService.createTaskQuery().processInstanceId(flow.getProcInsId()).active().singleResult();
        // task为null时，则当前节点为最后一个审核节点
        if(task != null){
            if(org.apache.commons.lang3.StringUtils.isNotBlank(flow.getAssignee ())){
                taskService.setAssignee(task.getId(), flow.getAssignee ());
            }
            if(ObjectUtil.isNotEmpty(report)) {
                CwProjectReportSignature cwProjectReportSignature = cwProjectReportSignatureMapper.selectOne(new QueryWrapper<CwProjectReportSignature>().lambda()
                        .eq(CwProjectReportSignature::getReportId, report.getId())
                        .eq(CwProjectReportSignature::getType, report.getSignatureType())
                );
                if ("2".equals(cwProjectReportSignature.getStatus())){
                    cwProjectReportSignature.setStatus("6");
                    cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
                }else if ("6".equals(cwProjectReportSignature.getStatus())){
                    cwProjectReportSignature.setStatus("7");
                    cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
                }
            }
        } else {
            // 修改数据流程状态为->审核通过
            if (ObjectUtil.isNotEmpty(report)){
                CwProjectReportSignature cwProjectReportSignature = cwProjectReportSignatureMapper.selectOne(new QueryWrapper<CwProjectReportSignature>().lambda()
                        .eq(CwProjectReportSignature::getReportId, report.getId())
                        .eq(CwProjectReportSignature::getType, report.getSignatureType())
                );
                cwProjectReportSignature.setStatus("5");
                cwProjectReportSignatureMapper.updateById(cwProjectReportSignature);
            }
        }
    }

    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<WorkAttachment> infoList = reportMapper.findFileList(id);
        if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachment i : infoList) {
                if (!names.contains(i.getUrl())) {
                    ossServiceMapper.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) {
                WorkAttachment i = new WorkAttachment();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateDate(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateDate(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("cwWorkContract");
                i.setFileSize(dto.getSize());
                i.setSort(j);
                ossServiceMapper.insertWorkAttachment(i, userDTO);
                CwProjectReportFile reportFile = new CwProjectReportFile();
                BeanUtils.copyProperties(dto, reportFile);
                reportFile.setReportFileId(i.getId());
                attachmentMapper.insert(reportFile);
                j++;
            } else {
//                CwProjectReportFile reportFile = new CwProjectReportFile();
//                BeanUtils.copyProperties(dto, reportFile);
                attachmentMapper.updateFileInfo(dto);
            }
        }
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles2(List<WorkAttachmentDto> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentDto dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachment> infoList = reportMapper.findFileList(id);
        if (CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachment i : infoList) {
                if (!names.contains(i.getUrl())) {
                    ossServiceMapper.deleteById(i.getId());
                    List<String> fileId = attachmentMapper.getFileId(i.getId());
                    fileId.forEach(fid->{
                        attachmentMapper.deleteById(fid);
                    });

                }
            }
        }
        //保存信息
        for (WorkAttachmentDto dto : list) {
            //判断是否存在
            Integer isExit = reportMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachment i = new WorkAttachment();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateDate(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateDate(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("cwWorkContract");
                i.setFileSize(dto.getSize());
                i.setSort(j);
                ossServiceMapper.insertWorkAttachment(i, userDTO);
                j++;
            }
        }
    }

    /**
     * 根据报告签章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查询流程当前节点信息
            FlowNode currentTask = flowTaskService.getCurrentTask(processInstanceId);
            if(null != currentTask && StringUtils.isNotBlank(currentTask.getName())){
                map.put("success", true);
                map.put("message", "获取签章流程成功");
                map.put("signatureType", currentTask.getName());
            }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 "签章管理人审核":
                    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_date");
                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_date");
                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_date");
                return reportMapper.getByIds(queryWrapper);
            }
        }
        return new ArrayList<>();
    }
}
