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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.projectRecords.domain.CwProjectRecords;
import com.jeeplus.test.cw.projectRecords.mapper.CwProjectRecordsMapper;
import com.jeeplus.test.cw.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.test.cw.projectReport.domain.*;
import com.jeeplus.test.cw.projectReport.mapper.CwProjectInfoMapper;
import com.jeeplus.test.cw.projectReport.mapper.CwProjectReportReviewMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.test.cw.projectReport.mapper.CwProofreadDetailMapper;
import com.jeeplus.flowable.service.FlowTaskService;
import com.jeeplus.test.cw.projectReportArchive.domain.CwProjectReportArchive;
import com.jeeplus.test.cw.projectReportArchive.mapper.CwProjectReportArchiveMapper;
import com.jeeplus.test.cw.reimbursementApproval.approvalInfo.service.dto.ReportNoDto;
import com.jeeplus.test.mould.service.SerialnumTplService;
import com.jeeplus.test.cw.projectReportArchive.service.dto.CwProjectReportArchiveDTO;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.engine.TaskService;
import org.apache.commons.beanutils.PropertyUtils;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.flowable.task.api.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
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 CwProofreadDetailMapper detailMapper;

    @Resource
    private SerialnumTplService serialnumTplService;

    @Resource
    private FlowTaskService flowTaskService;

    @Resource
    private CwProjectReportArchiveMapper cwProjectReportArchiveMapper;

    @Resource
    private CwProjectInfoMapper infoMapper;

    @Resource
    private CwProjectRecordsMapper recordsMapper;

    @Resource
    private TaskService taskService;

    @Resource
    private CwProjectReportReviewMapper cwProjectReportReviewMapper;

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

        return data;
    }

    /**
     * 修改状态
     * @param data
     * @return
     */
    public String updateReviewStatysByReportId(CwProjectReportData data) {
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        mapper.updateReviewStatysByReportId(data.getReviewStatus(),data.getId(),data.getNeedUpdate2(),data.getRemark2(),
        data.getNeedUpdate3(),data.getRemark3());
        //根据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.setCreateBy(userDTO.getId());
                    detail1.setCreateDate(new Date());
                    detail1.setUpdateBy(userDTO.getId());
                    detail1.setUpdateDate(new Date());
                    detailMapper.insert(detail1);
                } else {
                    detail1.setCreateDate(detail2.getCreateDate());
                    detail1.setCreateBy(detail2.getCreateBy());
                    detail1.setId(detail2.getId());
                    detail1.setInfoId(reviewData.getId());
                    detail1.setUpdateBy(userDTO.getId());
                    detail1.setUpdateDate(new Date());
                    detailMapper.updateById(detail1);
                }
            }
        }

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

    }
    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(CwProjectReportData reportData,CwProjectReview detail) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        CwProjectReview review = new CwProjectReview();
        BeanUtils.copyProperties(reportData, review);
        review.setCreateBy(detail.getCreateBy());
        review.setCreateDate(detail.getCreateDate());
        review.setUpdateBy(userDTO.getId());
        review.setUpdateDate(new Date());
        review.setId(detail.getId());
        if (StringUtils.isNotEmpty(detail.getProcInsId())) {
            FlowNode currentTask = flowTaskService.getCurrentTask(detail.getProcInsId());
            if(null != currentTask && StringUtils.isNotBlank(currentTask.getName())) {
                if ("二级复核".equals(currentTask.getName())) {
                    //设置报告文号、报告流水号
                    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 = serialnumTplService.genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.BIZ_CODE);
                                        //根据报告号查询诗剧苦中是否存在
                                        projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                                    }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                                    break;
                                case "2":   //咨字
                                    do{
                                        documentNo = serialnumTplService.genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.CONSULT_BIZ_CODE);
                                        //根据报告号查询诗剧苦中是否存在
                                        projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                                    }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                                    break;
                                case "3":   //审字
                                    do{
                                        documentNo = serialnumTplService.genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.EXAMINE_BIZ_CODE);
                                        //根据报告号查询诗剧苦中是否存在
                                        projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                                    }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                                    break;
                                case "4":   //验字
                                    do{
                                        documentNo = serialnumTplService.genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.CHECK_BIZ_CODE);
                                        //根据报告号查询诗剧苦中是否存在
                                        projectReportByNumber = mapper.getProjectReportByNumber(documentNo);
                                    }while (null != projectReportByNumber && StringUtils.isNotBlank(projectReportByNumber.getReportNo()));
                                    break;
                                case "5":   //特字
                                    do{
                                        documentNo = serialnumTplService.genSerialNumNoSort(userDTO.getCompanyDTO().getId(), CwProjectInfoData.SPECIAL_BIZ_CODE);
                                        //根据报告号查询诗剧苦中是否存在
                                        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 ("三级复核".equals(currentTask.getName())) {
                    review.setReviewStatus("5");
                }
            }
        }
        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.update(report, new QueryWrapper<CwProjectReport>().lambda().eq(CwProjectReport::getId,reportData.getId()));
            }
        }
        mapper.updateById(review);
        if ("5".equals(review.getReviewStatus())) {
            CwProjectRecords records = new CwProjectRecords();
            records.setId(reportData.getProjectId());
            records.setReportReview("1"); // 已开始报告复核
            recordsMapper.updateById(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.setCreateBy(userDTO.getId());
                    detail1.setCreateDate(new Date());
                    detail1.setUpdateBy(userDTO.getId());
                    detail1.setUpdateDate(new Date());
                    detailMapper.insert(detail1);
                } else {
                    detail1.setCreateDate(detail2.getCreateDate());
                    detail1.setCreateBy(detail2.getCreateBy());
                    detail1.setId(detail2.getId());
                    detail1.setInfoId(review.getId());
                    detail1.setUpdateBy(userDTO.getId());
                    detail1.setUpdateDate(new Date());
                    detailMapper.updateById(detail1);
                }
            }
        }
        return review.getId();
    }

    public String add(CwProjectReportData dto) throws Exception{
        //生成主键id值
        String id = UUID.randomUUID().toString().replace("-", "");
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        //保存基本信息
        CwProjectReview info = new CwProjectReview();
        BeanUtils.copyProperties(dto, info);
        //报告编号生成
        String documentNo = "";
        if (info.getReportType().equals("1")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE1);
        } else if (info.getReportType().equals("2")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE2);
        } else if (info.getReportType().equals("3")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE3);
        } else if (info.getReportType().equals("4")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE4);
        } else if (info.getReportType().equals("5")){
            documentNo = serialnumTplService.genSerialReviewNum(userDTO.getCompanyDTO().getId(), CwProjectReview.BIZ_CODE5);
        }
        info.setId(id);
        info.setReportReviewNo(documentNo);
        info.setCreateBy(userDTO.getId());
        info.setCreateDate(new Date());
        info.setUpdateBy(userDTO.getId());
        info.setUpdateDate(new Date());
        info.setReportId(dto.getId());
        mapper.insert(info);
//        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.setCreateBy(userDTO.getId());
                detail.setCreateDate(new Date());
                detail.setUpdateBy(userDTO.getId());
                detail.setUpdateDate(new Date());
                detailMapper.insert(detail);
            }
        }
        return info.getId();
    }

    public String getProcessStatus(String procInsId){
        FlowNode currentTask = flowTaskService.getCurrentTask(procInsId);
        if(null != currentTask && StringUtils.isNotBlank(currentTask.getName())) {
            return currentTask.getName();
        } 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 byReportId = infoMapper.getByReportId(reportId);
            // 生成报告文号
            documentNo = serialnumTplService.genSerialNumNoSort(UserUtils.getCurrentUserDTO().getCompanyDTO().getId(), CwProjectInfoData.BIZ_CODE);
            if(documentNo.contains("{replacement}")){
                if(StringUtils.isNotBlank(byReportId.getReportType())){
                    switch (byReportId.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();
        }
        // 保存报告文号
        infoMapper.updateReportNoByReportId(reportId,documentNo);
    }
}
