package com.jeeplus.finance.projectReport.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.finance.projectRecords.domain.CwProjectRecords;
import com.jeeplus.finance.projectRecords.mapper.CwProjectRecordsMapper;
import com.jeeplus.finance.projectReport.domain.*;
import com.jeeplus.finance.projectReport.mapper.*;
import com.jeeplus.finance.projectReport.service.dto.CwProjectReportDTO;
import com.jeeplus.finance.projectReportArchive.mapper.CwProjectReportArchiveMapper;
import com.jeeplus.finance.reimbursementApproval.approvalInfo.service.dto.ReportNoDto;
import com.jeeplus.flowable.feign.IFlowableApi;
//import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.UserUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.flowable.bpmn.model.FlowNode;
import org.apache.commons.beanutils.PropertyUtils;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 报告审核校对
 * @author: 王强
 * @create: 2022-12-12 20:35
 **/
@Service
@Transactional
public class CwProjectReportReviewService extends ServiceImpl<CwProjectReportReviewMapper, CwProjectReview>{

    @Resource
    private CwProjectReportService cwProjectReportService;

    @Resource
    private CwProjectReportReviewMapper mapper;

    @Resource
    private CwProjectReviewNewMapper reviewNewMapper;
    @Resource
    private CwProjectReviewNewTeamMapper newTeamMapper;

    @Resource
    private CwProofreadDetailMapper detailMapper;

//    @Resource
//    private SerialnumTplService serialnumTplService;

    @Resource
    private IFlowableApi flowTaskService;

    @Resource
    private CwProjectReportArchiveMapper cwProjectReportArchiveMapper;

    @Resource
    private CwProjectInfoMapper infoMapper;

    @Resource
    private CwProjectRecordsMapper recordsMapper;

    @Resource
    private CwProjectReportReviewMapper cwProjectReportReviewMapper;

    public CwProjectReportData queryByReportId(String id) {
        CwProjectReportData data = mapper.selectByPortId(id);
        //查询复核相关信息

        return data;
    }

    public CwProjectReportData getUserInfo(String id) {
        CwProjectReportData data = mapper.getUserInfo();
        if(null != data){
            UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getById(id);
            data.setReviewByName(userDTO.getName());
        }

        return data;
    }
    public CwProjectReportData queryByReportIdNew(String id) {
        CwProjectReviewNew reviewNew = reviewNewMapper.selectOne(new QueryWrapper<CwProjectReviewNew>().eq("report_id", id));
        CwProjectReportData data = new CwProjectReportData();
        if (null != reviewNew) {

            BeanUtils.copyProperties(reviewNew, data);
        }

        return data;
    }

    /**
     * 修改状态
     * @param data
     * @return
     */
    public String updateReviewStatysByReportId(CwProjectReportData data) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        mapper.updateReviewStatysByReportId(data.getReviewStatus(),data.getId(),data.getNeedUpdate2(),data.getRemark2(),
        data.getNeedUpdate3(),data.getRemark3());

        data = mapper.selectProjectReportById(data.getId());
        CwProjectReview detail = mapper.selectById(data.getId());
        if (null == detail){
            //传过来的是报告表id
            detail = mapper.selectByReportId(data.getId());
        }
        //如果是驳回操作，且是新的流程，则此处应对签章部分功能进行恢复
        if("1".equals(detail.getNewType())){
            //对签章表数据状态进行处理
            String signatureId = cwProjectReportService.modifySignatureStatus(data,data.getReviewStatus());
        }

        //根据id找到报告id，然后根据报告id找到projectid，然后根据projectId修改状态
        String projectId = mapper.getProjectIdByReportId(data.getId());

