package com.jeeplus.assess.program.configuration.projectList.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.assess.program.configuration.projectList.domain.*;
import com.jeeplus.assess.program.configuration.projectList.mapper.*;
import com.jeeplus.assess.program.configuration.projectList.service.dto.*;
import com.jeeplus.assess.program.configuration.projectList.service.mapstruct.ProgramAuditAssessPeopleWrapper;
import com.jeeplus.assess.program.configuration.projectList.service.mapstruct.ProgramAuditWrapper;
import com.jeeplus.assess.program.serviceType.service.ProgramServiceTypeService;
import com.jeeplus.assess.program.serviceType.service.dto.ProgramServiceTypeDTO;
import com.jeeplus.assess.proofread.domain.ProofreadDetail;
import com.jeeplus.assess.proofread.domain.ProofreadIssued;
import com.jeeplus.assess.proofread.service.ProofreadInfoService;
import com.jeeplus.assess.proofread.service.ProofreadIssuedService;
import com.jeeplus.assess.proofread.service.dto.ProofreadInfoDto;
import com.jeeplus.assess.workContract.domain.WorkContractInfo;
import com.jeeplus.assess.workContract.mapper.WorkContractInfoMapper;
import com.jeeplus.assess.workContract.service.WorkContractService;
import com.jeeplus.assess.workContract.service.dto.WorkContractInfoDto;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.flowable.feign.IFlowableApi;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
//import com.jeeplus.pubmodules.oss.service.OssService;
//import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
import com.jeeplus.sys.domain.User;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IRoleApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
//import com.jeeplus.sys.service.UserService;
//import com.jeeplus.sys.service.dto.DictValueDTO;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.dto.WorkAttachmentInfoDTO;
//import com.jeeplus.sys.utils.DictUtils;
//import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.compress.utils.Lists;
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.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProjectListService {

    @Autowired
    private ProjectListMapper projectListMapper;
    @Autowired
    private ProjectLinkMapper projectLinkMapper;
    @Autowired
    private ProjectMemberMapper projectMemberMapper;
    @Autowired
    private WorkContractInfoMapper workContractInfoMapper;
//    @Autowired
//    private OssServiceMapper ossServiceMapper;
//    @Autowired
//    private OssService ossService;
//    @Autowired
//    private SerialnumTplService serialnumTplService;
    @Autowired
    private WorkContractService workContractService;
    @Autowired
    private ProgramAuditMapper programAuditMapper;
    @Autowired
    private ProgramReportNoMapper programReportNoMapper;
    @Autowired
    private ProgramAuditAssessPeopleMapper programAuditAssessPeopleMapper;
    @Autowired
    private ProofreadInfoService proofreadInfoService;
    @Autowired
    private ProgramArchiveMapper programArchiveMapper;
    @Autowired
    private ProofreadIssuedService proofreadIssuedService;

    @Autowired
    private ProgramServiceTypeService programServiceTypeService;

    @Autowired
    private IFlowableApi flowTaskService;
    @Autowired
    private ProgramMembersService programMembersService;
//    @Autowired
//    private UserService userService;

    /**
     * getHaveProjectIds
     * @return
     */
    public ResponseEntity<String> getOverArchiveFlag(){
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        Integer overArchiveFlag = projectListMapper.getOverArchiveFlag(userDTO);
        if(overArchiveFlag>0){
            return ResponseEntity.ok("1");
        }
        return ResponseEntity.ok("0");
    }

    /**
     * 查询项目签发单完成后3天未归档项目信息
     * @return
     */
    public List<ProgramProjectListInfo> getOverdueFilingProjectList(){
        //获取3天前的时间
        String threeDayAgo = LocalDateTime.now().plusDays(-3).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //查询项目未归档且签发单完成时间在三天之前的项目
        List<ProgramProjectListInfo> list = projectListMapper.getOverdueFilingProjectList(threeDayAgo);
        return list;
    }

    /**
     * 修改报告归档 归档状态信息
     * @param id
     * @param archiveStatus 归档状态
     * @param overArchiveStatus 超期归档状态值（over_archive_status：0：未超期；1：已超期）
     */
    public void updateArchiveStatus(String id, String archiveStatus, String overArchiveStatus){
        projectListMapper.updateArchiveStatus(id, archiveStatus, overArchiveStatus);
    }

    public String save(ProjectListDto dto, String tabType) throws Exception{
        if (StringUtils.isNotEmpty(dto.getId())) {
            return update(dto);
        }
        return add(dto,tabType);
    }

    public String add(ProjectListDto dto,String tabType) throws Exception{
        String currentToken = TokenProvider.getCurrentToken();
        ProgramProjectListInfo info = new ProgramProjectListInfo();
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        // 保存项目管理列表主表信息
        BeanUtils.copyProperties(dto, info);
        String reportNo = "";
        String id = UUID.randomUUID().toString().replace("-", "");
        if (("true").equals(dto.getGenerateReportNumber())) {
            if(StringUtils.isNotBlank(info.getReportType())){
                if (info.getReportType().equals("1")){
                    reportNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE,currentToken);
                } else if (info.getReportType().equals("2")) {
                    reportNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE_,currentToken);
                }
                ProgramReportNo programReportNo = new ProgramReportNo();
                programReportNo.setProgramId(id);
                programReportNo.setReportNo(reportNo);
                programReportNoMapper.insert(programReportNo);
            }
        }
        //合同编号生成
        String no = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProjectListDto.BIZ_CODE,currentToken);
        //项目立项号生成
        String approvalNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProjectListDto.BIY_CODE,currentToken);
        info.setId(id);
        info.setNo(no);
        info.setApprovalNo(approvalNo);
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setDelFlag(0);
        info.setTabType(tabType);
        projectListMapper.insert(info);
        // 保存项目直接对接人信息
        if (CollectionUtils.isNotEmpty(dto.getLinks())) {
            for (ProgramProjectListLink link : dto.getLinks()) {
                link.setId(UUID.randomUUID().toString().replace("-", ""));
                link.setInfoId(id);
                link.setCreateById(userDTO.getId());
                link.setCreateTime(new Date());
                link.setUpdateById(userDTO.getId());
                link.setUpdateTime(new Date());
                link.setDelFlag(0);
                projectLinkMapper.insert(link);
            }
        }
        // 非主要项目组成员id集合
        List<String> memberIds = new ArrayList<>();
        // 要进行保存的项目组成员集合
        List<ProgramMembers> programMembers = new ArrayList<>();
        // 保存项目管理列表成员信息
        if (CollectionUtils.isNotEmpty(dto.getMembers())) {
            for (ProgramProjectListMember member : dto.getMembers()) {
                member.setId(UUID.randomUUID().toString().replace("-", ""));
                member.setInfoId(id);
                member.setCreateById(userDTO.getId());
                member.setCreateTime(new Date());
                member.setUpdateById(userDTO.getId());
                member.setUpdateTime(new Date());
                member.setDelFlag(0);
                projectMemberMapper.insert(member);
                if (StringUtils.isNotBlank(member.getUserId())) {
//                    成员的user_id不是"项目负责人"、"项目创建人"的添加到非主要项目组成员id集合中
                    if (!member.getUserId().equals(info.getProjectManager()) && !member.getUserId().equals(info.getCreateById())) {
                        memberIds.add(member.getUserId());
                    }
                }
            }
        }
        // 非主要项目组成员id集合去重后添加到项目组成员集合中
        if (CollectionUtil.isNotEmpty(memberIds)) {
            List<String> mids = memberIds.stream().distinct().collect(Collectors.toList());
            mids.stream().forEach(item -> {
                ProgramMembers p = new ProgramMembers();
                p.setIsImportant("0");  // 非主要成员
                p.setProjectId(id);
                p.setStatus("0");
                p.setUserId(item);  //  项目创建人
                programMembers.add(p);
            });
        }
        // 主要项目组成员去重后添加到项目组成员集合中
        ProgramMembers p = new ProgramMembers();
        p.setIsImportant("1");  // 主要成员
        p.setProjectId(id);
        p.setStatus("0");
        p.setUserId(info.getCreateById());  //  项目创建人
        programMembers.add(p);
        if (StringUtils.isNotBlank(info.getProjectManager())) {
            if (!info.getCreateById().equals(info.getProjectManager())) { // 项目创建人，项目负责人去重一下
                ProgramMembers m = new ProgramMembers();
                m.setIsImportant("1");  // 主要成员
                m.setProjectId(id);
                m.setStatus("0");
                m.setUserId(info.getProjectManager()); // 项目负责人
                programMembers.add(m);
            }
        }
        // 保存项目组成员
        programMembersService.saveBatch(programMembers);

        // 保存附件信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            workContractService.saveFiles(dto.getFiles(), userDTO, id);
        }
        // 三级校审添加
        ProgramAudit programAudit1 = new ProgramAudit();
        programAudit1.setAuditLevel("1");
        programAudit1.setProgramId(info.getId());
        programAudit1.setStatus("0");
        programAuditMapper.insert(programAudit1);
        ProgramAudit programAudit2 = new ProgramAudit();
        programAudit2.setAuditLevel("2");
        programAudit2.setProgramId(info.getId());
        programAudit2.setStatus("0");
        programAuditMapper.insert(programAudit2);
        ProgramAudit programAudit3 = new ProgramAudit();
        programAudit3.setAuditLevel("3");
        programAudit3.setProgramId(info.getId());
        programAudit3.setStatus("0");
        programAuditMapper.insert(programAudit3);
        // 项目归档添加
        ProgramArchive programArchive = new ProgramArchive();
        programArchive.setProgramId(info.getId());
        programArchive.setStatus("0");
        programArchiveMapper.insert(programArchive);
        // 当项目登记审核同意的时候，生成合同编号。根据createContractNo的值是“1”的时候，就是审核同意的时候
        if (ObjectUtil.isNotEmpty(dto)) {
            if (StringUtils.isNotBlank(dto.getCreateContractNo())) {
                if ("1".equals(dto.getCreateContractNo())) {
                    ProgramProjectListInfo programProjectListInfo = projectListMapper.getById(info.getId());
                    if (ObjectUtil.isNotEmpty(programProjectListInfo)) {
                        // 根据项目id查询关联的合同信息-》找到合同id
                        if (StringUtils.isNotBlank(programProjectListInfo.getContractId())) {
                            String contractId = programProjectListInfo.getContractId();
                            WorkContractInfo contract = workContractInfoMapper.findById(contractId);
                            if (ObjectUtil.isNotEmpty(contract) && StringUtils.isBlank(contract.getNo())) {
                                if (StringUtils.isNotBlank(programProjectListInfo.getReportType())) {
                                    if ("1".equals(programProjectListInfo.getReportType())) {
                                        // 生成合同编号-评估类
                                        String serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE,currentToken);
                                        // 根据合同id和合同编号来修改合同数据
                                        WorkContractInfo workContractInfo = new WorkContractInfo();
                                        workContractInfo.setNo(serialNum);
                                        workContractInfoMapper.update(workContractInfo, new QueryWrapper<WorkContractInfo>().lambda().eq(WorkContractInfo::getId, contractId));
                                    }else if("2".equals(programProjectListInfo.getReportType())){
                                        // 生成合同编号-咨询类
                                        String serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE_,currentToken);
                                        // 根据合同id和合同编号来修改合同数据
                                        WorkContractInfo workContractInfo = new WorkContractInfo();
                                        workContractInfo.setNo(serialNum);
                                        workContractInfoMapper.update(workContractInfo, new QueryWrapper<WorkContractInfo>().lambda().eq(WorkContractInfo::getId, contractId));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return id;
    }

    public String saveFormArchive(ProgramArchiveDto programArchiveDto) {
//        ProgramArchive programArchive = ProgramArchiveWrapper.INSTANCE.toEntity(programArchiveDto);
        //根据归档id 查询该归档信息是否为超期归档
        ProgramArchiveDto archive = programArchiveMapper.findByIdArchive(programArchiveDto.getId());
        if(null != archive && StringUtils.isNotBlank(archive.getOverArchiveStatus()) && "1".equals(archive.getOverArchiveStatus()) && "5".equals(programArchiveDto.getStatus())){
            programArchiveDto.setStatus("7");
        }

        ProgramArchive programArchive = new ProgramArchive();
        BeanUtils.copyProperties(programArchiveDto, programArchive);
        if (StringUtils.isNotBlank(programArchive.getId())){
            programArchiveMapper.updateById(programArchive);
        }else{
            programArchiveMapper.insert(programArchive);
        }
        String currentToken = TokenProvider.getCurrentToken();
        if (ObjectUtil.isNotEmpty(programArchiveDto)) {
            Map<String,String> map = new HashMap<>();
            String fileList = JSON.toJSONString((programArchiveDto.getReportFileList()));
            String attachmentId = programArchive.getId();
            String attachmentFlag = "report";
            map.put("fileList",fileList);
            map.put("attachmentId",attachmentId);
            map.put("attachmentFlag",attachmentFlag);
            map.put("currentToken", TokenProvider.getCurrentToken ( ));
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileListFlag(map);
            fileList = JSON.toJSONString((programArchiveDto.getDetailFileList()));
            attachmentFlag = "detail";
            map.put("fileList",fileList);
            map.put("attachmentFlag",attachmentFlag);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileListFlag(map);
            fileList = JSON.toJSONString((programArchiveDto.getExplainFileList()));
            attachmentFlag = "explain";
            map.put("fileList",fileList);
            map.put("attachmentFlag",attachmentFlag);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileListFlag(map);
            fileList = JSON.toJSONString((programArchiveDto.getPapersFileList()));
            attachmentFlag = "papers";
            map.put("fileList",fileList);
            map.put("attachmentFlag",attachmentFlag);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileListFlag(map);
            fileList = JSON.toJSONString((programArchiveDto.getOtherFileList()));
            attachmentFlag = "other";
            map.put("fileList",fileList);
            map.put("attachmentFlag",attachmentFlag);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileListFlag(map);
        }
        return programArchive.getId();
    }

    public String saveFormThree(ProgramAuditDto programAuditDto) throws Exception {
        String currentToken = TokenProvider.getCurrentToken();
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        ProgramAudit programAudit = ProgramAuditWrapper.INSTANCE.toEntity(programAuditDto);
        //生成项目报告号
        ProgramProjectListInfo projectListInfo = projectListMapper.getById(programAuditDto.getProgramId());
        String reportNo = "";
        if (StringUtils.isNotEmpty(programAuditDto.getProcInsId())) {
            String currentTaskName = flowTaskService.getCurrentTaskName(programAuditDto.getProcInsId());
            if(null != currentTaskName && StringUtils.isNotBlank(currentTaskName)) {
                if ("三级校审".equals(currentTaskName)) {
                    if (programAuditDto.getStatus().equals("5")) {
                        if (projectListInfo.getGenerateReportNumber().equals("false")) {
                            if(StringUtils.isNotBlank(projectListInfo.getReportType())){
                                if (projectListInfo.getReportType().equals("1")){
                                    reportNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE,currentToken);
                                } else if (projectListInfo.getReportType().equals("2")) {
                                    reportNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE_,currentToken);
                                }
                                ProgramReportNo programReportNo = new ProgramReportNo();
                                programReportNo.setProgramId(projectListInfo.getId());
                                programReportNo.setReportNo(reportNo);
                                programReportNoMapper.insert(programReportNo);
                            }
                        }
                    }
                }
            }
        }

        if (StringUtils.isNotBlank(programAudit.getId())){
            programAuditMapper.updateById(programAudit);
        }else{
            programAuditMapper.insert(programAudit);
        }
        if (ObjectUtil.isNotEmpty(programAuditDto)) {
            //附件
            Map<String,String> map = new HashMap<>();
            String fileList = JSON.toJSONString((programAuditDto.getWorkAttachmentDtoList()));
            String attachmentId = programAudit.getId();
            String attachmentFlag = "program";
            map.put("fileList",fileList);
            map.put("attachmentId",attachmentId);
            map.put("attachmentFlag",attachmentFlag);
            map.put("currentToken", TokenProvider.getCurrentToken ( ));
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map);
            //专业评估人员
            if (CollectionUtil.isNotEmpty(programAuditDto.getProgramAuditAssessPeopleDtoList())) {
                programAuditAssessPeopleMapper.delete(new QueryWrapper<ProgramAuditAssessPeople>().lambda().eq(ProgramAuditAssessPeople::getAuditId,programAudit.getId()));
                programAuditDto.getProgramAuditAssessPeopleDtoList().stream().forEach(item->{
                    ProgramAuditAssessPeople programAuditAssessPeople = ProgramAuditAssessPeopleWrapper.INSTANCE.toEntity(item);
                    programAuditAssessPeopleMapper.insert(programAuditAssessPeople);
                });
            }else{
                programAuditAssessPeopleMapper.delete(new QueryWrapper<ProgramAuditAssessPeople>().lambda().eq(ProgramAuditAssessPeople::getAuditId,programAudit.getId()));
            }
        }
        return programAudit.getId();
    }

    public String update(ProjectListDto dto) throws Exception{
        String currentToken = TokenProvider.getCurrentToken();
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        // 修改项目管理列表主表信息
        ProgramProjectListInfo info = new ProgramProjectListInfo();
        BeanUtils.copyProperties(dto, info);
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setDelFlag(0);
        projectListMapper.updateById(info);
        String reportNo = "";
        if (("true").equals(dto.getGenerateReportNumber())) {
            ProgramReportNo programReportNo = programReportNoMapper.selectByProgramId(info.getId());
            if (null == programReportNo) {
                if(StringUtils.isNotBlank(info.getReportType())){
                    if (info.getReportType().equals("1")){
                        reportNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE,currentToken);
                    } else if (info.getReportType().equals("2")) {
                        reportNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE_,currentToken);
                    }
                    programReportNo = new ProgramReportNo();
                    programReportNo.setProgramId(info.getId());
                    programReportNo.setReportNo(reportNo);
                    programReportNoMapper.insert(programReportNo);
                }
            }

        }
        // 修改联系人信息(先删除原有数据，再保存)
        projectLinkMapper.deleteByInfoId(dto.getId());
        if (CollectionUtils.isNotEmpty(dto.getLinks())) {
            for (ProgramProjectListLink link : dto.getLinks()) {
                link.setId(UUID.randomUUID().toString().replace("-", ""));
                link.setInfoId(dto.getId());
                link.setCreateById(userDTO.getId());
                link.setCreateTime(new Date());
                link.setUpdateById(userDTO.getId());
                link.setUpdateTime(new Date());
                link.setDelFlag(0);
                projectLinkMapper.insert(link);
            }
        }
        // 非主要项目组成员id集合
        List<String> memberIds = new ArrayList<>();
        // 要进行保存的项目组成员集合
        List<ProgramMembers> programMembers = new ArrayList<>();
        //  删除此项目的项目组成员信息(先删除原有数据，再保存)
        programMembersService.remove(new QueryWrapper<ProgramMembers>().lambda().eq(ProgramMembers::getProjectId,dto.getId()));
        // 修改项目管理列表成员信息(先删除原有数据，再保存)
        projectMemberMapper.deleteByInfoId(dto.getId());
        if (CollectionUtils.isNotEmpty(dto.getMembers())) {
            for (ProgramProjectListMember member : dto.getMembers()) {
                member.setId(UUID.randomUUID().toString().replace("-", ""));
                member.setInfoId(dto.getId());
                member.setCreateById(userDTO.getId());
                member.setCreateTime(new Date());
                member.setUpdateById(userDTO.getId());
                member.setUpdateTime(new Date());
                member.setDelFlag(0);
                projectMemberMapper.insert(member);
                if (StringUtils.isNotBlank(member.getUserId())) {
//                    成员的user_id不是"项目负责人"、"项目创建人"的添加到非主要项目组成员id集合中
                    if (!member.getUserId().equals(info.getProjectManager()) && !member.getUserId().equals(info.getCreateById())) {
                        memberIds.add(member.getUserId());
                    }
                }
            }
        }
        // 非主要项目组成员id集合去重后添加到项目组成员集合中
        if (CollectionUtil.isNotEmpty(memberIds)) {
            List<String> mids = memberIds.stream().distinct().collect(Collectors.toList());
            mids.stream().forEach(item -> {
                ProgramMembers p = new ProgramMembers();
                p.setIsImportant("0");  // 非主要成员
                p.setProjectId(dto.getId());
                p.setStatus("0");
                p.setUserId(item);  //  项目创建人
                programMembers.add(p);
            });
        }
        // 主要项目组成员去重后添加到项目组成员集合中
        ProgramProjectListInfo byId1 = projectListMapper.selectById(dto.getId());
        ProgramMembers p = new ProgramMembers();
        p.setIsImportant("1");  // 主要成员
        p.setProjectId(dto.getId());
        p.setStatus("0");
        p.setUserId(byId1.getCreateById());  //  项目创建人
        programMembers.add(p);
        if (StringUtils.isNotBlank(info.getProjectManager())) {
            ProgramProjectListInfo byId = projectListMapper.getById(dto.getId());
            if (!byId.getCreateById().equals(info.getProjectManager())) { // 项目创建人，项目负责人去重一下
                ProgramMembers m = new ProgramMembers();
                m.setIsImportant("1");  // 主要成员
                m.setProjectId(dto.getId());
                m.setStatus("0");
                m.setUserId(info.getProjectManager()); // 项目负责人
                programMembers.add(m);
            }
        }
        // 保存项目组成员
        programMembersService.saveBatch(programMembers);

        // 修改附件信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            workContractService.updateFiles(dto.getFiles(), userDTO, dto.getId());
        }
        // 当项目登记审核同意的时候，生成合同编号。根据createContractNo的值是“1”的时候，就是审核同意的时候
        if (ObjectUtil.isNotEmpty(dto)) {
            if (StringUtils.isNotBlank(dto.getCreateContractNo())) {
                if ("1".equals(dto.getCreateContractNo())) {
                    ProgramProjectListInfo programProjectListInfo = projectListMapper.getById(info.getId());
                    if (ObjectUtil.isNotEmpty(programProjectListInfo)) {
                        // 根据项目id查询关联的合同信息-》找到合同id
                        if (StringUtils.isNotBlank(programProjectListInfo.getContractId())) {
                            String contractId = programProjectListInfo.getContractId();
                            WorkContractInfo contract = workContractInfoMapper.findById(contractId);
                            if (ObjectUtil.isNotEmpty(contract) && StringUtils.isBlank(contract.getNo())) {
                                if (StringUtils.isNotBlank(programProjectListInfo.getReportType())) {
                                    if ("1".equals(programProjectListInfo.getReportType())) {
                                        // 生成合同编号-评估类
                                        String serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE,currentToken);
                                        // 根据合同id和合同编号来修改合同数据
                                        WorkContractInfo workContractInfo = new WorkContractInfo();
                                        workContractInfo.setNo(serialNum);
                                        workContractInfoMapper.update(workContractInfo, new QueryWrapper<WorkContractInfo>().lambda().eq(WorkContractInfo::getId, contractId));
                                    }else if("2".equals(programProjectListInfo.getReportType())){
                                        // 生成合同编号-咨询类
                                        String serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE_,currentToken);
                                        // 根据合同id和合同编号来修改合同数据
                                        WorkContractInfo workContractInfo = new WorkContractInfo();
                                        workContractInfo.setNo(serialNum);
                                        workContractInfoMapper.update(workContractInfo, new QueryWrapper<WorkContractInfo>().lambda().eq(WorkContractInfo::getId, contractId));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return dto.getId();
    }

    public ProjectListDto findById(String id) {
        ProjectListDto dto = new ProjectListDto();
        // 查询主表信息
        ProgramProjectListInfo info = projectListMapper.getById(id);
        BeanUtils.copyProperties(info, dto);
        // 查询联系人列表
        LambdaQueryWrapper<ProgramProjectListLink> linkWrapper = new LambdaQueryWrapper<>();
        linkWrapper.eq(ProgramProjectListLink::getInfoId, id);
        linkWrapper.eq(ProgramProjectListLink::getDelFlag, 0);
        List<ProgramProjectListLink> links = projectLinkMapper.selectList(linkWrapper);
        if (CollectionUtils.isNotEmpty(links)) {
            dto.setLinks(links);
        }
        // 查询成员列表
        LambdaQueryWrapper<ProgramProjectListMember> memberWrapper = new LambdaQueryWrapper<>();
        memberWrapper.eq(ProgramProjectListMember::getInfoId, id);
        memberWrapper.eq(ProgramProjectListMember::getDelFlag, 0);
        List<ProgramProjectListMember> members = projectMemberMapper.selectList(memberWrapper);
        if (CollectionUtils.isNotEmpty(members)) {
            members.stream().forEach(member -> {
                if (StringUtils.isNotBlank(member.getUserId())) {
                    UserDTO byId = SpringUtil.getBean ( IUserApi.class ).getById(member.getUserId());
                    if (ObjectUtil.isNotEmpty(byId)) {
                        member.setName(byId.getName());
                    }
                }
            });
            dto.setMembers(members);
        }
        // 查询附件信息
        List<WorkAttachmentInfo> files = workContractInfoMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentInfo i : files) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            dto.setFiles(files);
        }
        return dto;
    }

    public ProgramAuditDto findByIdAudit(String id){
        ProgramAuditDto byIdAudit = programAuditMapper.findByIdAudit(id);
        // 查询附件信息
        List<WorkAttachmentInfo> files = workContractInfoMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentInfo i : files) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            byIdAudit.setWorkAttachmentDtoList(files);
        }
        //根据项目的id去查校审的id
        List<String> ids = programAuditMapper.getIDsByProId(byIdAudit.getProgramId());
        if (ids.size() >= 1) {
            byIdAudit.setId1(ids.get(0));
        }
        if (ids.size() >= 2) {
            byIdAudit.setId2(ids.get(1));
        }
        if (ids.size() >= 3) {
            byIdAudit.setId3(ids.get(2));
        }
        return byIdAudit;
    }

    public ProgramArchiveDto findByIdArchive(String id){
        ProgramArchiveDto programArchiveDto = programArchiveMapper.findByIdArchive(id);
        if(ObjectUtil.isNotEmpty(programArchiveDto)){
            if(ObjectUtil.isNotEmpty(programArchiveDto.getProgramProjectListInfo())){
                if(StringUtils.isNotBlank(programArchiveDto.getProgramProjectListInfo().getProjectManager())){
                    UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getById(programArchiveDto.getProgramProjectListInfo().getProjectManager());
                    programArchiveDto.getProgramProjectListInfo().setOfficeId(userDTO.getOfficeDTO().getName());
                }
            }
        }
        // 查询附件信息 - 评估报告
        List<WorkAttachmentInfoDTO> reportFileList = workContractInfoMapper.findByAttachmentIdAndFlag(id, "report");
        if (CollectionUtils.isNotEmpty(reportFileList)) {
            for (WorkAttachmentInfoDTO i : reportFileList) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            programArchiveDto.setReportFileList(reportFileList);
        }

        // 查询附件信息 - 评估说明
        List<WorkAttachmentInfoDTO> explainFileList = workContractInfoMapper.findByAttachmentIdAndFlag(id, "explain");
        if (CollectionUtils.isNotEmpty(explainFileList)) {
            for (WorkAttachmentInfoDTO i : explainFileList) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            programArchiveDto.setExplainFileList(explainFileList);
        }

        // 查询附件信息 - 评估明细表
        List<WorkAttachmentInfoDTO> detailFileList = workContractInfoMapper.findByAttachmentIdAndFlag(id, "detail");
        if (CollectionUtils.isNotEmpty(detailFileList)) {
            for (WorkAttachmentInfoDTO i : detailFileList) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            programArchiveDto.setDetailFileList(detailFileList);
        }

        // 查询附件信息 - 评估操作计算底稿
        List<WorkAttachmentInfoDTO> papersFileList = workContractInfoMapper.findByAttachmentIdAndFlag(id, "papers");
        if (CollectionUtils.isNotEmpty(papersFileList)) {
            for (WorkAttachmentInfoDTO i : papersFileList) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            programArchiveDto.setPapersFileList(papersFileList);
        }

        // 查询附件信息 - 其他
        List<WorkAttachmentInfoDTO> otherFileList = workContractInfoMapper.findByAttachmentIdAndFlag(id, "other");
        if (CollectionUtils.isNotEmpty(otherFileList)) {
            for (WorkAttachmentInfoDTO i : otherFileList) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            programArchiveDto.setOtherFileList(otherFileList);
        }


        return programArchiveDto;
    }

    public String deleteById(String id) {
        projectListMapper.deleteById(id);
        projectLinkMapper.deleteByInfoId(id);
        projectMemberMapper.deleteByInfoId(id);
        // 附件删除
//        LambdaQueryWrapper<WorkAttachmentInfo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(WorkAttachmentInfo::getAttachmentId, id);
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        return "删除项目成功";
    }

    public IPage<WorkContractInfo> findContractPageList(ContractDto dto, Page<WorkContractInfo> page) {
        return projectListMapper.findContractPageList(page, dto);
    }

    public String updateStatusById(ProjectListDto dto) {
        projectListMapper.updateStatusById(dto.getId(), dto.getStatus());
        return "操作成功";
    }

    public String updateStatusByAuditId(ProjectListDto dto) {
        ProgramAudit programAudit = new ProgramAudit();
        programAudit.setId(dto.getId());
        programAudit.setStatus(dto.getStatus());
        programAuditMapper.update(programAudit,new QueryWrapper<ProgramAudit>().lambda().eq(ProgramAudit::getId,programAudit.getId()));
        return "操作成功";
    }

    public String updateStatusByArchiveId(ProjectListDto dto) {
        ProgramArchive programArchive = new ProgramArchive();
        programArchive.setId(dto.getId());
        programArchive.setStatus(dto.getStatus());
        programArchiveMapper.update(programArchive,new QueryWrapper<ProgramArchive>().lambda().eq(ProgramArchive::getId,programArchive.getId()));
        return "操作成功";
    }

    public IPage<ProgramProjectListInfo> list(Page<ProgramProjectListInfo> page, ProgramProjectListInfo info, String tabType) throws Exception{
        QueryWrapper<ProgramProjectListInfo> wrapper = QueryWrapperGenerator.buildQueryCondition(info, ProgramProjectListInfo.class);
        if (ObjectUtil.isNotEmpty(info) && StringUtils.isNotBlank(info.getCreateById())) {
            wrapper.eq("a.create_by_id", info.getCreateById());
        }
        wrapper.eq("a.del_flag", "0");
        wrapper.eq("a.tab_type", tabType);
        if (info.getCreateDates() != null && info.getCreateDates().length > 0) {
            wrapper.between("a.create_time", info.getCreateDates()[0], info.getCreateDates()[1]);
        }
        if (StringUtils.isNotBlank(info.getStatus1())){
            wrapper.eq("pa1.status", info.getStatus1());
        }
        if (StringUtils.isNotBlank(info.getStatus2())){
            wrapper.eq("pa2.status", info.getStatus2());
        }
        if (StringUtils.isNotBlank(info.getStatus3())){
            wrapper.eq("pa3.status", info.getStatus3());
        }
        if (StringUtils.isNotBlank(info.getIssuedStatus())){
            if (info.getIssuedStatus().equals("0")){
                wrapper.isNull("d.status");
            }else {
                wrapper.eq("d.status", info.getIssuedStatus());
            }
        }
        if (StringUtils.isNotBlank(info.getArchiveStatus())){
            wrapper.eq("pa.status", info.getArchiveStatus());
        }
        /*//获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        //获取当前登录人所属角色
        //若是评估部门主任，则仅展示部门主任信息
        //若是评估员工，则仅展示自己的数据信息
        List<RoleDTO> roleDTOList = userDTO.getRoleDTOList();
        for (RoleDTO roleDTO : roleDTOList) {
            //根据角色id查询角色信息
            RoleDTO roleDTOById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
            if("yg".equals(roleDTOById.getEnName()) && "评估员工".equals(roleDTOById.getName())){
                wrapper.eq("a.create_by_id", userDTO.getId());
                break;
            }else if("bmzr".equals(roleDTOById.getEnName()) && "评估部门主任".equals(roleDTOById.getName())){
                wrapper.eq("b.office_id", userDTO.getOfficeDTO().getId());
                break;
            }
        }*/
        IPage<ProgramProjectListInfo> pageList = projectListMapper.findPageList(page, wrapper);
        pageList.getRecords().stream().forEach(item ->{
            // 查询关联发票的开票状态
            if (StringUtils.isNotBlank(info.getShowInvoiceFlag()) && "1".equals(info.getShowInvoiceFlag())) {
                String isInvoice = projectListMapper.selectInvoiceFlag(item.getId());
                item.setIsInvoice(isInvoice);
            }
            // 项目登记
            if (StringUtils.isNotBlank(item.getTaskId()) && StringUtils.isNotBlank(item.getStatus())) {
                if ("2".equals(item.getStatus())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIds(flowTaskService.getTaskAuditUsers(item.getTaskId()));  // 获取数据审核人
                }
            }
            // 一级校审
            if (StringUtils.isNotBlank(item.getTaskIdAudit1()) && StringUtils.isNotBlank(item.getStatus1())) {
                if ("2".equals(item.getStatus1())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIds1(flowTaskService.getTaskAuditUsers(item.getTaskIdAudit1()));  // 获取数据审核人
                }
            }
            // 二级校审
            if (StringUtils.isNotBlank(item.getTaskIdAudit2()) && StringUtils.isNotBlank(item.getStatus2())) {
                if ("2".equals(item.getStatus2())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIds2(flowTaskService.getTaskAuditUsers(item.getTaskIdAudit2()));  // 获取数据审核人
                }
            }
            // 三级校审
            if (StringUtils.isNotBlank(item.getTaskIdAudit3()) && StringUtils.isNotBlank(item.getStatus3())) {
                if ("2".equals(item.getStatus3())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIds3(flowTaskService.getTaskAuditUsers(item.getTaskIdAudit3()));  // 获取数据审核人
                }
            }
            // 签发
            if (StringUtils.isNotBlank(item.getTaskIdIssued()) && StringUtils.isNotBlank(item.getIssuedStatus())) {
                if ("2".equals(item.getIssuedStatus())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIdsIssued(flowTaskService.getTaskAuditUsers(item.getTaskIdIssued()));  // 获取数据审核人
                }
            }
            // 归档
            if (StringUtils.isNotBlank(item.getTaskIdArchive()) && StringUtils.isNotBlank(item.getArchiveStatus())) {
                if ("2".equals(item.getArchiveStatus())) { // “审核中”的数据要获取数据审核人
                    item.setAuditUserIdsArchive(flowTaskService.getTaskAuditUsers(item.getTaskIdArchive()));  // 获取数据审核人
                }
            }
        });
        return pageList;
    }
    /**
     * 项目登记列表,和上面list接口是一样的，目的时跳过list mapper接口的数据规则（比如仅部门可见、仅自己可见之类的）
     */
    public IPage<ProgramProjectListInfo> list2(Page<ProgramProjectListInfo> page, ProgramProjectListInfo info, String tabType) throws Exception{
        QueryWrapper<ProgramProjectListInfo> wrapper = QueryWrapperGenerator.buildQueryCondition(info, ProgramProjectListInfo.class);
        wrapper.eq("a.del_flag", "0");
        wrapper.eq("a.tab_type", tabType);
        if (info.getCreateDates() != null) {
            wrapper.between("a.create_date", info.getCreateDates()[0], info.getCreateDates()[1]);
        }
        IPage<ProgramProjectListInfo> pageList = projectListMapper.findPageList2(page, wrapper);
        pageList.getRecords().stream().forEach(item ->{
            String isInvoice = projectListMapper.selectInvoiceFlag(item.getId());
            item.setIsInvoice(isInvoice);
        });
        return pageList;
    }

    public List<ExportFileDto> exportList(List<ProgramProjectListInfo> infoList){
        List<ExportFileDto> list = projectListMapper.findList(infoList);
        return list;
    }

    public String saveReportNo(String id) throws Exception{
        String currentToken = TokenProvider.getCurrentToken();
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        ProgramProjectListInfo programProjectListInfo = projectListMapper.selectById(id);
        String reportNo = "";
        if(ObjectUtil.isNotEmpty(programProjectListInfo)){
            if(StringUtils.isNotBlank(programProjectListInfo.getReportType())){
                if (programProjectListInfo.getReportType().equals("1")){
                    reportNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE,currentToken);
                } else if (programProjectListInfo.getReportType().equals("2")) {
                    reportNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE_,currentToken);
                }
                ProgramReportNo programReportNo = new ProgramReportNo();
                programReportNo.setProgramId(id);
                programReportNo.setReportNo(reportNo);
                programReportNoMapper.insert(programReportNo);
            }
        }
        return reportNo;
    }

    /**
     * 查询校审数据信息并导出文档
     * @param info
     * @return
     */
    public Map<String,Object> getAuditInfoMap(ProgramProjectListInfo info){
        Map data = new HashMap();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年 MM月 dd日");

        //查询项目信息
        ProjectListDto projectDto = findById(info.getId());

        //查询校审信息
        ProgramAuditDto auditDto =null;
        if(StringUtils.isNotBlank(info.getAuditId1())){
            auditDto = findByIdAudit(info.getAuditId1());
        }else if(StringUtils.isNotBlank(info.getAuditId2())) {
            auditDto = findByIdAudit(info.getAuditId2());
        }else if(StringUtils.isNotBlank(info.getAuditId3())) {
            auditDto = findByIdAudit(info.getAuditId3());
        }
        //项目名称
        if(StringUtils.isNotBlank(projectDto.getName())){
            data.put("projectName",projectDto.getName());
        }else{
            data.put("projectName","");
        }
        //评估基准日
        Date assessmentDate=projectDto.getAssessmentDate();
        if(null == assessmentDate){
            data.put("assessBaseMessage","");
        }else{
            String str = sdf.format(assessmentDate);
            data.put("assessBaseMessage",str);
        }
        //项目负责人
        if(StringUtils.isBlank(projectDto.getProjectManager())){
            data.put("projectMaster","");
        }else{
            data.put("projectMaster",SpringUtil.getBean ( IUserApi.class ).getById(projectDto.getProjectManager()).getName());
        }
        //如果存在审核意见则进行处理
        if(null != auditDto){
            //专业评估人员
            List<ProgramAuditAssessPeopleDto> programAuditAssessPeopleDtoList = auditDto.getProgramAuditAssessPeopleDtoList();
            List<String> appraiserList = Lists.newArrayList();
            for (ProgramAuditAssessPeopleDto assessPeopleDto:programAuditAssessPeopleDtoList) {
                appraiserList.add(SpringUtil.getBean ( IUserApi.class ).getById(assessPeopleDto.getAssessPeople()).getName());
            }
            data.put("appraisers",String.join(",",appraiserList));

            //项目审核人
            data.put("projectauditor",SpringUtil.getBean ( IUserApi.class ).getById(auditDto.getAuditPeople()).getName());
            //明细表
            data.put("detailedStatement",disposeAuditDetails(auditDto.getDetailOpinion()));
            //评估报告
            data.put("assessmentReport",disposeAuditDetails(auditDto.getReportOpinion()));
            //技术说明
            data.put("technicalDescription",disposeAuditDetails(auditDto.getRemarksOpinion()));
            //工作底稿
            data.put("workingPaper",disposeAuditDetails(auditDto.getWorkOpinion()));
            //保留意见
            data.put("qualifiedOpinion",auditDto.getRetainOpinion());
            //执行人
            data.put("executor",SpringUtil.getBean ( IUserApi.class ).getById(auditDto.getCreateBy().getId()).getName());

            Date auditDate=projectDto.getAgreeTime();
            if(null == auditDate){
                //执行人时间
                data.put("executorDate","");
                //审核人时间
                data.put("auditorDate","");
            }else{
                String str = sdf.format(auditDate);
                //执行人时间
                data.put("executorDate",str);
                //审核人时间
                data.put("auditorDate",str);
            }

            //未修改意见
            data.put("notModifiedOpinion",auditDto.getChangeOpinion());
            //审核人
            data.put("auditor",SpringUtil.getBean ( IUserApi.class ).getById(auditDto.getAuditPeople()).getName());

        }else{
            data.put("appraisers","");
            //执行人时间
            data.put("executorDate","");
            //审核人时间
            data.put("auditorDate","");
            //项目审核人
            data.put("projectauditor","");
            //明细表
            data.put("detailedStatement","");
            //评估报告
            data.put("assessmentReport","");
            //技术说明
            data.put("technicalDescription","");
            //工作底稿
            data.put("workingPaper","");
            //保留意见
            data.put("qualifiedOpinion","");
            //执行人
            data.put("executor","");
            //未修改意见
            data.put("notModifiedOpinion","");
            //审核人
            data.put("auditor","");
        }
        return data;
    }

    /**
     * 审核内容处理
     * @param auditDetails
     * @return
     */
    private String disposeAuditDetails(String auditDetails){
        if(StringUtils.isNotBlank(auditDetails)){
            auditDetails = auditDetails.replaceAll("<p>","");
            auditDetails = auditDetails.replaceAll("</p>","<w:br/>");
            auditDetails = auditDetails.replaceAll("<br>","");
            auditDetails = auditDetails.replaceAll("&nbsp;","");
        }
        return auditDetails;
    }



    /**
     * 查询校审数据信息并导出文档
     * @param info
     * @return
     */
    public Map<String,Object> getProofreadAuditMap(ProgramProjectListInfo info){
        Map data = new HashMap();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年 MM月 dd日");

        //查询项目信息
        ProjectListDto projectDto = findById(info.getId());

        //查询自校数据信息信息
        ProofreadInfoDto proofreadInfoDto = proofreadInfoService.findById(info.getId(),"1");

        /**
         * 自校明细表信息
         */
        List<ProofreadDetail> details = proofreadInfoDto.getDetails();
        List<ProofreadDetail> detailedStatementList = Lists.newArrayList();
        List<ProofreadDetail> assessmentInstructions1List = Lists.newArrayList();
        List<ProofreadDetail> assessmentInstructions2List = Lists.newArrayList();
        List<ProofreadDetail> assessmentInstructions3List = Lists.newArrayList();
        List<ProofreadDetail> assessmentInstructions4List = Lists.newArrayList();
        List<ProofreadDetail> assessmentInstructions5List = Lists.newArrayList();
        List<ProofreadDetail> assessmentReportList = Lists.newArrayList();
        Integer detailedStatement = 0;
        Integer assessmentInstructions1 = 0;
        Integer assessmentInstructions2 = 0;
        Integer assessmentInstructions3 = 0;
        Integer assessmentInstructions4 = 0;
        Integer assessmentInstructions5 = 0;
        Integer assessmentReport = 0;

        for (ProofreadDetail item :details) {
            if(item.getSort().startsWith("1010")){
                detailedStatement ++ ;
                item.setSerialNumber(detailedStatement);
                detailedStatementList.add(item);
            }else if(item.getSort().startsWith("2010")){
                assessmentInstructions1 ++ ;
                item.setSerialNumber(assessmentInstructions1);
                assessmentInstructions1List.add(item);
            }else if(item.getSort().startsWith("2020")){
                assessmentInstructions2 ++ ;
                item.setSerialNumber(assessmentInstructions2);
                assessmentInstructions2List.add(item);
            }else if(item.getSort().startsWith("2030")){
                assessmentInstructions3 ++ ;
                item.setSerialNumber(assessmentInstructions3);
                assessmentInstructions3List.add(item);
            }else if(item.getSort().startsWith("2040")){
                assessmentInstructions4 ++ ;
                item.setSerialNumber(assessmentInstructions4);
                assessmentInstructions4List.add(item);
            }else if(item.getSort().startsWith("2050")){
                assessmentInstructions5 ++ ;
                item.setSerialNumber(assessmentInstructions5);
                assessmentInstructions5List.add(item);
            }else if(item.getSort().startsWith("2060")){

            }else if(item.getSort().startsWith("30")){
                assessmentReport ++ ;
                item.setSerialNumber(assessmentReport);
                assessmentReportList.add(item);
            }

        }
        data.put("detailedStatementList",detailedStatementList);
        data.put("assessmentInstructions1List",assessmentInstructions1List);
        data.put("assessmentInstructions2List",assessmentInstructions2List);
        data.put("assessmentInstructions3List",assessmentInstructions3List);
        data.put("assessmentInstructions4List",assessmentInstructions4List);
        data.put("assessmentInstructions5List",assessmentInstructions5List);
        data.put("assessmentReportList",assessmentReportList);


        //项目名称
        if(StringUtils.isNotBlank(projectDto.getName())){
            data.put("projectName",projectDto.getName());
        }else{
            data.put("projectName","");
        }
        //评估基准日
        Date assessmentDate=projectDto.getAssessmentDate();
        if(null == assessmentDate){
            data.put("assessBaseMessage","");
        }else{
            String str = sdf.format(assessmentDate);
            data.put("assessBaseMessage",str);
        }
        //项目负责人
        if(StringUtils.isBlank(projectDto.getProjectManager())){
            data.put("projectMaster","");
        }else{
            data.put("projectMaster",SpringUtil.getBean ( IUserApi.class ).getById(projectDto.getProjectManager()).getName());
        }

        //项目审核人
        if(StringUtils.isBlank(projectDto.getAgreeUserId())){
            data.put("projectauditor","");
        }else{
            data.put("projectauditor",SpringUtil.getBean ( IUserApi.class ).getById(projectDto.getProjectManager()).getName());
        }
        //项目审核时间
        Date agreeTime=projectDto.getAgreeTime();
        if(null == agreeTime){
            data.put("projectAuditDate","");
            data.put("auditDate","");
        }else{
            String str = sdf.format(agreeTime);
            data.put("projectAuditDate",str);
            data.put("auditDate",str);
        }
        //审核人员签字
        if(StringUtils.isBlank(proofreadInfoDto.getUpdateById())){
            data.put("auditPersonnel","");
            data.put("correctPersonnel","");
            data.put("executor","");
        }else{
            data.put("auditPersonnel",SpringUtil.getBean ( IUserApi.class ).getById(proofreadInfoDto.getUpdateById()).getName());
            //改正人员签字
            data.put("correctPersonnel",SpringUtil.getBean ( IUserApi.class ).getById(proofreadInfoDto.getUpdateById()).getName());
            //执行人
            data.put("executor",SpringUtil.getBean ( IUserApi.class ).getById(proofreadInfoDto.getUpdateById()).getName());
        }
        //保留意见
        if(StringUtils.isBlank(proofreadInfoDto.getReservations())){
            data.put("qualifiedOpinion","");
        }else{
            data.put("qualifiedOpinion",proofreadInfoDto.getReservations());
        }
        //未修改意见
        if(StringUtils.isBlank(proofreadInfoDto.getUnmodifiedComments())){
            data.put("notModifiedOpinion","");
        }else{
            data.put("notModifiedOpinion",proofreadInfoDto.getUnmodifiedComments());
        }
        //执行时间
        //改正人员签字时间
        Date executorDate=proofreadInfoDto.getUpdateTime();
        if(null == executorDate){
            data.put("correctDate","");
            data.put("executorDate","");
        }else{
            String str = sdf.format(executorDate);
            data.put("correctDate",str);
            data.put("executorDate",str);
        }

        return data;
    }



    /**
     * 查询评估报告装订后浏览审核记录表并导出文档
     * @param info
     * @return
     */
    public Map<String,Object> getAuditRecordFormAfterBindingMap(ProgramProjectListInfo info){
        Map data = new HashMap();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年 MM月 dd日");

        //查询项目信息
        ProjectListDto projectDto = findById(info.getId());

        //查询自校数据信息信息
        ProofreadInfoDto proofreadInfoDto = proofreadInfoService.findById(info.getId(),"2");

        /**
         * 自校明细表信息
         */

        List<ProofreadDetail> details = proofreadInfoDto.getDetails();
        List<ProofreadDetail> assessmentList = Lists.newArrayList();
        List<ProofreadDetail> assessmentReportList = Lists.newArrayList();
        List<ProofreadDetail> assessmentExplainList = Lists.newArrayList();
        List<ProofreadDetail> assessmentDetailList = Lists.newArrayList();
        Integer assessment = 0;
        Integer assessmentReport = 0;
        Integer assessmentExplain = 0;
        Integer assessmentDetail = 0;

        for (ProofreadDetail item :details) {
            if(item.getSort().startsWith("40")){
                assessment ++ ;
                item.setSerialNumber(assessment);
                assessmentList.add(item);
            }else if(item.getSort().startsWith("50")){
                assessmentReport ++ ;
                item.setSerialNumber(assessmentReport);
                assessmentReportList.add(item);
            }else if(item.getSort().startsWith("60")){
                assessmentExplain ++ ;
                item.setSerialNumber(assessmentExplain);
                assessmentExplainList.add(item);
            }else if(item.getSort().startsWith("70")){
                assessmentDetail ++ ;
                item.setSerialNumber(assessmentDetail);
                assessmentDetailList.add(item);
            }

        }

        data.put("assessmentList",assessmentList);
        data.put("assessmentReportList",assessmentReportList);
        data.put("assessmentExplainList",assessmentExplainList);
        data.put("assessmentDetailList",assessmentDetailList);


        //项目名称
        if(StringUtils.isNotBlank(projectDto.getName())){
            data.put("projectName",projectDto.getName());
        }else{
            data.put("projectName","");
        }
        //评估基准日
        Date assessmentDate=projectDto.getAssessmentDate();
        if(null == assessmentDate){
            data.put("assessBaseMessage","");
        }else{
            String str = sdf.format(assessmentDate);
            data.put("assessBaseMessage",str);
        }
        //项目负责人
        if(StringUtils.isBlank(projectDto.getProjectManager())){
            data.put("projectMaster","");
        }else{
            data.put("projectMaster",SpringUtil.getBean ( IUserApi.class ).getById(projectDto.getProjectManager()).getName());
        }

        //项目审核人
        if(StringUtils.isBlank(projectDto.getAgreeUserId())){
            data.put("projectauditor","");
        }else{
            data.put("projectauditor",SpringUtil.getBean ( IUserApi.class ).getById(projectDto.getAgreeUserId()).getName());
        }
        //项目审核时间
        Date agreeTime=projectDto.getAgreeTime();
        if(null == agreeTime){
            data.put("projectAuditDate","");
            data.put("auditDate","");
        }else{
            String str = sdf.format(agreeTime);
            data.put("projectAuditDate",str);
            data.put("auditDate",str);
        }

        //审核人员签字
        if(StringUtils.isBlank(projectDto.getUpdateById())){
            data.put("auditPersonnel","");
            data.put("correctPersonnel","");
            data.put("executor","");
        }else{
            data.put("auditPersonnel",proofreadInfoDto.getProjectManagerName());
            //改正人员签字
            data.put("correctPersonnel",SpringUtil.getBean ( IUserApi.class ).getById(proofreadInfoDto.getUpdateById()).getName());
            //执行人
            data.put("executor",SpringUtil.getBean ( IUserApi.class ).getById(proofreadInfoDto.getUpdateById()).getName());
        }
        //保留意见
        if(StringUtils.isBlank(proofreadInfoDto.getReservations())){
            data.put("qualifiedOpinion","");
        }else{
            data.put("qualifiedOpinion",proofreadInfoDto.getReservations());
        }
        //未修改意见
        if(StringUtils.isBlank(proofreadInfoDto.getUnmodifiedComments())){
            data.put("notModifiedOpinion","");
        }else{
            data.put("notModifiedOpinion",proofreadInfoDto.getUnmodifiedComments());
        }

        //执行时间
        //改正人员签字时间
        Date executorDate=proofreadInfoDto.getUpdateTime();
        if(null == executorDate){
            data.put("correctDate","");
            data.put("executorDate","");
        }else{
            String str = sdf.format(executorDate);
            data.put("correctDate",str);
            data.put("executorDate",str);
        }

        return data;
    }



    /**
     * 查询评报告签发表并导出文档
     * @param info
     * @return
     */
    public Map<String,Object> downloadReportAusstellungTpl(ProgramProjectListInfo info){
        Map data = new HashMap();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年 MM月 dd日");

        //查询项目信息
        ProjectListDto projectDto = findById(info.getId());

        //查询项目详情
        ProgramProjectListInfo programProjectListInfo = projectListMapper.getById(projectDto.getId());
        //查询报告签发表信息
        ProofreadIssued issuedById = proofreadIssuedService.findById(info.getId());

        List<ProgramServiceTypeDTO> programServiceTypeList = programServiceTypeService.getList();
        for (ProgramServiceTypeDTO programServiceType: programServiceTypeList) {
            if(programServiceType.getChildrenList().size()>0){
                switch (programServiceType.getName()){
                    case "A类":
                        for(int i = 0 ;i<programServiceType.getChildrenList().size(); i++ ){
                            ProgramServiceTypeDTO programServiceTypeDTO = programServiceType.getChildrenList().get(i);
                            data.put("AMessage" + (i+1),programServiceTypeDTO.getName());
                            if(issuedById.getServiceType().equals(programServiceTypeDTO.getId())){
                                data.put("A" + (i+1),"0052");
                            }else{
                                data.put("A" + (i+1),"00A3");
                            }
                        }
                        break;
                    case "B类":
                        for(int i = 0 ;i<programServiceType.getChildrenList().size(); i++ ){
                            ProgramServiceTypeDTO programServiceTypeDTO = programServiceType.getChildrenList().get(i);
                            data.put("BMessage" + (i+1),programServiceTypeDTO.getName());
                            if(issuedById.getServiceType().equals(programServiceTypeDTO.getId())){
                                data.put("B" + (i+1),"0052");
                            }else{
                                data.put("B" + (i+1),"00A3");
                            }
                        }
                        break;
                    case "C类":
                        for(int i = 0 ;i<programServiceType.getChildrenList().size(); i++ ){
                            ProgramServiceTypeDTO programServiceTypeDTO = programServiceType.getChildrenList().get(i);
                            data.put("CMessage" + (i+1),programServiceTypeDTO.getName());
                            if(issuedById.getServiceType().equals(programServiceTypeDTO.getId())){
                                data.put("C" + (i+1),"0052");
                            }else{
                                data.put("C" + (i+1),"00A3");
                            }
                        }
                        break;
                }
            }else{
                data.put("A1","00A3");
                data.put("A2","00A3");
                data.put("A3","00A3");
                data.put("A4","00A3");
                data.put("A5","00A3");
                data.put("AMessage1" ,"经济行为涉及上市公司及其子公司的资产组合、无形资产、企业价值（包括业务及资产组）评估业务");
                data.put("AMessage2" ,"上市公司及其合并报表范围内的下属公司财务报告目的的评估及咨询业务");
                data.put("AMessage3" ,"经济行为涉及上市公司及其合并报表范围内的下属公司的除本条第（一）款规定之外的评估业务");
                data.put("AMessage4" ,"经济行为涉及非上市证券公司、非上市期货公司、非上市公众公司、拟上市公司及其合并报表范围内的下属公司的评估业务");
                data.put("AMessage5" ,"其中：非国有企业改制设立股份公司评估业务");
                data.put("B1","00A3");
                data.put("B2","00A3");
                data.put("B3","00A3");
                data.put("B4","00A3");
                data.put("B5","00A3");
                data.put("B6","00A3");
                data.put("B7","00A3");
                data.put("B8","00A3");
                data.put("B9","00A3");

                data.put("BMessage1","除A类业务以外的无形资产评估业务");
                data.put("BMessage2","除A类业务以外的资产组合评估业务");
                data.put("BMessage3","除A类业务以外的企业价值评估业务");
                data.put("BMessage4","除A类业务以外的报务报告目的评估业务");
                data.put("BMessage5","除A类业务以外的抵押担保目的评估业务");
                data.put("BMessage6","除A类以外的，涉及上市公司、证券公司、期货公司、非上市公众公司、拟上市公司及其下属公司不用于市场交易的复核评估、追溯评估和咨询评估业务");
                data.put("BMessage7","除A类以外的涉及国有企业与非国有企业之间的交易行为的评估业务及相关的复核评估、追溯评估和咨询评估业务");
                data.put("BMessage8","金融企业（包括银行、保险公司、信托投资公司、基金管理公司、租赁公司等）的评估业务");
                data.put("BMessage9","评估经验较少的新领域评估业务");

                data.put("C1","00A3");
                data.put("C2","00A3");

                data.put("CMessage1","除A、B类业务以外的经济行为涉及单项资产的评估业务");
                data.put("CMessage2","除A、B类业务以外的不用于市场交易的复核评估、追溯评估和咨询评估业务");
            }
        }
        //报告号
        data.put("projectName",projectDto.getName());
        //报告号
        data.put("projectReportNumber",programProjectListInfo.getReportNo());

        if(null != issuedById){
            //台账
            if(StringUtils.isNotBlank(issuedById.getIsTxtz())){
                if("1".equals(issuedById.getIsTxtz())){
                    data.put("standingBook","是");
                }else{
                    data.put("standingBook","否");
                }
            }else{
                data.put("standingBook","");
            }
            //电子归档
            if(StringUtils.isNotBlank(issuedById.getIsBgdzdgd())){
                if("1".equals(issuedById.getIsBgdzdgd())){
                    data.put("electronicsArchive","是");
                }else{
                    data.put("electronicsArchive","否");
                }
            }else{
                data.put("electronicsArchive","");
            }
            //备案
            if(StringUtils.isNotBlank(issuedById.getIsXyba())){
                if("1".equals(issuedById.getIsXyba())){
                    data.put("putOnRecords","是");
                }else{
                    data.put("putOnRecords","否");
                }
            }else{
                data.put("putOnRecords","");
            }
            //完成备案
            if(StringUtils.isNotBlank(issuedById.getIsWcba())){
                if("1".equals(issuedById.getIsWcba())){
                    data.put("accomplishPutOnRecords","是");
                }else{
                    data.put("accomplishPutOnRecords","否");
                }
            }else{
                data.put("accomplishPutOnRecords","");
            }
            //用印类型
            if(StringUtils.isNotBlank(issuedById.getSealType())){
                data.put("sealType",issuedById.getSealType());
            }else{
                data.put("sealType","");
            }
            String reportCopiesDetail = "";
                // 咨询报告 份
                if(StringUtils.isNotBlank(issuedById.getConsultingReport())){
                    reportCopiesDetail = reportCopiesDetail + "咨询报告" + issuedById.getConsultingReport() + "份; ";
                }
                // 评估报告 份
                if(StringUtils.isNotBlank(issuedById.getAssessmentReport())){
                    reportCopiesDetail = reportCopiesDetail + "评估报告" + issuedById.getAssessmentReport() + "份; ";
                }
                // 评估说明 份
                if(StringUtils.isNotBlank(issuedById.getAssessmentExplain())){
                    reportCopiesDetail = reportCopiesDetail + "评估说明" + issuedById.getAssessmentExplain() + "份; ";
                }
                // 评估明细表 份
                if(StringUtils.isNotBlank(issuedById.getAssessmentDetail())){
                    reportCopiesDetail = reportCopiesDetail + "评估明细表" + issuedById.getAssessmentDetail() + "份; ";
                }
            data.put("reportCopiesDetail",reportCopiesDetail);
        }else{
            data.put("standingBook","");
            data.put("electronicsArchive","");
            data.put("putOnRecords","");
            data.put("accomplishPutOnRecords","");
            data.put("sealType","");
            data.put("assessmentReport","");
            data.put("assessmentExplain","");
            data.put("assessmentDetail","");
            data.put("consultingReport","");
        }

        //项目负责人
        if(StringUtils.isBlank(projectDto.getProjectManager())){
            data.put("projectMaster","");
        }else{
            data.put("projectMaster",SpringUtil.getBean ( IUserApi.class ).getById(projectDto.getProjectManager()).getName());
        }
        //项目负责人时间
        Date agreeTime=projectDto.getAgreeTime();
        if(null == agreeTime){
            data.put("projectMasterDate","");
        }else{
            String str = sdf.format(agreeTime);
            data.put("projectMasterDate",str);
        }

        //一级审核人
        //查询校审信息
        ProgramAuditDto audit1Dto = findByIdAudit(programProjectListInfo.getAuditId1());
        if(null != audit1Dto){
            //一级审核人
            data.put("firstAuditMaster",SpringUtil.getBean ( IUserApi.class ).getById(audit1Dto.getAuditPeople()).getName());
            //审核时间
            Date auditDate=audit1Dto.getAuditDate();
            if(null == auditDate){
                data.put("firstAuditMasterDate","");
            }else{
                String str = sdf.format(auditDate);
                data.put("firstAuditMasterDate",str);
            }
        }else{
            data.put("firstAuditMaster","");
            data.put("firstAuditMasterDate","");
        }
        //二级审核人
        ProgramAuditDto audit2Dto = findByIdAudit(programProjectListInfo.getAuditId2());
        if(null != audit2Dto){
            //二级审核人
            data.put("secondAuditMaster",SpringUtil.getBean ( IUserApi.class ).getById(audit2Dto.getAuditPeople()).getName());
            //审核时间
            Date auditDate=audit2Dto.getAuditDate();
            if(null == auditDate){
                data.put("secondAuditMasterDate","");
            }else{
                String str = sdf.format(auditDate);
                data.put("secondAuditMasterDate",str);
            }
        }else{
            data.put("secondAuditMaster","");
            data.put("secondAuditMasterDate","");
        }
        //三级审核人
        ProgramAuditDto audit3Dto = findByIdAudit(programProjectListInfo.getAuditId3());
        if(null != audit1Dto){
            //一级审核人
            data.put("thirdAuditMaster",SpringUtil.getBean ( IUserApi.class ).getById(audit3Dto.getAuditPeople()).getName());
            //审核时间
            Date auditDate=audit3Dto.getAuditDate();
            if(null == auditDate){
                data.put("thirdAuditMasterDate","");
            }else{
                String str = sdf.format(auditDate);
                data.put("thirdAuditMasterDate",str);
            }
        }else{
            data.put("thirdAuditMaster","");
            data.put("thirdAuditMasterDate","");
        }

        //校对负责人
        ProofreadInfoDto proofreadInfoDto = proofreadInfoService.findById(info.getId(),"1");

        if(null != proofreadInfoDto){
            //校对负责人
            data.put("proofreadMaster",SpringUtil.getBean ( IUserApi.class ).getById(proofreadInfoDto.getUpdateById()).getName());
            //审核时间
            Date processDate=proofreadInfoDto.getProcessDate();
            if(null == processDate){
                data.put("proofreadMasterDate","");
            }else{
                String str = sdf.format(processDate);
                data.put("proofreadMasterDate",str);
            }
        }else{
            data.put("proofreadMaster","");
            data.put("proofreadMasterDate","");
        }
        //签发人
        if(null != issuedById){
            //校对负责人
            if(StringUtils.isNotBlank(issuedById.getAgreeUserId())){
                data.put("signer",SpringUtil.getBean ( IUserApi.class ).getById(issuedById.getAgreeUserId()).getName());
            }else{
                data.put("signer","");
            }
            //校对时间
            Date issuedAgreeTime=issuedById.getAgreeTime();
            if(null == issuedAgreeTime){
                data.put("signerDate","");
            }else{
                String str = sdf.format(issuedAgreeTime);
                data.put("signerDate",str);
            }
        }else{
            data.put("signer","");
            data.put("signerDate","");
        }


        //归档负责人
        ProgramArchiveDto programArchiveDto = programArchiveMapper.findByProgramIdArchive(info.getId());
        if(null != programArchiveDto){
            //校对负责人
            data.put("archiveMaster","");
            if(StringUtils.isNotBlank(programArchiveDto.getAuditUserId())){
                data.put("archiveMaster",SpringUtil.getBean ( IUserApi.class ).getById(programArchiveDto.getAuditUserId()).getName());
            }else{
                data.put("archiveMaster","");
            }
            //校对时间
            Date auditDate=programArchiveDto.getAuditDateDate();
            if(null == auditDate){
                data.put("archiveMasterDate","");
            }else{
                String str = sdf.format(auditDate);
                data.put("archiveMasterDate",str);
            }
        }else{
            data.put("archiveMaster","");
            data.put("archiveMasterDate","");
        }

        return data;
    }


    /**
     * getHaveProjectIds
     * @return
     */
    public ResponseEntity<List<String>> getHaveProjectIds(){
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        return ResponseEntity.ok(projectListMapper.getHaveProjectIds(userDTO));
    }

    public ResponseEntity<ProgramAuditDto> findByProIdAndLevel(String programId, String auditLevel) {
        String id = programAuditMapper.findIdByProIdAndLevel(programId,auditLevel);
        ProgramAuditDto byIdAudit = new ProgramAuditDto();
        if (StringUtils.isNotBlank(id)) {
            byIdAudit = findByIdAudit(id);
        }
        return ResponseEntity.ok(byIdAudit);
    }
}
