package com.chinaweal.aiccs.aiccs.revoke.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.service.IGzaiccodeService;
import com.chinaweal.aiccs.aiccs.asyncTask.RevokeAsyncTask;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAttachmentService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSWritService;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.dict.entity.CmsDictCode;
import com.chinaweal.aiccs.aiccs.dict.service.CmsDictCodeService;
import com.chinaweal.aiccs.aiccs.forcedCancellation.entity.ForceLogoutNotice;
import com.chinaweal.aiccs.aiccs.forcedCancellation.entity.ForceLogoutNoticeDetail;
import com.chinaweal.aiccs.aiccs.forcedCancellation.entity.LicenseCancellationDeclare;
import com.chinaweal.aiccs.aiccs.forcedCancellation.service.ForceLogoutNoticeDetailService;
import com.chinaweal.aiccs.aiccs.forcedCancellation.service.ForceLogoutNoticeService;
import com.chinaweal.aiccs.aiccs.forcedCancellation.service.LicenseCancellationDeclareService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.revoke.entity.*;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.BizRevEntAttachDto;
import com.chinaweal.aiccs.aiccs.revoke.entity.dto.RevokeProcessDto;
import com.chinaweal.aiccs.aiccs.revoke.service.*;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.ConstantsUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Lee
 * @since 2022-02-16 10:27
 */
@Service
@Slf4j
public class RevokeServiceImpl implements IRevokeProcessService {

    @Resource
    private WorkFlowService workFlowService;
    @Resource
    private CmsDictCodeService cmsDictCodeService;
    @Resource
    private CaseService caseService;
    @Resource
    private TsrevtasklistService tsrevtasklistService;
    @Resource
    private TsbizrevlistService tsbizrevlistService;
    @Resource
    private TswrittemplateService tswrittemplateService;
    @Resource
    private AicorgService aicorgService;
    @Resource
    private TSWorkNoService tsWorkNoService;
    @Resource
    private TSWritService tsWritService;
    @Resource
    private BizRevEntService bizRevEntService;
    @Resource
    private TSAttachmentService attachmentService;
    @Resource
    private CreateFileService createFileService;
    @Resource
    private RevokelistService revokelistService;
    @Resource
    private EBaseinfoService eBaseinfoService;
    @Resource
    private OrgUM orgUM;
    @Resource
    private RevokeAsyncTask revokeAsyncTask;
    @Resource
    private TSOpinionService opinionService;
    @Autowired
    private ForceLogoutNoticeDetailService forceLogoutNoticeDetailService;
    @Autowired
    private ForceLogoutNoticeService forceLogoutNoticeService;
    @Autowired
    private LicenseCancellationDeclareService licenseCancellationDeclareService;