        //将关联的项目信息的状态改为已开始/已复核完成
//        CwProjectRecords records = new CwProjectRecords();
//        records.setId(projectId);
//        records.setReportReview("0");
//        recordsMapper.updateById(records);
        CwProjectReportData reviewData = mapper.selectByPortId(data.getId());
        //对复核数据进行持久化操作
        if (CollectionUtils.isNotEmpty(data.getDetails())) {
            for (CwProofreadDetail detail1:data.getDetails()) {
                CwProofreadDetail detail2 = detailMapper.getByTypeIdAndInfoId(detail1.getTypeId(),reviewData.getId());
                if (null == detail2) {
                    String detailId = UUID.randomUUID().toString().replace("-", "");
                    detail1.setId(detailId);
                    detail1.setInfoId(reviewData.getId());
                    detail1.setCreateById(userDTO.getId());
                    detail1.setCreateTime(new Date());
                    detail1.setUpdateById(userDTO.getId());
                    detail1.setUpdateTime(new Date());
                    detailMapper.insert(detail1);
                } else {
                    detail1.setCreateTime(detail2.getCreateTime());
                    detail1.setCreateById(detail2.getCreateById());
                    detail1.setId(detail2.getId());
                    detail1.setInfoId(reviewData.getId());
                    detail1.setUpdateById(userDTO.getId());
                    detail1.setUpdateTime(new Date());
                    detailMapper.updateById(detail1);
                }
            }
        }

        return "操作成功";
    }
    /**
     * 修改状态
     * @param data
     * @return
     */
    public String updateReviewStatusByReportIdNew(CwProjectReportData data) {
        reviewNewMapper.updateStatusById(data.getId(),data.getReviewStatus());
        return "操作成功";
    }

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

            CwProjectReview detail = mapper.selectById(reportData.getId());
            if (detail != null){
                reportData.setCreateBy(reportData.getCreateBy());
                return update(reportData,detail);
            } else {
                //传过来的是报告表id
                detail = mapper.selectByReportId(reportData.getId());
                if (detail != null){
                    reportData.setCreateBy(reportData.getCreateBy());
                    return update(reportData,detail);
                }
            }
        }
        return add(reportData);

    }

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

            CwProjectReviewNew detail = reviewNewMapper.selectById(reportData.getReviewNewId());
            if (detail != null){
                reportData.setCreateBy(reportData.getCreateBy());
                reportData.setMark(detail.getMark());
                return updateNew(reportData,detail);
            }
        }
        return addNew(reportData);

    }

    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String updateNew(CwProjectReportData reportData,CwProjectReviewNew detail) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        CwProjectReviewNew review = new CwProjectReviewNew();
        BeanUtils.copyProperties(reportData, review);
        review.setUpdateById(userDTO.getId());
        review.setUpdateTime(new Date());
        review.setId(reportData.getReviewNewId());

        if (StringUtils.isNotBlank(reportData.getMark())) {
            if (reportData.getMark().equals("1") && reportData.getReviewStatus().equals("5")) {
                //超期复核
                review.setReviewStatus("7");
            }
        }
        if (null == review.getCheckCompleteTime()) {
            review.setCheckCompleteTime(new Date());
        }
        reviewNewMapper.updateById(review);

        //项目组成员数据处理
        newTeamMapper.delete(new QueryWrapper<CwProjectReviewNewTeam>().eq("report_id",reportData.getId()));
        //项目组成员保存
        List<CwProjectReviewNewTeam> newTeams = reportData.getDetailInfos();
        for (CwProjectReviewNewTeam newTeam : newTeams) {
            String teamId = UUID.randomUUID().toString().replace("-", "");
            newTeam.setId(teamId);
            newTeam.setCreateById(userDTO.getId());
            newTeam.setCreateTime(new Date());
            newTeam.setUpdateById(userDTO.getId());
            newTeam.setUpdateTime(new Date());
            newTeam.setReportId(reportData.getId());
            newTeamMapper.insert(newTeam);
        }
        return review.getId();
    }

    public String addNew(CwProjectReportData dto) throws Exception{


        //生成主键id值
        String id = UUID.randomUUID().toString().replace("-", "");
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        //保存基本信息
        CwProjectReviewNew info = new CwProjectReviewNew();
        BeanUtils.copyProperties(dto, info);

        info.setId(id);
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setReportId(dto.getId());

        reviewNewMapper.insert(info);

        //项目组成员保存
        List<CwProjectReviewNewTeam> newTeams = dto.getDetailInfos();
        for (CwProjectReviewNewTeam newTeam : newTeams) {
            String teamId = UUID.randomUUID().toString().replace("-", "");
            newTeam.setId(teamId);
            newTeam.setCreateById(userDTO.getId());
            newTeam.setCreateTime(new Date());
            newTeam.setUpdateById(userDTO.getId());
            newTeam.setUpdateTime(new Date());
            newTeam.setReportId(dto.getId());
            newTeamMapper.insert(newTeam);
        }

        return info.getId();
    }

    /**
     * 保存项目以及其他相关信息
     * @param reportData
     * @return
     * @throws Exception
     */
    public String saveFormNew(CwProjectReportData reportData) throws Exception{
        //生成一条报告信息，并且生成一个报告号
        //生成报告信息
        String currentToken = TokenProvider.getCurrentToken();
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(currentToken);
        String reportId = UUID.randomUUID().toString().replace("-", "");
        CwProjectReport cwProjectReport = new CwProjectReport();
        cwProjectReport.setProjectId(reportData.getProjectId());
        cwProjectReport.setId(reportId);
        cwProjectReport.setStatus("5");
        cwProjectReport.setCreateById(userDTO.getId());
        cwProjectReport.setCreateTime(new Date());
        cwProjectReport.setUpdateById(userDTO.getId());
        cwProjectReport.setUpdateTime(new Date());
        //生成单据编号
        String documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), CwProjectReportDTO.BIZ_CODE,currentToken);
        cwProjectReport.setDocumentNo(documentNo);
        //这个是报告编号
