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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
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.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.service.dto.DictValueDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.DictUtils;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
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.OssService;
import com.jeeplus.test.program.configuration.projectList.domain.*;
import com.jeeplus.test.program.configuration.projectList.mapper.*;
import com.jeeplus.test.program.configuration.projectList.service.dto.*;
import com.jeeplus.test.program.configuration.projectList.service.mapstruct.ProgramArchiveWrapper;
import com.jeeplus.test.program.configuration.projectList.service.mapstruct.ProgramAuditAssessPeopleWrapper;
import com.jeeplus.test.program.configuration.projectList.service.mapstruct.ProgramAuditWrapper;
import com.jeeplus.test.proofread.domain.ProofreadDetail;
import com.jeeplus.test.proofread.domain.ProofreadIssued;
import com.jeeplus.test.proofread.service.ProofreadInfoService;
import com.jeeplus.test.proofread.service.ProofreadIssuedService;
import com.jeeplus.test.proofread.service.dto.ProofreadInfoDto;
import com.jeeplus.test.workContract.domain.WorkContractInfo;
import com.jeeplus.test.workContract.mapper.WorkContractInfoMapper;
import com.jeeplus.test.workContract.service.WorkContractService;
import com.jeeplus.test.workContract.service.dto.WorkAttachmentDto;
import com.jeeplus.test.workContract.service.dto.WorkContractInfoDto;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProjectListService {

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

    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{
        ProgramProjectListInfo info = new ProgramProjectListInfo();
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        // 保存项目管理列表主表信息
        BeanUtils.copyProperties(dto, info);
        String id = UUID.randomUUID().toString().replace("-", "");
        //合同编号生成
        String no = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), ProjectListDto.BIZ_CODE);
        //项目立项号生成
        String approvalNo = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), ProjectListDto.BIY_CODE);
        info.setId(id);
        info.setNo(no);
        info.setApprovalNo(approvalNo);
        info.setCreateBy(userDTO.getId());
        info.setCreateDate(new Date());
        info.setUpdateBy(userDTO.getId());
        info.setUpdateDate(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.setCreateBy(userDTO.getId());
                link.setCreateDate(new Date());
                link.setUpdateBy(userDTO.getId());
                link.setUpdateDate(new Date());
                link.setDelFlag(0);
                projectLinkMapper.insert(link);
            }
        }
        // 保存项目管理列表成员信息
        if (CollectionUtils.isNotEmpty(dto.getMembers())) {
            for (ProgramProjectListMember member : dto.getMembers()) {
                member.setId(UUID.randomUUID().toString().replace("-", ""));
                member.setInfoId(id);
                member.setCreateBy(userDTO.getId());
                member.setCreateDate(new Date());
                member.setUpdateBy(userDTO.getId());
                member.setUpdateDate(new Date());
                member.setDelFlag(0);
                projectMemberMapper.insert(member);
            }
        }
        // 保存附件信息
        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
                        String contractId = programProjectListInfo.getContractId();
                        if (StringUtils.isNotBlank(programProjectListInfo.getReportType())) {
                            if ("1".equals(programProjectListInfo.getReportType())) {
                                // 生成合同编号-评估类
                                String serialNum = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE);
                                // 根据合同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 = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE_);
                                // 根据合同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);
        if (StringUtils.isNotBlank(programArchive.getId())){
            programArchiveMapper.updateById(programArchive);
        }else{
            programArchiveMapper.insert(programArchive);
        }
        if (ObjectUtil.isNotEmpty(programArchiveDto)) {
            ossService.saveOrUpdateFileListFlag(programArchiveDto.getReportFileList(),programArchive.getId(),"report");
            ossService.saveOrUpdateFileListFlag(programArchiveDto.getDetailFileList(),programArchive.getId(),"detail");
            ossService.saveOrUpdateFileListFlag(programArchiveDto.getExplainFileList(),programArchive.getId(),"explain");
            ossService.saveOrUpdateFileListFlag(programArchiveDto.getPapersFileList(),programArchive.getId(),"papers");
            ossService.saveOrUpdateFileListFlag(programArchiveDto.getOtherFileList(),programArchive.getId(),"other");
        }
        return programArchive.getId();
    }

    public String saveFormThree(ProgramAuditDto programAuditDto) {
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        ProgramAudit programAudit = ProgramAuditWrapper.INSTANCE.toEntity(programAuditDto);
        if (StringUtils.isNotBlank(programAudit.getId())){
            programAuditMapper.updateById(programAudit);
        }else{
            programAuditMapper.insert(programAudit);
        }
        if (ObjectUtil.isNotEmpty(programAuditDto)) {
            //附件
            ossService.saveOrUpdateFileList(programAuditDto.getWorkAttachmentDtoList(),programAudit.getId(),"program");
            //专业评估人员
            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{
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        // 修改项目管理列表主表信息
        ProgramProjectListInfo info = new ProgramProjectListInfo();
        BeanUtils.copyProperties(dto, info);
        info.setUpdateBy(userDTO.getId());
        info.setUpdateDate(new Date());
        info.setDelFlag(0);
        projectListMapper.updateById(info);
        // 修改联系人信息(先删除原有数据，再保存)
        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.setCreateBy(userDTO.getId());
                link.setCreateDate(new Date());
                link.setUpdateBy(userDTO.getId());
                link.setUpdateDate(new Date());
                link.setDelFlag(0);
                projectLinkMapper.insert(link);
            }
        }
        // 修改项目管理列表成员信息(先删除原有数据，再保存)
        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.setCreateBy(userDTO.getId());
                member.setCreateDate(new Date());
                member.setUpdateBy(userDTO.getId());
                member.setUpdateDate(new Date());
                member.setDelFlag(0);
                projectMemberMapper.insert(member);
            }
        }
        // 修改附件信息
        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
                        String contractId = programProjectListInfo.getContractId();
                        if (StringUtils.isNotBlank(programProjectListInfo.getReportType())) {
                            if ("1".equals(programProjectListInfo.getReportType())) {
                                // 生成合同编号-评估类
                                String serialNum = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE);
                                // 根据合同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 = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE_);
                                // 根据合同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.selectById(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)) {
            dto.setMembers(members);
        }
        // 查询附件信息
        List<WorkAttachmentDto> files = workContractInfoMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentDto i : files) {
                i.setCreateBy(UserUtils.get(i.getBy()));
            }
            dto.setFiles(files);
        }
        return dto;
    }

    public ProgramAuditDto findByIdAudit(String id){
        ProgramAuditDto byIdAudit = programAuditMapper.findByIdAudit(id);
        // 查询附件信息
        List<WorkAttachmentDto> files = workContractInfoMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentDto i : files) {
                i.setCreateBy(UserUtils.get(i.getBy()));
            }
            byIdAudit.setWorkAttachmentDtoList(files);
        }
        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 = UserUtils.get(programArchiveDto.getProgramProjectListInfo().getProjectManager());
                    programArchiveDto.getProgramProjectListInfo().setOfficeId(userDTO.getOfficeDTO().getName());
                }
            }
        }
        // 查询附件信息 - 评估报告
        List<WorkAttachmentDto> reportFileList = workContractInfoMapper.findByAttachmentIdAndFlag(id, "report");
        if (CollectionUtils.isNotEmpty(reportFileList)) {
            for (WorkAttachmentDto i : reportFileList) {
                i.setCreateBy(UserUtils.get(i.getBy()));
            }
            programArchiveDto.setReportFileList(reportFileList);
        }

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

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

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

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


        return programArchiveDto;
    }

    public String deleteById(String id) {
        projectListMapper.deleteById(id);
        projectLinkMapper.deleteByInfoId(id);
        projectMemberMapper.deleteByInfoId(id);
        // 附件删除
        LambdaQueryWrapper<WorkAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkAttachment::getAttachmentId, id);
        ossServiceMapper.delete(wrapper);
        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);
        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.findPageList(page, wrapper);
        pageList.getRecords().stream().forEach(item ->{
            String isInvoice = projectListMapper.selectInvoiceFlag(item.getId());
            item.setIsInvoice(isInvoice);
        });
        return pageList;
    }

    public List<ExportFileDto> exportList(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]);
        }
        List<ProgramProjectListInfo> infoList = projectListMapper.findInfoList(wrapper);
        List<ExportFileDto> list = projectListMapper.findList(infoList);
        List<DictValueDTO> dictDTOList = DictUtils.getDictDTOList("program_registered_type");
        for (ExportFileDto projectInfo: list) {
            for (DictValueDTO dictInfo: dictDTOList) {
                if (StrUtil.isNotBlank(projectInfo.getProgramType())){
                    if (projectInfo.getProgramType().equals(dictInfo.getValue())){
                        projectInfo.setProgramType(dictInfo.getLabel());
                    }
                }
            }
        }
        return list;
    }

    public String saveReportNo(String id) throws Exception{
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        ProgramProjectListInfo programProjectListInfo = projectListMapper.selectById(id);
        String reportNo = "";
        if(ObjectUtil.isNotEmpty(programProjectListInfo)){
            if(StringUtils.isNotBlank(programProjectListInfo.getReportType())){
                if (programProjectListInfo.getReportType().equals("1")){
                    reportNo = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE);
                } else if (programProjectListInfo.getReportType().equals("2")) {
                    reportNo = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), ProgramReportNoDto.BIZ_CODE_);
                }
                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",UserUtils.get(projectDto.getProjectManager()).getName());
        }
        //如果存在审核意见则进行处理
        if(null != auditDto){
            //专业评估人员
            List<ProgramAuditAssessPeopleDto> programAuditAssessPeopleDtoList = auditDto.getProgramAuditAssessPeopleDtoList();
            List<String> appraiserList = Lists.newArrayList();
            for (ProgramAuditAssessPeopleDto assessPeopleDto:programAuditAssessPeopleDtoList) {
                appraiserList.add(UserUtils.get(assessPeopleDto.getAssessPeople()).getName());
            }
            data.put("appraisers",String.join(",",appraiserList));

            //项目审核人
            data.put("projectauditor",UserUtils.get(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",UserUtils.get(auditDto.getCreateBy().getId()).getName());

            Date auditDate=projectDto.getAssessmentDate();
            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",UserUtils.get(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",UserUtils.get(projectDto.getProjectManager()).getName());
        }

        //项目审核人
        if(StringUtils.isBlank(projectDto.getAgreeUserId())){
            data.put("projectauditor","");
        }else{
            data.put("projectauditor",UserUtils.get(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.getUpdateBy())){
            data.put("auditPersonnel","");
            data.put("correctPersonnel","");
            data.put("executor","");
        }else{
            data.put("auditPersonnel",UserUtils.get(proofreadInfoDto.getUpdateBy()).getName());
            //改正人员签字
            data.put("correctPersonnel",UserUtils.get(proofreadInfoDto.getUpdateBy()).getName());
            //执行人
            data.put("executor",UserUtils.get(proofreadInfoDto.getUpdateBy()).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.getUpdateDate();
        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",UserUtils.get(projectDto.getProjectManager()).getName());
        }

        //项目审核人
        if(StringUtils.isBlank(projectDto.getAgreeUserId())){
            data.put("projectauditor","");
        }else{
            data.put("projectauditor",UserUtils.get(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.getUpdateBy())){
            data.put("auditPersonnel","");
            data.put("correctPersonnel","");
            data.put("executor","");
        }else{
            data.put("auditPersonnel",proofreadInfoDto.getProjectManagerName());
            //改正人员签字
            data.put("correctPersonnel",UserUtils.get(proofreadInfoDto.getUpdateBy()).getName());
            //执行人
            data.put("executor",UserUtils.get(proofreadInfoDto.getUpdateBy()).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.getUpdateDate();
        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());

        //报告号
        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",UserUtils.get(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",UserUtils.get(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",UserUtils.get(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",UserUtils.get(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",UserUtils.get(proofreadInfoDto.getUpdateBy()).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",UserUtils.get(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",UserUtils.get(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;
    }
}