    @Override
    public void processControl(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist,
                               AICUser loginUser)throws Exception  {
        TSTwfProcessNode twfProcessNode = workFlowService.findCurrentNode(taskList.getWorkflowid());
        String link = String.format("%s_%s", twfProcessNode.getCurrentnode(), revokeProcessDto.getNextNodeID());
        TsCase caseModel = revokeProcessDto.getCaseModel();
        boolean flag = false; // 生成审批表的环节，要先推进流程，保存意见
        switch (link) {
            // 立案调查开始
            case "caseEnter_handleCase": // 经办_审核
                this.toHandleCase(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "approvalCase_caseEnter": // 回退至经办人
            case "handleCase_caseEnter": // 回退至经办人
                this.backCaseEnter(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "handleCase_handleCase": // 审核_审核
                tsbizrevlist.setStatus("2");
                break;
            case "handleCase_approvalCase": // 审核_审批
                tsbizrevlist.setStatus("3");
                break;
            case "approvalCase_handleCase": // 审批_审核
                tsbizrevlist.setStatus("2");
                this.backLastStep(revokeProcessDto, taskList,"approvalCase", "handleCase");
                break;
            // 立案调查结束  听证告知与行政处罚建议开始
            case "approvalCase_investigateEnter":// 立案审批_听证告知经办
                flag = true;
                this.toInvestigateEnter(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "investigateEnter_handleHearing": // 经办_审核
                tsbizrevlist.setStatus("8");
//                this.toHandleHearing(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "hearingRegDepLeader_investigateEnter": // 回退至经办人
            case "handleHearing_investigateEnter":
            case "approvalHearing_investigateEnter":
                this.backInvestigateEnter(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "handleHearing_handleHearing": // 审核-审核
                tsbizrevlist.setStatus("8");
                break;
            case "handleHearing_hearingRegDepLeader": // 审核-法规分派
                tsbizrevlist.setStatus("24");
//                this.toHearingRegDepLeader(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "hearingRegDepLeader_hearingRegDepHandle":
                tsbizrevlist.setStatus("25");
                break;
            case "hearingRegDepHandle_hearingRegDepLeader":
                tsbizrevlist.setStatus("26");
                break;
            case "hearingRegDepLeader_approvalHearing":
                tsbizrevlist.setStatus("9");
                break;

            // 听证告知与行政处罚建议结束  行政处罚决定开始
            case "approvalHearing_decisionEnter":
                flag = true;
                this.toDecisionEnter(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "decisionEnter_handleDecision":
                this.toHandleDecision(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "handleDecision_decisionEnter": // 回退至经办人
            case "decisionRegDepLeader_decisionEnter": // 回退至经办人
            case "approvalDecision_decisionEnter": // 回退至经办人
                this.backHandleDecision(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "handleDecision_decisionRegDepLeader":
                tsbizrevlist.setStatus("27");
                break;
            case "handleDecision_handleDecision": // 审核-审核
                tsbizrevlist.setStatus("11");
                break;
            case "decisionRegDepLeader_decisionRegDepHandle":
                tsbizrevlist.setStatus("28");
                break;
            case "decisionRegDepHandle_decisionRegDepLeader":
                tsbizrevlist.setStatus("29");
                break;
            case "decisionRegDepLeader_approvalDecision":
                tsbizrevlist.setStatus("13");
                break;
            case "approvalDecision_sendEnter":
                flag = true;
                this.toSendEnter(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            // 行政处罚决定结束
            // 归档
            case "sendEnter_endRevoke":
                tsbizrevlist.setStatus("20");
                break;
            default:
                throw new RuntimeException("流程扭转出错");
        }
        caseModel.setStatus("0");
        caseModel.setLaupTime(LocalDateTime.now());
        caseService.updateById(caseModel);//保存案件信息
        tsbizrevlist.setLauptime(LocalDateTime.now());
        tsbizrevlistService.saveOrUpdate(tsbizrevlist);

        if(!flag) {
            //流程推进
            tsrevtasklistService.updateWorkFlow(loginUser, revokeProcessDto.getOpinion(), taskList,
                    revokeProcessDto.getNextNodeID(), revokeProcessDto.getNextPerformerIds(), revokeProcessDto.getNextPerformerNames());
        }
    }

    @Override
    public void processControlZx(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist,
                                 AICUser loginUser) {
        TSTwfProcessNode twfProcessNode = workFlowService.findCurrentNode(taskList.getWorkflowid());
        String link = String.format("%s_%s", twfProcessNode.getCurrentnode(), revokeProcessDto.getNextNodeID());
        TsCase caseModel = revokeProcessDto.getCaseModel();
        boolean flag = false; // 生成审批表的环节，要先推进流程，保存意见
        switch (link) {
            // 立案调查开始
            case "batchDeactivationlEnter_handleBatchDeactivationl": // 经办_审核
                this.toHandleBatchDeactivationl(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "handleBatchDeactivationl_batchDeactivationlEnter": // 回退至经办人
                this.backBatchDeactivaEnter(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
                //handleBatchDeactivationl_approveBatchDeactivationl
            case "handleBatchDeactivationl_approveBatchDeactivationl": // 审核_审批
                this.toApproveBatchDeactivationl(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "approveBatchDeactivationl_batchDeactivationlEnter": // 审批_经办
                this.toBatchDeactivationlEntertionl(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                break;
            case "approveBatchDeactivationl_forcedLogoutEnter": // 公告审批_注销经办
                flag = true;
                try {
                    this.toForcedLogoutEnter(revokeProcessDto, taskList,tsbizrevlist, loginUser);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                break;
            case "handleCase_handleCase": // 审核_审核
                tsbizrevlist.setStatus("2");
                break;
            default:
                throw new RuntimeException("流程扭转出错");
        }

        tsbizrevlist.setLauptime(LocalDateTime.now());
        tsbizrevlistService.saveOrUpdate(tsbizrevlist);

        if(!flag) {
            //流程推进
            tsrevtasklistService.updateWorkFlowZx(loginUser, revokeProcessDto.getOpinion(), taskList,
                    revokeProcessDto.getNextNodeID(), revokeProcessDto.getNextPerformerIds(), revokeProcessDto.getNextPerformerNames());
        }
    }

    @Override
    public void backCaseEnter(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        tsbizrevlist.setStatus("1");
        // 获取主办人
        TsCase caseDB = caseService.getByBizseq(revokeProcessDto.getBizseq());
        AICUser handler = orgUM.findUserByPrimaryKey(caseDB.getHandlerId());
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});
    }

    @Override
    public void toHandleCase(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        TsCase caseModel = revokeProcessDto.getCaseModel();
        taskList.setBusname(caseModel.getCaseName());//案件名称作为待办busname
        if(StringUtils.isNotEmpty(caseModel.getIllegalAct())){// 违法行为中文
            String[] split = caseModel.getIllegalAct().split(Constant.COMMA);
            String s = split[split.length - 1];
            CmsDictCode dictCode = cmsDictCodeService.getList("illegalAct", s);
            caseModel.setIllegalActCn(dictCode.getLabel());
        }
        tsbizrevlist.setStatus("2"); // 流程中业务状态设置成 "立案审核"
    }

    @Override
    public void toApprovalCase(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        //流程推进
        tsrevtasklistService.updateWorkFlow(loginUser, revokeProcessDto.getOpinion(), taskList,
                revokeProcessDto.getNextNodeID(), revokeProcessDto.getNextPerformerIds(), revokeProcessDto.getNextPerformerNames());
        tsbizrevlist.setStatus("3"); // 流程中业务状态设置成 "立案审批"
        tsbizrevlist.setLauptime(LocalDateTime.now());
        tsbizrevlistService.saveOrUpdate(tsbizrevlist);
    }

    @Override
    public void toInvestigateEnter(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) throws Exception {
        TsCase caseDB = caseService.getByBizseq(revokeProcessDto.getBizseq());
        // 获取主办人
        AICUser handler = orgUM.findUserByPrimaryKey(caseDB.getHandlerId());
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});

        //流程推进
        tsrevtasklistService.updateWorkFlow(loginUser, revokeProcessDto.getOpinion(), taskList,
                revokeProcessDto.getNextNodeID(), revokeProcessDto.getNextPerformerIds(), revokeProcessDto.getNextPerformerNames());

        tsbizrevlist.setStatus("4"); // 流程中业务状态设置成 "听证经办"
        TsCase caseModel = revokeProcessDto.getCaseModel();
        // 立案时间，由操作时间改为手动选择的时间，之后等线下的件办完要改回来
//        caseModel.setSetTime(LocalDateTime.now());
        // 获取立案审批人手动选择的时间
        List<TSOpinion> list = opinionService.list(new LambdaQueryWrapper<TSOpinion>()
                .eq(TSOpinion::getWorkflowid, taskList.getWorkflowid())
                .eq(TSOpinion::getIsagree,"1")
                .eq(TSOpinion::getOpiniontype,"3")
                .orderByDesc(TSOpinion::getLauptime));
        caseModel.setSetTime(list.get(0).getHandledate());

        String bizseq = revokeProcessDto.getBizseq();
        String userOrgCode = aicorgService.getRegionCodeByUser(loginUser);
        List<BizRevEnt> bizRevEntList = bizRevEntService.getListByBizseq(bizseq);
        if(CollectionUtils.isEmpty(bizRevEntList))throw new BusinessException("业务主体数据为空");

        // 生成案件审批表
        createFileService.createCaseApprovalDocx(bizseq, ConstantsUtil.getAreaName(userOrgCode), userOrgCode, taskList.getWorkflowid());

        // 生成立案名单附件
        String path = createFileService.createEntExcel(bizseq, "21", bizRevEntList);
        if(path == null){
            throw new BusinessException("立案名单附件生成出错");
        }

    }

    @Override
    public void backInvestigateEnter(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        tsbizrevlist.setStatus("4");
        // 获取主办人
        TsCase caseDB = caseService.getByBizseq(revokeProcessDto.getBizseq());
        AICUser handler = orgUM.findUserByPrimaryKey(caseDB.getHandlerId());
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});
    }

    @Override
    public void toHandleHearing(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        //流程推进
        tsrevtasklistService.updateWorkFlow(loginUser, revokeProcessDto.getOpinion(), taskList,
                revokeProcessDto.getNextNodeID(), revokeProcessDto.getNextPerformerIds(), revokeProcessDto.getNextPerformerNames());
        tsbizrevlist.setStatus("8"); // 流程中业务状态设置成 "听证告知审核"
        tsbizrevlist.setLauptime(LocalDateTime.now());
        tsbizrevlistService.saveOrUpdate(tsbizrevlist);
    }

    @Override
    public void toHearingRegDepLeader(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        //流程推进
        tsrevtasklistService.updateWorkFlow(loginUser, revokeProcessDto.getOpinion(), taskList,
                revokeProcessDto.getNextNodeID(), revokeProcessDto.getNextPerformerIds(), revokeProcessDto.getNextPerformerNames());
        tsbizrevlist.setStatus("24"); // 流程中业务状态设置成 "听证告知审核"
        tsbizrevlist.setLauptime(LocalDateTime.now());
        tsbizrevlistService.saveOrUpdate(tsbizrevlist);
    }

    @Override
    public void toDecisionEnter(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) throws Exception {
        // 获取主办人
        TsCase caseDB = caseService.getByBizseq(revokeProcessDto.getBizseq());
        AICUser handler = orgUM.findUserByPrimaryKey(caseDB.getHandlerId());
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});
        //流程推进
        tsrevtasklistService.updateWorkFlow(loginUser, revokeProcessDto.getOpinion(), taskList,
                revokeProcessDto.getNextNodeID(), revokeProcessDto.getNextPerformerIds(), revokeProcessDto.getNextPerformerNames());
        tsbizrevlist.setStatus("10"); // 流程中业务状态设置成 "处罚决定经办"

        String bizseq = revokeProcessDto.getBizseq();
        List<BizRevEnt> bizRevEntList = bizRevEntService.getListByBizseq(bizseq);
        if(CollectionUtils.isEmpty(bizRevEntList))throw new BusinessException("业务主体数据为空");

        // 生成行政处罚建议审批表
        String areaName = ConstantsUtil.getAreaName(tsbizrevlist.getHandleOrg());
        createFileService.createPunishAdviceApprDocx(bizseq,areaName,taskList.getWorkflowid());

        // 生成听证名单附件
        String excelPath = createFileService.createEntExcel(bizseq, "22", bizRevEntList);
        if(excelPath == null){
            throw new BusinessException("听证告知名单附件生成出错");
        }
    }

    @Override
    public void toSendEnter(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) throws Exception {
        TsCase caseDB = caseService.getByBizseq(revokeProcessDto.getBizseq());
        // 获取主办人
        AICUser handler = orgUM.findUserByPrimaryKey(caseDB.getHandlerId());
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});
        //流程推进
        tsrevtasklistService.updateWorkFlow(loginUser, revokeProcessDto.getOpinion(), taskList,
                revokeProcessDto.getNextNodeID(), revokeProcessDto.getNextPerformerIds(), revokeProcessDto.getNextPerformerNames());
       tsbizrevlist.setStatus("14"); // 流程中业务状态设置成 "送达经办"

        LocalDateTime now = LocalDateTime.now();
        String bizseq = revokeProcessDto.getBizseq();
        String userOrgCode = aicorgService.getRegionCodeByUser(loginUser);
        List<BizRevEnt> bizRevEntList = bizRevEntService.getListByBizseq(bizseq);
        if(CollectionUtils.isEmpty(bizRevEntList))throw new BusinessException("业务主体数据为空");


        //ArrayList<Revokelist> revokelists = new ArrayList<>();
        for (BizRevEnt bizRevEnt : bizRevEntList) {
            // 保存至批吊主体信息表
            Revokelist revokelistModel = new Revokelist();
            revokelistModel.setRevlistid(bizRevEnt.getRevlistid());
            revokelistModel.setPripid(bizRevEnt.getPripid());
            revokelistModel.setEntname(bizRevEnt.getEntname());
            revokelistModel.setUniscid(bizRevEnt.getUniscid());
            revokelistModel.setRegno(bizRevEnt.getRegno());
            revokelistModel.setIntosponsorid(tsbizrevlist.getIntosponsorId());
            revokelistModel.setIntosponsorname(tsbizrevlist.getIntosponsor());
            revokelistModel.setRevokedate(now);
            revokelistModel.setRevokeRea(caseDB.getRevokeRea());
            revokelistModel.setCaseno(caseDB.getCaseNo());
            revokelistModel.setState("1");//吊销
            revokelistModel.setLauptime(LocalDateTime.now());//吊销
            revokelistModel.setPunishOrg(tsbizrevlist.getHandleOrg());
            revokelistModel.setPunishOrgCn(tsbizrevlist.getHandleOrgCn());
            //revokelists.add(revokelistModel);
            revokelistService.save(revokelistModel);

        }
        //revokelistService.saveBatch(revokelists);

        // 生成处罚决定审批表
        String areaName = ConstantsUtil.getAreaName(userOrgCode);
        createFileService.createPunishDecisionApprDocx(bizseq,areaName,taskList.getWorkflowid());
        // 生成处罚决定名单附件
        String excelPath = createFileService.createEntExcel(bizseq, "23", bizRevEntList);
        if(excelPath == null){
            throw new BusinessException("行政处罚决定名单附件生成出错");
        }
    }

    @Override
    public void toHandleDecision(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        tsbizrevlist.setStatus("11"); // 流程中业务状态设置成 "处罚决定审核"

        String bizseq = revokeProcessDto.getBizseq();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("bizseq",bizseq);
        IPage<Tsbizrevlist> revEntPage = tsbizrevlistService.getRevEntPage(new Page<>(1, 1), paramMap);
        Tsbizrevlist firstEnt = revEntPage.getRecords().get(0);
        String userOrgCode = aicorgService.getRegionCodeByUser(loginUser);
        if(tsbizrevlist.getDecWritStartNo() == null){ // 未有决定书流水号值
            Map<String, Object> map = tsWorkNoService.getBatchWrirsno(WorkNoUtil.WORKNOTYPE_33, userOrgCode, (int) revEntPage.getTotal());
            int currentNo = (int) map.get("currentNo");
            String genRule = (String) map.get("genRule");
            tsbizrevlist.setDecWritStartNo(currentNo);
            tsbizrevlist.setDecFirstWrit(genRule);
            tsbizrevlistService.updateById(tsbizrevlist);
        }

        // 生成第一份处罚决定书附件，作为预览
        Map<String, Object> map = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        map.put("year", now.getYear());
        map.put("month", now.getMonthValue());
        map.put("day", now.getDayOfMonth());
        LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tswrittemplate::getBizseq,bizseq)
                .eq(Tswrittemplate::getIsTemplate,"0")
                .eq(Tswrittemplate::getWritsType,WorkNoUtil.WORKNOTYPE_33);
        Tswrittemplate tswrittemplate = tswrittemplateService.getOne(wrapper);
        map.put("htmlContent",tswrittemplate.getContent());
        EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, firstEnt.getPripid()));
        map.put("entName", eBaseinfo.getEntname());
        map.put("uniscid", eBaseinfo.getUniscid());
        map.put("lerep", eBaseinfo.getLerep());
        map.put("dom",eBaseinfo.getDom());
        map.put("pripid", eBaseinfo.getPripid());
        map.put("entCerName", eBaseinfo.getEntname());
        String firstWritsNo = tsWorkNoService.updateWritsNo(tsbizrevlist.getDecFirstWrit(), tsbizrevlist.getDecWritStartNo());
        map.put("writsno", firstWritsNo);
        map.put("areaName",ConstantsUtil.getAreaName(userOrgCode));
        String fileName = firstEnt.getEntname() + "-处罚决定书";
        String path = "static" + File.separator +  "template" + File.separator + "punishDecision.docx";
        // attachtype为'20' 作为处罚决定书预览类型
        String docxPath = createFileService.createDocx(firstEnt.getBizseq(), fileName, "20", path, map);

    }