//        String documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE2,TokenProvider.getCurrentToken());
        CwProjectInfoData infoData = new CwProjectInfoData();
        String infoDataId = UUID.randomUUID().toString().replace("-", "");
        infoData.setId(infoDataId);
        infoData.setCreateById(userDTO.getId());
        infoData.setCreateTime(new Date());
        infoData.setUpdateById(userDTO.getId());
        infoData.setUpdateTime(new Date());
        infoData.setReportId(reportId);
        infoData.setReportType("2");

        String reportNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.CONSULT_BIZ_CODE,currentToken);
        infoData.setReportNo(reportNo);

        //报告流水号生成  根据项目编号去new_line表查询
        String reportNumber = infoMapper.selectReportNumberByProjectNo(reportData.getProjectNumber());
        if (null != reportNumber) {
            int stress = 0;
            stress = reportNumber.indexOf("-");//分隔符位置
            String substring = reportNumber.substring(stress + 1, reportNumber.length());
            int integer = Integer.parseInt(substring);

            String newReportNumber = "";
            if (integer < 10) {
                if (integer == 9) {
                    newReportNumber = reportData.getProjectNumber() + "-010";
                } else {
                    newReportNumber = reportData.getProjectNumber() + "-00" + (integer + 1);
                }
            } else {
                if (integer < 100) {
                    if (integer == 99) {
                        newReportNumber = reportData.getProjectNumber() + "-100";
                    } else {
                        newReportNumber = reportData.getProjectNumber() + "-0" + (integer + 1);
                    }
                } else {
                    newReportNumber = reportData.getProjectNumber() + "-" + (integer + 1);
                }
            }

            infoData.setReportNumber(newReportNumber);
        } else {
            infoData.setReportNumber(reportData.getProjectNumber() + "-001");
        }

        infoMapper.insert(infoData);

        cwProjectReportService.saveOrUpdate(cwProjectReport);

        return reportId;

    }
    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(CwProjectReportData reportData,CwProjectReview detail) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        CwProjectReview review = new CwProjectReview();
        BeanUtils.copyProperties(reportData, review);
        review.setCreateById(detail.getCreateById());
        review.setCreateTime(detail.getCreateTime());
        review.setUpdateById(userDTO.getId());
        review.setUpdateTime(new Date());
        review.setId(detail.getId());
        String currentToken = TokenProvider.getCurrentToken();
        if (StringUtils.isNotEmpty(detail.getProcInsId())) {
            String currentTask = flowTaskService.getCurrentTaskName(detail.getProcInsId());
            if(StringUtils.isNotBlank(currentTask)) {
                if ("二级复核".equals(currentTask) || "质控审核".equals(currentTask)) {
                    //设置报告文号、报告流水号
                    CwProjectInfoData infoData = new CwProjectInfoData();
                    //报告文号生成
                    String documentNo = "";
                    if(StringUtils.isNotBlank(reportData.getReportNo())){
                        infoData.setReportNo(reportData.getReportNo());
                    }else{
                        if(StringUtils.isNotBlank(reportData.getReportType())) {
                            ReportNoDto projectReportByNumber = new ReportNoDto();
                            switch (reportData.getReportType()) {
                                case "1":   //基字
                                    do{
                                        documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.BIZ_CODE,currentToken);
                                        //根据报告号查询诗剧苦中是否存在
                                        projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                                    }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                                    break;
                                case "2":   //咨字
                                    do{
                                        documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.CONSULT_BIZ_CODE,currentToken);
                                        //根据报告号查询诗剧苦中是否存在
                                        projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                                    }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                                    break;
                                case "3":   //审字
                                    do{
                                        documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.EXAMINE_BIZ_CODE,currentToken);
                                        //根据报告号查询诗剧苦中是否存在
                                        projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                                    }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                                    break;
                                case "4":   //验字
                                    do{
                                        documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.CHECK_BIZ_CODE,currentToken);
                                        //根据报告号查询诗剧苦中是否存在
                                        projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                                    }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                                    break;
                                case "5":   //特字
                                    do{
                                        documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.SPECIAL_BIZ_CODE,currentToken);
                                        //根据报告号查询诗剧苦中是否存在
                                        projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                                    }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                                    break;
                            }
                        }
                        /*try {
                            documentNo = serialnumTplService.genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.BIZ_CODE);
                            if(documentNo.contains("{replacement}")){
                                if(StringUtils.isNotBlank(reportData.getReportType())){
                                    switch (reportData.getReportType()){
                                        case "1":
                                            documentNo = documentNo.replace("{replacement}","基");
                                            break;
                                        case "2":
                                            documentNo = documentNo.replace("{replacement}","咨");
                                            break;
                                        case "3":
                                            documentNo = documentNo.replace("{replacement}","审");
                                            break;
                                        case "4":
                                            documentNo = documentNo.replace("{replacement}","验");
                                            break;
                                        case "5":
                                            documentNo = documentNo.replace("{replacement}","特");
                                            break;
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }*/
                        infoData.setReportId(review.getReportId());
                        infoData.setReportNo(documentNo);
                        // 如果数据已经生成报告文号，则不重复生成
                        CwProjectInfoData byReportId = infoMapper.getByReportId(review.getReportId());
                        if(ObjectUtil.isNotEmpty(byReportId)) {
                            if (StringUtils.isNotBlank(byReportId.getReportNo())) {
                                infoData.setReportNo(byReportId.getReportNo());
                            }
                        }
                    }
                    if(StringUtils.isNotBlank(reportData.getReportNumber())){
                        infoData.setReportNumber(reportData.getReportNumber());
                    }else {
                        //报告流水号生成  根据项目编号去new_line表查询
                        String reportNumber = infoMapper.selectReportNumberByProjectNo(reportData.getProjectNumber());
                        if (null != reportNumber) {
                            int stress = 0;
                            stress = reportNumber.indexOf("-");//分隔符位置
                            String substring = reportNumber.substring(stress + 1, reportNumber.length());
                            int integer = Integer.parseInt(substring);

                            String newReportNumber = "";
                            if (integer < 10) {
                                if (integer == 9) {
                                    newReportNumber = reportData.getProjectNumber() + "-010";
                                } else {
                                    newReportNumber = reportData.getProjectNumber() + "-00" + (integer + 1);
                                }
                            } else {
                                if (integer < 100) {
                                    if (integer == 99) {
                                        newReportNumber = reportData.getProjectNumber() + "-100";
                                    } else {
                                        newReportNumber = reportData.getProjectNumber() + "-0" + (integer + 1);
                                    }
                                } else {
                                    newReportNumber = reportData.getProjectNumber() + "-" + (integer + 1);
                                }
                            }

                            infoData.setReportNumber(newReportNumber);
                        } else {
                            infoData.setReportNumber(reportData.getProjectNumber() + "-001");
                        }
                    }
                    infoMapper.updateByReportId(reportData.getId(),infoData.getReportNumber(),infoData.getReportNo());
                    //必须是盖电子公章和整合后的报告才可走签章流程
                    if("1".equals(detail.getNewType()) && StringUtils.isNotBlank(reportData.getSignatureType()) && "1".equals(reportData.getSignatureType())){
                        //生成签章文件
                        // 有电子章的附件时，走签章流程
                        Map<String, Object> signatureContractId = cwProjectReportService.createSignatureContractId(reportData);
                        boolean bool = (boolean)signatureContractId.get("success");
                        if (bool) {
                            String signatureId = cwProjectReportService.getSignature(reportData);
                            mapper.updateSignatureProcInsId(detail.getProcInsId(),detail.getProcessDefinitionId(),signatureId);
                            System.out.println(signatureId);
                        }
                    } else if("质控审核".equals(currentTask)){
                        review.setReviewStatus("5");
                    }

                }
                if ("三级复核".equals(currentTask) || "三级复核及签章".equals(currentTask)) {
                    review.setReviewStatus("5");
                    if("1".equals(detail.getNewType())){
                        //原签章表中的状态值也调整为5
                        String signatureId = cwProjectReportService.modifySignatureStatus(reportData,"5");
                        //System.out.println(signatureId);
                        //复核完成后生成新的归档信息数据
                        //cwProjectReportService.saveReportArchive(reportData.getId());
                    }
                }
            }
        }
        if (ObjectUtil.isNotEmpty(reportData)) {
            if (ObjectUtil.isNotEmpty(reportData.getReportDate())) {
                CwProjectInfoData line = new CwProjectInfoData();
                line.setReportDate(reportData.getReportDate());
                line.setReportId(reportData.getId());
                infoMapper.update(line, new QueryWrapper<CwProjectInfoData>().lambda().eq(CwProjectInfoData::getReportId,reportData.getId()));
            }
            CwProjectReport report = new CwProjectReport();
            if (StringUtils.isNotBlank(reportData.getRegisterAddress())){
                report.setRegisterAddress(reportData.getRegisterAddress());
            }
            if (StringUtils.isNotBlank(reportData.getBusinessLocation())){
                report.setBusinessLocation(reportData.getBusinessLocation());
            }
            if (StringUtils.isNotBlank(reportData.getSecurityBusiness())){
                report.setSecurityBusiness(reportData.getSecurityBusiness());
            }
            if (StringUtils.isNotBlank(reportData.getIndustry())){
                report.setIndustry(reportData.getIndustry());
            }
            if (StringUtils.isNotBlank(reportData.getBusinessObjects())){
                report.setBusinessObjects(reportData.getBusinessObjects());
            }
            if (ObjectUtil.isNotEmpty(report)) {
                cwProjectReportService.updateCwProjectReportDataById(report);
            }
        }
        mapper.updateReviewById(review);
        if ("5".equals(review.getReviewStatus())) {
            CwProjectRecords records = new CwProjectRecords();
            records.setId(reportData.getProjectId());
            records.setReportReview("1"); // 已开始报告复核
            recordsMapper.updatereportReviewById(records);
        }
        //对复核数据进行持久化操作
        if (CollectionUtils.isNotEmpty(reportData.getDetails())) {
            for (CwProofreadDetail detail1:reportData.getDetails()) {
                CwProofreadDetail detail2 = detailMapper.getByTypeIdAndInfoId(detail1.getTypeId(),review.getId());
                if (null == detail2) {
                    String detailId = UUID.randomUUID().toString().replace("-", "");
                    detail1.setId(detailId);
                    detail1.setInfoId(detail.getId());
                    detail1.setCreateById(userDTO.getId());
                    detail1.setCreateTime(new Date());
                    detail1.setUpdateById(userDTO.getId());
                    detail1.setUpdateTime(new Date());
                    detailMapper.insert(detail1);
                } else {
                    detail1.setCreateTime(detail2.getCreateTime());
                    detail1.setCreateById(detail2.getCreateById());
                    detail1.setId(detail2.getId());
                    detail1.setInfoId(review.getId());
                    detail1.setUpdateById(userDTO.getId());
                    detail1.setUpdateTime(new Date());
                    detailMapper.updateReportReviewInfoById(detail1);
                }
            }
        }
        return review.getId();
    }

    public String add(CwProjectReportData dto) throws Exception{

        long l1 = System.currentTimeMillis();

        //生成主键id值
        String id = UUID.randomUUID().toString().replace("-", "");
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
        //保存基本信息
        CwProjectReview info = new CwProjectReview();
        BeanUtils.copyProperties(dto, info);

        long l2 = System.currentTimeMillis();
        System.out.println("addservice1:" + (l2 -l1));
        //报告编号生成
        String documentNo = "";
        String currentToken = TokenProvider.getCurrentToken();
        if (info.getReportType().equals("1")){
            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE1,currentToken);
        } else if (info.getReportType().equals("2")){
            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE2,currentToken);
        } else if (info.getReportType().equals("3")){
            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE3,currentToken);
        } else if (info.getReportType().equals("4")){
            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE4,currentToken);
        } else if (info.getReportType().equals("5")){
            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE5,currentToken);
        }
        long l3 = System.currentTimeMillis();
        System.out.println("addservice2:" + (l3 -l2));
        info.setId(id);
        info.setReportReviewNo(documentNo);
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        info.setReportId(dto.getId());
        mapper.insert(info);
        long l4 = System.currentTimeMillis();
        System.out.println("addservice2:" + (l4 -l3));
//        CwProjectRecords records = new CwProjectRecords();
//        records.setId(dto.getProjectId());
//        records.setReportReview("1"); // 已开始报告复核
//        recordsMapper.updateById(records);
        //明细表相关信息
        if (CollectionUtils.isNotEmpty(dto.getDetails())) {
            for (CwProofreadDetail detail:dto.getDetails()) {
                String detailId = UUID.randomUUID().toString().replace("-", "");
                detail.setId(detailId);
                detail.setInfoId(id);
                detail.setCreateById(userDTO.getId());
                detail.setCreateTime(new Date());
                detail.setUpdateById(userDTO.getId());
                detail.setUpdateTime(new Date());
                detailMapper.insert(detail);
            }
        }
        long l5 = System.currentTimeMillis();
        System.out.println("addservice2:" + (l5 -l4));
        return info.getId();
    }

    public String getProcessStatus(String procInsId){
        String currentTask = flowTaskService.getCurrentTaskName(procInsId);
        if(StringUtils.isNotBlank(currentTask)) {
            return currentTask;
        } else {
            return "";
        }
    }

    public String getHaveReportNo(String reportId) {
        // 根据报告id查询是否已生成报告文号
        CwProjectInfoData byReportId = infoMapper.getByReportId(reportId);
        if(ObjectUtil.isNotEmpty(byReportId)) {
            if (StringUtils.isNotBlank(byReportId.getReportNo())) {
                return "1"; // 已生成
            }
        }
        return "0"; // 未生成
    }

    // 生成报告文号
    public void saveReportNo(String reportId) {
        String documentNo = "";
        try {
            // 根据reportId查询 new_line数据
            CwProjectInfoData reportData = infoMapper.getByReportId(reportId);
            // 生成报告文号
            //获取当前登录人信息
            UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken ( ));
            String currentToken = TokenProvider.getCurrentToken();
            if(StringUtils.isNotBlank(reportData.getReportType())) {
                ReportNoDto projectReportByNumber = new ReportNoDto();
                switch (reportData.getReportType()) {
                    case "1":   //基字
                        do{
                            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.BIZ_CODE,currentToken);
                            //根据报告号查询诗剧苦中是否存在
                            projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                        }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                        break;
                    case "2":   //咨字
                        do{
                            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.CONSULT_BIZ_CODE,currentToken);
                            //根据报告号查询诗剧苦中是否存在
                            projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                        }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                        break;
                    case "3":   //审字
                        do{
                            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.EXAMINE_BIZ_CODE,currentToken);
                            //根据报告号查询诗剧苦中是否存在
                            projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                        }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                        break;
                    case "4":   //验字
                        do{
                            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.CHECK_BIZ_CODE,currentToken);
                            //根据报告号查询诗剧苦中是否存在
                            projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                        }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                        break;
                    case "5":   //特字
                        do{
                            documentNo = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.SPECIAL_BIZ_CODE,currentToken);
                            //根据报告号查询诗剧苦中是否存在
                            projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                        }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 保存报告文号
        infoMapper.updateReportNoByReportId(reportId,documentNo);
    }
}