    @Override
    public void backHandleDecision(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        tsbizrevlist.setStatus("10");
        // 获取主办人
        TsCase caseDB = caseService.getByBizseq(revokeProcessDto.getBizseq());
        AICUser handler = orgUM.findUserByPrimaryKey(caseDB.getHandlerId());
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});
    }

    @Override
    public void backLastStep(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList,String currentNode,String nextNode) {
        String userId = workFlowService.findLastTwfprocessnodeByProcessidAndNodename(taskList.getWorkflowid(), currentNode, nextNode);
        AICUser handler = orgUM.findUserByPrimaryKey(userId);
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});
    }

    public void toHandleBatchDeactivationl(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        tsbizrevlist.setStatus("32"); // 流程中业务状态设置成 "注销审核"
        ForceLogoutNotice forceLogoutNotice = new ForceLogoutNotice();
        forceLogoutNotice.setBizseqId(revokeProcessDto.getBizseq());


    }

    public void backBatchDeactivaEnter(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        tsbizrevlist.setStatus("31");
        // 获取主办人
        AICUser handler = orgUM.findUserByPrimaryKey(tsbizrevlist.getIntosponsorId());
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});
    }

    public void toApproveBatchDeactivationl(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        tsbizrevlist.setStatus("33"); // 流程中业务状态设置成 "注销审核"

    }

    public void toBatchDeactivationlEntertionl(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) {
        tsbizrevlist.setStatus("31"); // 流程中业务状态设置成 "注销经办"
        AICUser handler = orgUM.findUserByPrimaryKey(tsbizrevlist.getIntosponsorId());
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});
    }

    public void toForcedLogoutEnter(RevokeProcessDto revokeProcessDto, Tsrevtasklist taskList, Tsbizrevlist tsbizrevlist, AICUser loginUser) throws Exception {
        // 获取主办人
        AICUser handler = orgUM.findUserByPrimaryKey(tsbizrevlist.getIntosponsorId());
        revokeProcessDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeProcessDto.setNextPerformerNames(new String[]{handler.getName()});

        //流程推进
        tsrevtasklistService.updateWorkFlow(loginUser, revokeProcessDto.getOpinion(), taskList,
                revokeProcessDto.getNextNodeID(), revokeProcessDto.getNextPerformerIds(), revokeProcessDto.getNextPerformerNames());

        tsbizrevlist.setStatus("34"); // 流程中业务状态设置成 "注销经办"


        String bizseq = revokeProcessDto.getBizseq();
        String userOrgCode = aicorgService.getRegionCodeByUser(loginUser);
        List<ForceLogoutNoticeDetail> forceLogoutNoticeDetailList = forceLogoutNoticeDetailService.getByBizSeqId(bizseq);
        if(CollectionUtils.isEmpty(forceLogoutNoticeDetailList))throw new BusinessException("业务主体数据为空");

        //生成注销公告
        // 获取当前日期（LocalDate类型）
        LocalDate currentDate = LocalDate.now();
        // 获取90天后的日期（LocalDate类型）
        LocalDate futureDate = currentDate.plusDays(90);

        LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Tswrittemplate::getBizseq,bizseq)
                .eq(Tswrittemplate::getIsTemplate,"0")
                .eq(Tswrittemplate::getWritsType,WorkNoUtil.WORKNOTYPE_64);
        Tswrittemplate tswrittemplate = tswrittemplateService.getOne(wrapper);

        ForceLogoutNotice forceLogoutNotice = new ForceLogoutNotice();
        String id = UUID.randomUUID().toString();
        forceLogoutNotice.setForceId(id);
        forceLogoutNotice.setBizseqId(bizseq);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String data =  sdf.format(new Date());
        String zxbt = tsbizrevlist.getHandleOrgCn() + data + "拟强制注销公告";
        forceLogoutNotice.setNoticeTitle(zxbt);
        forceLogoutNotice.setNoticeContent(tswrittemplate.getContent());
        forceLogoutNotice.setJudAuth(tsbizrevlist.getHandleOrg());
        forceLogoutNotice.setJudAuthCn(tsbizrevlist.getHandleOrgCn());
        forceLogoutNotice.setNoticeFrom(currentDate);
        forceLogoutNotice.setNoticeTo(futureDate);
        forceLogoutNotice.setSExtDatetime(LocalDateTime.now());

        for (ForceLogoutNoticeDetail forceLogoutNoticeDetail : forceLogoutNoticeDetailList) {
            forceLogoutNoticeDetail.setForceId(id);
            forceLogoutNoticeDetailService.updateById(forceLogoutNoticeDetail);
        }

        forceLogoutNoticeService.save(forceLogoutNotice);

        forceLogoutNoticeService.deactivationNotice(bizseq,loginUser,tsbizrevlist,taskList);

        // 生成营业执照作废声明
        for (ForceLogoutNoticeDetail detail : forceLogoutNoticeDetailList) {
            // 跳过已剔除的企业
            if ("1".equals(detail.getIsRemove())) {
                continue;
            }

            LicenseCancellationDeclare declare = new LicenseCancellationDeclare();
            declare.setRecId(UUID.randomUUID().toString());
            declare.setBizseqId(detail.getBizseqId());
            declare.setPripid(detail.getPripid());
            declare.setEntName(detail.getEntName());
            declare.setUniscid(detail.getUniscid());
            declare.setRegOrg(detail.getRegOrg());
            declare.setRegOrgCn(detail.getRegOrgCn());
            declare.setRegType("FORCE_LOGOUT");
            declare.setLicCanReason("1");
            declare.setIsoriCop("1");
            declare.setLicCanSta("营业执照因强制注销公告作废");
            declare.setLicCanDate(LocalDate.now());
            declare.setSExtFromnode(detail.getSExtFromnode());
            declare.setSExtDatetime(LocalDateTime.now());
            declare.setCreateTime(LocalDateTime.now());
            declare.setLauptime(LocalDateTime.now());

            licenseCancellationDeclareService.save(declare);
        }

    }
}
