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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.TSBizRemListMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.mapper.TSOpinionMapper;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.blacklist.entity.TPyBlacklist;
import com.chinaweal.aiccs.aiccs.blacklist.service.ITPyBlacklistService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalRemService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.aiccs.writs.entity.Tswrittemplate;
import com.chinaweal.aiccs.aiccs.writs.service.TswrittemplateService;
import com.chinaweal.aiccs.aiceps.annual.entity.TREntBaseInfoSplit;
import com.chinaweal.aiccs.aiceps.annual.service.TREntBaseInfoSplitService;
import com.chinaweal.aiccs.aicris.forgiveprudent.entity.ForgiveprudentObject;
import com.chinaweal.aiccs.aicris.forgiveprudent.service.ForgiveprudentObjectService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.crgs.moveinDetails.entity.EAlterRecoder;
import com.chinaweal.aiccs.crgs.moveinDetails.entity.EGtAlterRecoder;
import com.chinaweal.aiccs.crgs.moveinDetails.service.EAlterRecoderService;
import com.chinaweal.aiccs.crgs.moveinDetails.service.EGtAlterRecoderService;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.chinaweal.aiccs.common.base.controller.BaseController.getLoginUser;

/**
 * <p>
 * 移出经营异常名录业务表 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-01-19
 */
@Service
@Slf4j
public class TSBizRemListServiceImpl extends ServiceImpl<TSBizRemListMapper, TSBizRemList> implements TSBizRemListService {

    @Autowired
    private TSAbnListService abnListService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSWorkNoService workNoService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private CreatePdfService createPdfService;
    @Autowired
    private TswrittemplateService tswrittemplateService;
    @Lazy
    @Autowired
    private IGzaiccodeService gzaiccodeService;
    @Autowired
    private TSTwfProcessNodeService tsTwfProcessNodeService;
    @Lazy
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Lazy
    @Autowired
    private TSAbnListService tsAbnListService;
    @Resource
    private TSOpinionMapper tsOpinionMapper;
    @Autowired
    private TSAttachmentService tsAttachmentService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSOpinionService opinionService;
    @Resource
    private UuidUtil uuidUtil;
    @Autowired
    private TSBizSerIllegalRemService tsBizSerIllegalRemService;
    @Autowired
    private ForgiveprudentObjectService forgiveprudentObjectService;
    @Autowired
    private TREntBaseInfoSplitService trEntBaseInfoSplitService;
    @Autowired
    private EGtAlterRecoderService eGtAlterRecoderService;
    @Autowired
    private EAlterRecoderService eAlterRecoderService;
    @Autowired
    private ITPyBlacklistService iTPyBlacklistService;

    @Override
    public TSTaskList saveBizRemListAuditProcess(AICUser user, TSTaskList taskListModel, List<TSBizRemList> bizRemListModelList, TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        try {
            if (StringUtils.isNotBlank(taskListModel.getAcceptgroupid())) {
                workFlowService.claimGroup(taskListModel.getWorkflowid(), user.getPrimaryKey());
            }
            taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
            String orgCode = aicorgService.getRegionCodeByUser(user);
            for (TSBizRemList tsBizRemListModel : bizRemListModelList) {
                String type = tsBizRemListModel.getType();
                if (FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST.equals(nextNodeID)) {//审批
                    if ("0".equals(tsBizRemListModel.getIsAgreeRepair())) {
                        tsBizRemListModel.setStatus("3"); //不予修复
                    } else {
                        tsBizRemListModel.setStatus("1"); // 审批流程中把状态设置成 "审批中"
                    }
                    tsBizRemListModel.setLauptime(LocalDateTime.now());
                    saveOrUpdate(tsBizRemListModel);
                }
                LocalDate now = LocalDate.now();
                if (FlowUtil.EXPTLISTWORKFLOW_ENDEXPTLIST.equals(nextNodeID)) { //完结时
                    TSAbnList abnListModel = abnListService.getById(tsBizRemListModel.getAbnlistid());
                    TSAbnList tsAbnListModel = new TSAbnList();
                    tsAbnListModel.setAbnlistid(abnListModel.getAbnlistid());
                    LocalDateTime nowDateTime = LocalDateTime.now();
                    TSWrit tsWritModel = new TSWrit();
                    String tswritId = UUID.randomUUID().toString();
                    tsWritModel.setWritsid(tswritId);
                    String workNoType = "";
                    String workNoTypeSearch = "";
                    String codeId = "";
                    String path = "";
                    if ("0".equals(tsBizRemListModel.getIsAgreeRepair())) {
                        if ("company".equals(type) || "farmer".equals(type)) {
                            workNoType = WorkNoUtil.WORKNOTYPE_55; //企业农专-不予信用修复决定书
                        } else if ("individual".equals(type)) {
                            workNoType = WorkNoUtil.WORKNOTYPE_58; //个体户-不予信用修复决定书
                        }
                        path = "static" + File.separator + "template" + File.separator + "noRepairDec.docx";
                        tsBizRemListModel.setHandleStatus("4");
                        workNoTypeSearch = WorkNoUtil.WORKNOTYPE_52;
                    } else if ("1".equals(tsBizRemListModel.getIsAgreeRepair())) {
                        if ("company".equals(type)) {
                            workNoType = WorkNoUtil.WORKNOTYPE_56; //企业农专-准予信用修复决定书
                            codeId = "C14007"; // 旧代码CD72，改新的C14007，两者区别只在于中文描述少了“三年内”
                        } else if ("farmer".equals(type)) {
                            workNoType = WorkNoUtil.WORKNOTYPE_56;
                            codeId = "CD78";
                        } else if ("individual".equals(type)) {
                            workNoType = WorkNoUtil.WORKNOTYPE_59; //个体户-准予信用修复决定书
                            codeId = "CD76";
                        }
                        path = "static" + File.separator + "template" + File.separator + "repairDec.docx";
                        tsBizRemListModel.setHandleStatus("3");
                        workNoTypeSearch = WorkNoUtil.WORKNOTYPE_53;
                        if (StringUtils.isBlank(tsBizRemListModel.getRemexcpres())) {
                            throw new BusinessException("移出经营异常名录原因为空！");
                        }
                        tsAbnListModel.setRemexcpres(tsBizRemListModel.getRemexcpres());
                        Map<String, TRBaseCode> remCodeMap = baseCodeService.getBaseCodeMapFormCache(codeId);
                        TRBaseCode code = remCodeMap.get(tsBizRemListModel.getRemexcpres());
                        if (code != null) {
                            tsAbnListModel.setRemreasons(code.getName());
                        }
                        tsAbnListModel.setRemSponsor(tsBizRemListModel.getRemSponsor()); // 移出主办人
                        if (now == null) {
                            throw new BusinessException("移出经营异常名录移出日期为空！");
                        }
                        if (now.isBefore(abnListModel.getAbntime())) {
                            throw new BusinessException("移出经营异常名录移出日期小于列入经营异常日期！");
                        }
                        tsAbnListModel.setRemdate(now);
                        tsAbnListModel.setOperatestatus("0");
                        tsAbnListModel.setLauptime(LocalDateTime.now());
                        tsAbnListModel.setRemRemark(tsBizRemListModel.getRemRemark());
                        if (tsBizRemListModel.getDecorg() != null) {
                            tsAbnListModel.setRemDecorg(tsBizRemListModel.getDecorg());// 移出决定机关码值
                        } else {
                            tsAbnListModel.setRemDecorg(orgCode);
                        }
                        String decOrgName = gzaiccodeService.getNameByCode(tsAbnListModel.getRemDecorg());
                        if (decOrgName == null || "".equals(decOrgName)) {
                            throw new BusinessException("移出经营异常名录移出决定机关中文为空！");
                        }
                        tsAbnListModel.setReDecorg(decOrgName);// 移出决定机关中文
                    }
                    LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(Tswrittemplate::getBizseq, tsBizRemListModel.getBizseq())
                            .eq(Tswrittemplate::getIsTemplate, "0")
                            .eq(Tswrittemplate::getWritsType, workNoType);
                    Tswrittemplate tswrittemplate = tswrittemplateService.getOne(wrapper);
                    tsWritModel.setBizseq(tsBizRemListModel.getBizseq());
                    //获取用户所在部门辖区码值
                    if (tsBizRemListModel.getAreaCode() != null && !tsBizRemListModel.getAreaCode().equals("150000")) {
                        tsWritModel.setAreaCode(tsBizRemListModel.getAreaCode());
                    } else {
                        tsBizRemListModel.setAreaCode(orgCode);
                        tsWritModel.setAreaCode(orgCode);
                    }


                    tsWritModel.setWritsno(workNoService.getOperatingWrirsno(workNoTypeSearch, tsWritModel.getAreaCode())); //当前用户的regionID
                    tsWritModel.setWritstype(workNoType);
                    tsWritModel.setPripid(tsBizRemListModel.getPripid());
                    tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
                    tsWritModel.setCreatetime(nowDateTime);
                    tsWritModel.setLauptime(nowDateTime);
                    if (tswrittemplate != null) {
                        tsWritModel.setContent(tswrittemplate.getContent());
                    }

                    // 生成决定书附件
                    HashMap<String, Object> map = new HashMap<>();
                    String cityName = Constant.NM_REGION_CODE.get(tsWritModel.getAreaCode().substring(0, 4) + "00");
                    String locName = Constant.NM_LOC_REGION_CODE.get(tsWritModel.getAreaCode());
                    String areaName = cityName + locName;
                    areaName = StringUtils.equals(tsWritModel.getAreaCode(),"150000") ? "内蒙古自治区" : areaName;
                    map.put("areaName", areaName);
                    map.put("writsNo", tsWritModel.getWritsno());
                    map.put("htmlContent", tsWritModel.getContent());
                    String approveDate = DateUtils.localDateFormat(now, "yyyy年MM月dd日");
                    map.put("approveDate", approveDate);

                    String pdfPath = createPdfService.createPdfWithHtmlTemplate(tsBizRemListModel.getBizseq(), path, map);
                    if (StringUtils.isNotBlank(pdfPath)) {
                        tsWritModel.setPath(pdfPath);
                    }
                    tsWritService.save(tsWritModel);

                    tsAbnListModel.setRemwritid(tswritId);
                    if ("0".equals(tsBizRemListModel.getAppOrPc())) {
                        if ("0".equals(tsBizRemListModel.getIsAgreeRepair())) {
                            if ("company".equals(type) || "farmer".equals(type)) {
                                workNoType = WorkNoUtil.WORKNOTYPE_57; //企业农专-不予信用修复决定书--无印章
                            } else if ("individual".equals(type)) {
                                workNoType = WorkNoUtil.WORKNOTYPE_60; //个体户-不予信用修复决定书--无印章
                            }
                            String path1 = "static" + File.separator + "template" + File.separator + "noRepairDecNoSeal.docx";
                            map.put("htmlContent", tsWritModel.getContent());
                            String pdfPath1 = createPdfService.createPdfWithHtmlTemplate(tsBizRemListModel.getBizseq(), path1, map);
                            TSWrit tsWrit = new TSWrit();
                            BeanUtils.copyProperties(tsWritModel, tsWrit);
                            tsWrit.setWritstype(workNoType);
                            tsWrit.setWritsid(UUID.randomUUID().toString());
                            if (StringUtils.isNotBlank(pdfPath1)) {
                                tsWrit.setPath(pdfPath1);
                            }
                            tsWritService.save(tsWrit);
                        } else if ("1".equals(tsBizRemListModel.getIsAgreeRepair())) {
                            if ("company".equals(type) || "farmer".equals(type)) {
                                workNoType = WorkNoUtil.WORKNOTYPE_62; //企业农专-准予信用修复决定书--无印章
                            } else if ("individual".equals(type)) {
                                workNoType = WorkNoUtil.WORKNOTYPE_63; //个体户-准予信用修复决定书--无印章
                            }
                            String path1 = "static" + File.separator + "template" + File.separator + "repairDecNoSeal.docx";
                            map.put("htmlContent", tsWritModel.getContent());
                            String pdfPath1 = createPdfService.createPdfWithHtmlTemplate(tsBizRemListModel.getBizseq(), path1, map);
                            TSWrit tsWrit = new TSWrit();
                            BeanUtils.copyProperties(tsWritModel, tsWrit);
                            tsWrit.setWritstype(workNoType);
                            tsWrit.setWritsid(UUID.randomUUID().toString());
                            if (StringUtils.isNotBlank(pdfPath1)) {
                                tsWrit.setPath(pdfPath1);
                            }
                            tsWritService.save(tsWrit);
                        }
                    }

                    abnListService.saveOrUpdate(tsAbnListModel);
                    tsBizRemListModel.setApprovaldate(now); //核准时间
                    if (!"3".equals(tsBizRemListModel.getStatus())) {
                        tsBizRemListModel.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
                    }
                    tsBizRemListModel.setLauptime(LocalDateTime.now());
                    updateById(tsBizRemListModel);
                }
                if (FlowUtil.EXPTLISTWORKFLOW_OVEREXPTLIST.equals(nextNodeID)) {
                    tsBizRemListModel.setApprovaldate(now); //核准时间
                    tsBizRemListModel.setStatus("3"); // 9 受理中、1 审批中、2 已通过、3 不通过
                    tsBizRemListModel.setHandleStatus("4");
                    tsBizRemListModel.setLauptime(LocalDateTime.now());
                    updateById(tsBizRemListModel);
                }
                if (FlowUtil.EXPTLISTWORKFLOW_OVERFINISH.equals(nextNodeID)) {
                    tsBizRemListModel.setApprovaldate(now); //核准时间
                    tsBizRemListModel.setStatus("3"); // 9 受理中、1 审批中、2 已通过、3 不通过
                    tsBizRemListModel.setHandleStatus("5");
                    tsBizRemListModel.setLauptime(LocalDateTime.now());
                    updateById(tsBizRemListModel);
                }
            }
        } catch (Exception e) {
            log.error("移出经营异常名录审核出错", e);
            throw new BusinessException("移出经营异常名录审核出错");
        }
        return taskListModel;
    }

    @Override
    public List<TSBizRemList> selectBRMexptlist(TSBizRemList tsBizRemListModel) {
        return baseMapper.selectBRMexptlist(tsBizRemListModel);
    }

    @Override
    public IPage<TSBizRemList> selectbizRemlist(IPage<TSBizRemList> page, TSBizRemList tsBizSpeListModel) {
        return baseMapper.selectbizRemByPagelist(page, tsBizSpeListModel);
    }

    @Override
    public TSTaskList saveAbnListStart(AICUser aicUser, TSTaskList taskListModel, List<TSBizRemList> bizRemListModelList) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            for (TSBizRemList tsBizRemListModel : bizRemListModelList) {
                if ("1".equals(tsBizRemListModel.getAppOrPc())) {// 移动端不设置移出主办人信息
                    tsBizRemListModel.setRemSponsor(aicUser.getName());// 移出主办人
                    tsBizRemListModel.setRemSponsorID(aicUser.getPrimaryKey());// 移出主办人id
                }
                tsBizRemListModel.setStatus("9"); // 流程启动把状态设置为 "受理中"
                saveOrUpdate(tsBizRemListModel);
            }
            String definedname = FlowUtil.EXPTLISTWORKFLOW;//企业经营异常名录流程模板
            //新待办
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, aicUser);
            //开始工作流
            taskListService.startWorkFlow(taskListModel, aicUser, definedname);
        }
        return taskListModel;
    }

    @Override
    public TSTaskList saveAbnListStartApp(AICUser aicUser, List<String> userIdList, TSTaskList taskListModel, List<TSBizRemList> bizRemListModelList) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            for (TSBizRemList tsBizRemListModel : bizRemListModelList) {
                tsBizRemListModel.setStatus("9"); // 流程启动把状态设置为 "受理中"
                saveOrUpdate(tsBizRemListModel);
            }
            String definedName = FlowUtil.EXPTLISTWORKFLOW; // 企业经营异常名录流程模板
            // 新待办
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel);
            // 开始工作流
            taskListService.startWorkFlow(taskListModel, userIdList, aicUser.getRegionID().substring(0, 6), definedName);
        }
        return taskListModel;
    }


    @Override
    public List<TSBizRemList> selectbizRembizseq(String bizseqid) {
        return baseMapper.selectbizRembizseq(bizseqid);
    }

    @Override
    public List<TSBizRemList> selectbizRemByPriPid(Map<String, Object> parm) {
        return baseMapper.selectbizRemByPriPid(parm);
    }

    @Override
    public List<TSBizRemList> selectbizRemByPriPidAndBIZSEQ(Map<String, Object> parm) {
        return baseMapper.selectbizRemByPriPidAndBIZSEQ(parm);
    }

    @Override
    public List<TSBizRemList> selectbizRem(Map<String, Object> parm) {
        return baseMapper.selectbizRem(parm);
    }

    @Override
    public List<TSBizRemList> queryByxyh(String remSponsorID) {
        return baseMapper.queryByxyh(remSponsorID);
    }

    @Override
    public TSTaskList saveAbnListtoxyh(AICUser aicUser, TSTaskList taskListModel) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            String definedname = FlowUtil.EXPTLISTWORKFLOW;//企业经营异常名录流程模板
            //新待办
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, aicUser);
            //开始工作流
            taskListService.startWorkFlow(taskListModel, aicUser, definedname);
        }
        return taskListModel;
    }

    @Override
    public void insertIdTobak(String tasklistid) {
        baseMapper.insertIdTobak(tasklistid);
    }

    @Override
    public List<TSBizRemList> checkTaskList(String ABNLISTID) {
        return baseMapper.checkTaskList(ABNLISTID);
    }

    @Override
    public String checkWritNoWithSleep(String type, String code) {
        System.out.println("sleep查询开始" + "==========");
        String no = workNoService.getOperatingWrirsno(type, code);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("sleep查询完成" + "==========" + no);
        return no;
    }

    @Override
    public String checkWritNo(String type, String code) {
        System.out.println("查询开始" + "==========");
        String no = workNoService.getOperatingWrirsno(type, code);
        System.out.println("查询完成" + "==========" + no);
        if (StringUtils.isNotBlank(no)) {
            throw new RuntimeException("--");
        }
        return no;
    }

    @Override
    public void cancelBusiness(String bizseq) {
        TSBizRemList tsBizRemList = getOne(new LambdaQueryWrapper<TSBizRemList>().eq(TSBizRemList::getBizseq, bizseq));
        tsBizRemList.setStatus("3");
        tsBizRemList.setHandleStatus("5");
        tsBizRemList.setLauptime(LocalDateTime.now());
        tsBizRemList.setRemRemark("申请人主动撤销");
        updateById(tsBizRemList);
        TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizseq)
                .eq(TSTaskList::getBusstatus, "5"));
        List<TSTwfProcessNode> tsTwfProcessNodes = tsTwfProcessNodeService.queryByPROCESSIDAndCURRENTNODE(taskList.getWorkflowid(), FlowUtil.EXPTLISTWORKFLOW_EXPTLISTENTER);
        String nextPerformerids = tsTwfProcessNodes.get(0).getCurruserid();
        String nextPerformerNames = tsTwfProcessNodeService.queryRealName(tsTwfProcessNodes.get(0).getCurruserid());
        String[] ids = StringUtils.split(nextPerformerids, Constant.COMMA);
        String[] names = StringUtils.split(nextPerformerNames, Constant.COMMA);
        taskListService.updateWorkFlowApp(taskList, FlowUtil.EXPTLISTWORKFLOW_OVEREXPTLIST, ids, names);
    }

    /**
     * 退回移动端后撤销业务---经营异常--pc
     *
     * @param bizseq
     */
    @Override
    public void pcCancelBusiness(String bizseq) {
        TSBizRemList tsBizRemList = getOne(new LambdaQueryWrapper<TSBizRemList>().eq(TSBizRemList::getBizseq, bizseq)
                .eq(TSBizRemList::getHandleStatus, "2"));
        tsBizRemList.setStatus("3");
        tsBizRemList.setHandleStatus("5");
        tsBizRemList.setLauptime(LocalDateTime.now());
        updateById(tsBizRemList);
        TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, bizseq)
                .eq(TSTaskList::getBusstatus, "5"));
        List<TSTwfProcessNode> tsTwfProcessNodes = tsTwfProcessNodeService.queryByPROCESSIDAndCURRENTNODE(taskList.getWorkflowid(), FlowUtil.EXPTLISTWORKFLOW_EXPTLISTENTER);
        String nextPerformerids = tsTwfProcessNodes.get(0).getCurruserid();
        String nextPerformerNames = tsTwfProcessNodeService.queryRealName(tsTwfProcessNodes.get(0).getCurruserid());
        String[] ids = StringUtils.split(nextPerformerids, Constant.COMMA);
        String[] names = StringUtils.split(nextPerformerNames, Constant.COMMA);
        taskListService.updateWorkFlowApp(taskList, FlowUtil.EXPTLISTWORKFLOW_OVEREXPTLIST, ids, names);
    }

    @Override
    public RestResult<?> selectHistorybizRemlist(String bizseq) {
        Map<String, Object> resultMap = new HashMap<>();
        TSBizRemList bizRemListModel = baseMapper.queryHistoryInfo(bizseq);
        resultMap.put("bizRemListMOdel", bizRemListModel);
        EBaseinfo eBaseinfo = eBaseinfoService.getById(bizRemListModel.getPripid());
        resultMap.put("bizList", eBaseinfo);
        TSAbnList tsAbnList = tsAbnListService.getById(bizRemListModel.getAbnlistid());
        resultMap.put("tsAbnList", tsAbnList);
        List<TSOpinion> tsOpinions = tsOpinionMapper.queryOldOpninion(bizseq);
        tsOpinions.forEach(each -> {
            String type = each.getOpiniontype();
            if (StringUtils.isNotBlank(type)) {
                each.setOpiniontype(String.valueOf(Integer.parseInt(type) - 1));
            }
        });
        resultMap.put("tsOpinions", tsOpinions);
        List<TSAttachment> tsAttachments = tsAttachmentService.queryFileByHistory(bizseq);
        resultMap.put("tsAttachments", tsAttachments);
        String content = baseMapper.queryHistoryContent(bizseq);
        resultMap.put("content", content);
        return RestResult.ok(resultMap);
    }

    @Override
    public RestResult<?> bizRemoveNext(HttpServletRequest request, TSBizRemList tsBizRemListModel, TSOpinion opinionModel,
                                       String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID, String entertype) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        if ("handleExptlist".equals(nextNodeID) || "overFinish".equals(nextNodeID)) {
            if (tsBizRemListModel != null && StringUtils.isNotBlank(tsBizRemListModel.getBizseq())) {

                //删除待办
                LambdaQueryWrapper<TSTaskList> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TSTaskList::getBizseqid, tsBizRemListModel.getBizseq())
                        .ne(TSTaskList::getBusstatus, BaseDataConstant.BUSINESS_STATUS_XYXF_END);
                List<TSTaskList> tsTaskLists = taskListService.list(wrapper);
                List<TSBizRemList> tsBizRemLists = this.list(new LambdaQueryWrapper<TSBizRemList>().eq(TSBizRemList::getBizseq, tsBizRemListModel.getBizseq()));
                if (CollectionUtils.isNotEmpty(tsTaskLists)) {

                    boolean isExist = false;
                    if (tsTaskLists.size() > 1) {
                        for (int i = 0; i < tsTaskLists.size(); i++) {
                            if (user.getPrimaryKey().equals(tsTaskLists.get(i).getSignuserid())) {
                                tsTaskLists.get(i).setIsBack("0");
                                taskListService.updateById(tsTaskLists.get(i));
                                tsTaskLists.remove(tsTaskLists.get(i));
                                isExist = true;
                                break;
                            }
                        }
                        if (isExist) {
                            for (int i = 0; i < tsTaskLists.size(); i++) {
                                TSTaskList task = tsTaskLists.get(i);
                                task.setBusstatus(BaseDataConstant.BUSINESS_STATUS_XYXF_END);
                                task.setIsBack("0");
                                taskListService.updateById(task);
                                if (tsBizRemLists.size() > 1) {
                                    LambdaQueryWrapper<TSBizRemList> queryWrapper = new LambdaQueryWrapper<>();
                                    queryWrapper.eq(TSBizRemList::getBizseq, task.getBizseqid())
                                            .eq(TSBizRemList::getRemSponsorID, task.getSignuserid());
                                    TSBizRemList bizRemListDB = this.getOne(queryWrapper);
                                    if (bizRemListDB != null) {
                                        bizRemListDB.setBizseq("");
                                        this.updateById(bizRemListDB);
                                    }
                                }

                            }
                        } else {
                            throw new BusinessException("业务办理错误");
                        }

                    } else {
                        if (tsTaskLists.size() == 1 && !user.getPrimaryKey().equals(tsTaskLists.get(0).getSignuserid())) {
                            throw new BusinessException("业务已在办理中");
                        }
                    }
                }

            }
        }


        Map<String, Object> resultMap = new HashMap<>();
        //更新 异常名录移出业务表
        if (tsBizRemListModel != null && StringUtils.isNotBlank(tsBizRemListModel.getBizseq())) {

            //批量，业务主体有多个
            List<TSBizRemList> tsBizRemLists = this.list(new LambdaQueryWrapper<TSBizRemList>().eq(TSBizRemList::getBizseq, tsBizRemListModel.getBizseq()));
            if (CollectionUtils.isEmpty(tsBizRemLists)) {
                throw new BusinessException(ResultCode.BUSINESS_LOGIC_ERROR);
            }
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            TSTwfProcessNode processNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());

            String decOrgCode = aicorgService.getRegionCodeByUser(user);
            for (TSBizRemList bizRemListModel : tsBizRemLists) {
                //下一步为审核
                if (FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST.equals(nextNodeID)) {
                    if (FlowUtil.EXPTLISTWORKFLOW_EXPTLISTENTER.equals(processNode.getCurrentnode())) {
                        bizRemListModel.setRemRemark(StringUtils.isNotBlank(tsBizRemListModel.getRemRemark()) ? tsBizRemListModel.getRemRemark() : StringUtils.EMPTY);
                        bizRemListModel.setReconsiderationOrg(tsBizRemListModel.getReconsiderationOrg());
                        bizRemListModel.setGovernmentOrg(tsBizRemListModel.getGovernmentOrg());
                        bizRemListModel.setLitiOrg(tsBizRemListModel.getLitiOrg());
                        bizRemListModel.setRemexcpres(tsBizRemListModel.getRemexcpres());// 移出原因
                        bizRemListModel.setRemreasons(tsBizRemListModel.getRemreasons());// 作出决定的事实、理由、依据及主要内容
                        if (StringUtils.isNotEmpty(tsBizRemListModel.getIsAccept())) {
                            bizRemListModel.setIsAccept(tsBizRemListModel.getIsAccept());
                        }
                        if (StringUtils.isNotEmpty(tsBizRemListModel.getIsAgreeRepair())) {
                            bizRemListModel.setIsAgreeRepair(tsBizRemListModel.getIsAgreeRepair());
                        }
                        if (tsBizRemListModel.getApplicant() != null) {
                            bizRemListModel.setApplicant(tsBizRemListModel.getApplicant());
                        }
                        if ("0".equals(bizRemListModel.getAppOrPc())) {
                            bizRemListModel.setRemSponsor(user.getName());// 移出主办人
                            bizRemListModel.setRemSponsorID(user.getPrimaryKey());// 移出主办人id
                            bizRemListModel.setDecorg(decOrgCode);
                            bizRemListModel.setAreaCode(decOrgCode);
                        }
                    }
                }
            }
            if (StringUtils.isBlank(nextPerformerids)) {
                TSTwfProcessNode processNode1 = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
                int order = WorkFlowUtil.checkNextOrder(processNode1.getCurrentnode(), nextNodeID);
                // 通过order判断为回退还是前进 >0前进
                if (order > 0) {
                    LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TSOpinion::getWorkflowid, taskListModel.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, "0")// 经办为0
                            .orderByDesc(TSOpinion::getLauptime);
                    List<TSOpinion> list = opinionService.list(wrapper);
                    if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                        return RestResult.error(ResultCode.DATA_NONE);
                    }
                    nextPerformerids = list.get(0).getHandlerid();
                    nextPerformerNames = list.get(0).getHandler();
                }
                // 回退时 获取经办人
                if (order < 0) {
                    // 获取经办人
                    LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TSOpinion::getWorkflowid, taskListModel.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, '0')
                            .orderByDesc(TSOpinion::getLauptime);
                    List<TSOpinion> list = opinionService.list(wrapper);
                    if (CollectionUtils.isEmpty(list)) {
                        return RestResult.error(ResultCode.DATA_NONE);
                    }
                    nextPerformerids = list.get(0).getHandlerid();
                    nextPerformerNames = list.get(0).getHandler();
                }
            }


            //发送
            String[] ids = StringUtils.split(nextPerformerids, Constant.COMMA);
            String[] names = StringUtils.split(nextPerformerNames, Constant.COMMA);
            try {

                TSTaskList tsTaskList = this.saveBizRemListAuditProcess(user, taskListModel, tsBizRemLists, opinionModel, nextNodeID, ids, names);
                if (FlowUtil.EXPTLISTWORKFLOW_EXPTLISTENTER.equals(nextNodeID)) {
                    LocalDateTime now = LocalDateTime.now();
                    // 回退时，所有有权限经办人都可以看到并办理
                    TSBizRemList bizRemList = tsBizRemLists.get(0);
                    if ("0".equals(bizRemList.getAppOrPc())) {// 移动端发起的业务才需要更新
                        String bizseq = bizRemList.getBizseq();
                        TSAbnList abnList = tsAbnListService.getById(bizRemList.getAbnlistid());
                        // 先获取所有有权限的人
                        // 判断主体类型
                        String permission = "";
                        if ("individual".equals(bizRemList.getType())) {
                            permission = "individualRecoverAccept";
                        } else if ("farmer".equals(bizRemList.getType())) {
                            permission = "agricultureRecoverAccept";
                        } else if ("company".equals(bizRemList.getType())) {
                            permission = "exptRemoveEnter";
                        }
                        List<AICUser> userList = gzaiccodeService.byPermissionListHandleUserList(bizRemList.getPripid(), permission, abnList.getDecorg(), abnList.getIntoDecorg());
                        if (userList == null || userList.isEmpty()) {
                            log.error("分派失败，权限用户列表为空,bizRemList为：{},权限为：{}，abnList为{}", bizRemList, permission, abnList);
                            throw new BusinessException("权限用户列表为空！");
                        }
                        // 将这些人的待办设置为在办，并且用同一个workflowid
                        for (AICUser aicUser : userList) {
                            if (aicUser.getPrimaryKey().equals(tsTaskList.getSignuserid())) {// 一开始的经办人，无需再设置
                                continue;
                            } else {
                                LambdaQueryWrapper<TSTaskList> wrapper = new LambdaQueryWrapper<>();
                                wrapper.eq(TSTaskList::getBizseqid, bizseq)
                                        .eq(TSTaskList::getSignuserid, aicUser.getPrimaryKey());
                                TSTaskList taskListDB = taskListService.getOne(wrapper, false);
                                if (taskListDB == null) {
                                    TSTaskList taskListNew = new TSTaskList();
                                    BeanUtils.copyProperties(tsTaskList, taskListNew);
                                    taskListNew.setTasklistid(null);
                                    //设置受理号
//                                    taskListNew.setAcceptno(aicUser.getRegionID().substring(0, Math.min(aicUser.getRegionID().length(), 6)) + uuidUtil.getCurAcceptNo());
                                    //因xr_id_maker容易被锁，临时用新的生成规则生成受理编号
                                    LocalDateTime nowLocalDateTime = LocalDateTime.now();  // 获取当前日期和时间
                                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  // 定义格式化模式
                                    String formattedDate = nowLocalDateTime.format(formatter);  // 将日期格式化为字符串
                                    String acceptno = "7" + formattedDate + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
                                    taskListNew.setAcceptno(acceptno);

                                    //设置签收人信息
                                    taskListNew.setSignuserid(aicUser.getPrimaryKey());
                                    taskListNew.setSignloginname(aicUser.getName());
                                    taskListService.save(taskListNew);
                                    log.info("回退时，经办人{}{}没有待办，重新创建待办：{}", aicUser.getName(), aicUser.getEname(), taskListNew.getTasklistid());
                                } else {
                                    taskListDB.setWorkflowid(tsTaskList.getWorkflowid());// 重设workflowid，才可回显之前意见记录
                                    taskListDB.setSendername(tsTaskList.getSendername());
                                    taskListDB.setSendertime(tsTaskList.getSendertime());
                                    taskListDB.setSenderuserid(tsTaskList.getSenderuserid());
                                    taskListDB.setSigntime(tsTaskList.getSigntime());
                                    taskListDB.setBusstatus(tsTaskList.getBusstatus());
                                    taskListDB.setLauptime(now);
                                    taskListService.updateById(taskListDB);
                                    log.info("回退时，经办人{}{}有待办，更新待办：{}", aicUser.getName(), aicUser.getEname(), taskListDB.getTasklistid());
                                }
                            }
                        }
                        // 重新设置业务表为未认领状态
                        bizRemList.setRemSponsor(null);
                        bizRemList.setRemSponsorID(null);
                        bizRemList.setLauptime(now);
                        this.updateById(bizRemList);
                    }
                }
                if (ids.length == 1 && StringUtils.equals(user.getPrimaryKey(), ids[0])) {
                    resultMap.put("bizseq", tsBizRemListModel.getBizseq());
                    resultMap.put("nextNodeId", nextNodeID);
                    resultMap.put("taskListId", tasklistid);
                    resultMap.put("workFlowId", taskListModel.getWorkflowid());
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("移出经营异常名录审核审批出错");
            }
        }
        return RestResult.ok(resultMap);
    }

    @Override
    public int getInsertDeadlineDate(String speCause, String busType, boolean isApply) {
        /*
          （1）符合第五条第（一）（二）项规定进行信用修复的，办理时限五个工作日，起算点为收到申请之日的次日；
          （2）符合第五条第（三）（四）项规定进行信用修复的，办理时限五个工作日，起算点为收到申请之日的次日；
          （3）违反《企业名称登记管理规定》进行信用修复的，办理时限五个工作日，起算点为收到申请之日的次日；
         */
        int num = 5;
        return num;
    }

    @Override
    public RestResult<?> bizRemoveNext(AICUser user, TSBizRemList tsBizRemListModel, TSOpinion opinionModel, String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID, String entertype) {
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        if ("handleExptlist".equals(nextNodeID) || "overFinish".equals(nextNodeID)) {
            if (tsBizRemListModel != null && org.apache.commons.lang.StringUtils.isNotBlank(tsBizRemListModel.getBizseq())) {

                //删除待办
                LambdaQueryWrapper<TSTaskList> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TSTaskList::getBizseqid, tsBizRemListModel.getBizseq())
                        .ne(TSTaskList::getBusstatus, BaseDataConstant.BUSINESS_STATUS_XYXF_END);
                List<TSTaskList> tsTaskLists = taskListService.list(wrapper);
                List<TSBizRemList> tsBizRemLists = list(new LambdaQueryWrapper<TSBizRemList>().eq(TSBizRemList::getBizseq, tsBizRemListModel.getBizseq()));
//                List<TSTaskList> tsTaskLists = taskListService.selectTaskListByBizseqid(tsBizRemListModel.getBizseq());
                if (CollectionUtils.isNotEmpty(tsTaskLists)) {

                    boolean isExist = false;
                    if (tsTaskLists.size() > 1) {
                        for (int i = 0; i < tsTaskLists.size(); i++) {
                            if (user.getPrimaryKey().equals(tsTaskLists.get(i).getSignuserid())) {
                                tsTaskLists.get(i).setIsBack("0");
                                taskListService.updateById(tsTaskLists.get(i));
                                tsTaskLists.remove(tsTaskLists.get(i));
                                isExist = true;
                                break;
                            }
                        }
                        if (isExist) {
                            for (int i = 0; i < tsTaskLists.size(); i++) {
                                TSTaskList task = tsTaskLists.get(i);
                                task.setBusstatus(BaseDataConstant.BUSINESS_STATUS_XYXF_END);
                                task.setIsBack("0");
                                taskListService.updateById(task);
                                if (tsBizRemLists.size() > 1) {
                                    LambdaQueryWrapper<TSBizRemList> queryWrapper = new LambdaQueryWrapper<>();
                                    queryWrapper.eq(TSBizRemList::getBizseq, task.getBizseqid())
                                            .eq(TSBizRemList::getRemSponsorID, task.getSignuserid());
                                    TSBizRemList bizRemListDB = getOne(queryWrapper);
                                    if (bizRemListDB != null) {
                                        bizRemListDB.setBizseq("");
                                        updateById(bizRemListDB);
                                    }
                                }

                            }
                        } else {
                            throw new BusinessException("业务办理错误");
                        }

                    } else {
                        if (tsTaskLists.size() == 1 && !user.getPrimaryKey().equals(tsTaskLists.get(0).getSignuserid())) {
                            throw new BusinessException("业务已在办理中");
                        }
                    }
                }

            }
        }


        Map<String, Object> resultMap = new HashMap<>();
        //更新 异常名录移出业务表
        if (tsBizRemListModel != null && org.apache.commons.lang.StringUtils.isNotBlank(tsBizRemListModel.getBizseq())) {

            //批量，业务主体有多个
            List<TSBizRemList> tsBizRemLists = list(new LambdaQueryWrapper<TSBizRemList>().eq(TSBizRemList::getBizseq, tsBizRemListModel.getBizseq()));
            if (CollectionUtils.isEmpty(tsBizRemLists)) {
                throw new BusinessException(ResultCode.BUSINESS_LOGIC_ERROR);
            }
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            TSTwfProcessNode processNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());

            String decOrgCode = aicorgService.getRegionCodeByUser(user);
            for (TSBizRemList bizRemListModel : tsBizRemLists) {
                //下一步为审核
                if (FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST.equals(nextNodeID)) {
//                    bizRemListModel.setRemreasons(tsBizRemListModel.getRemreasons());
                    if (FlowUtil.EXPTLISTWORKFLOW_EXPTLISTENTER.equals(processNode.getCurrentnode())) {
//                        if (StringUtils.isNotBlank(tsBizRemListModel.getRemRemark())) {
//                            bizRemListModel.setRemRemark(tsBizRemListModel.getRemRemark());
//                        }
                        bizRemListModel.setRemRemark(org.apache.commons.lang.StringUtils.isNotBlank(tsBizRemListModel.getRemRemark()) ? tsBizRemListModel.getRemRemark() : org.apache.commons.lang.StringUtils.EMPTY);
                        bizRemListModel.setReconsiderationOrg(tsBizRemListModel.getReconsiderationOrg());
                        bizRemListModel.setGovernmentOrg(tsBizRemListModel.getGovernmentOrg());
                        bizRemListModel.setLitiOrg(tsBizRemListModel.getLitiOrg());
                        bizRemListModel.setRemexcpres(tsBizRemListModel.getRemexcpres());// 移出原因
                        bizRemListModel.setRemreasons(tsBizRemListModel.getRemreasons());// 作出决定的事实、理由、依据及主要内容
                        if (org.apache.commons.lang.StringUtils.isNotEmpty(tsBizRemListModel.getIsAccept())) {
                            bizRemListModel.setIsAccept(tsBizRemListModel.getIsAccept());
                        }
                        if (org.apache.commons.lang.StringUtils.isNotEmpty(tsBizRemListModel.getIsAgreeRepair())) {
                            bizRemListModel.setIsAgreeRepair(tsBizRemListModel.getIsAgreeRepair());
                        }
                        if (tsBizRemListModel.getApplicant() != null) {
                            bizRemListModel.setApplicant(tsBizRemListModel.getApplicant());
                        }
                        if ("0".equals(bizRemListModel.getAppOrPc())) {
                            bizRemListModel.setRemSponsor(user.getName());// 移出主办人
                            bizRemListModel.setRemSponsorID(user.getPrimaryKey());// 移出主办人id
                            bizRemListModel.setDecorg(decOrgCode);
                            bizRemListModel.setAreaCode(decOrgCode);
                        }
                    }
                }
            }
            if (com.chinaweal.aiccs.common.util.StringUtils.isBlank(nextPerformerids)) {
                TSTwfProcessNode processNode1 = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
                int order = WorkFlowUtil.checkNextOrder(processNode1.getCurrentnode(), nextNodeID);
                // 通过order判断为回退还是前进 >0前进
                if (order > 0) {
                    LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TSOpinion::getWorkflowid, taskListModel.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, "0")// 经办为0
                            .orderByDesc(TSOpinion::getLauptime);
                    List<TSOpinion> list = opinionService.list(wrapper);
                    if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                        return RestResult.error(ResultCode.DATA_NONE);
                    }
                    nextPerformerids = list.get(0).getHandlerid();
                    nextPerformerNames = list.get(0).getHandler();
                }
                // 回退时 获取经办人
                if (order < 0) {
                    // 获取经办人
                    LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TSOpinion::getWorkflowid, taskListModel.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, '0')
                            .orderByDesc(TSOpinion::getLauptime);
                    List<TSOpinion> list = opinionService.list(wrapper);
                    if (CollectionUtils.isEmpty(list)) {
                        return RestResult.error(ResultCode.DATA_NONE);
                    }
                    nextPerformerids = list.get(0).getHandlerid();
                    nextPerformerNames = list.get(0).getHandler();
                }
            }


            //发送
            String[] ids = com.chinaweal.aiccs.common.util.StringUtils.split(nextPerformerids, Constant.COMMA);
            String[] names = com.chinaweal.aiccs.common.util.StringUtils.split(nextPerformerNames, Constant.COMMA);
            try {

                TSTaskList tsTaskList = saveBizRemListAuditProcess(user, taskListModel, tsBizRemLists, opinionModel, nextNodeID, ids, names);
                if (FlowUtil.EXPTLISTWORKFLOW_EXPTLISTENTER.equals(nextNodeID)) {
                    LocalDateTime now = LocalDateTime.now();
                    // 回退时，所有有权限经办人都可以看到并办理
                    TSBizRemList bizRemList = tsBizRemLists.get(0);
                    if ("0".equals(bizRemList.getAppOrPc())) {// 移动端发起的业务才需要更新
                        String bizseq = bizRemList.getBizseq();
                        TSAbnList abnList = tsAbnListService.getById(bizRemList.getAbnlistid());
                        // 先获取所有有权限的人
                        // 判断主体类型
                        String permission = "";
                        if ("individual".equals(bizRemList.getType())) {
                            permission = "individualRecoverAccept";
                        } else if ("farmer".equals(bizRemList.getType())) {
                            permission = "agricultureRecoverAccept";
                        } else if ("company".equals(bizRemList.getType())) {
                            permission = "exptRemoveEnter";
                        }
                        List<AICUser> userList = SpringUtil.getBean(IGzaiccodeService.class).byPermissionListHandleUserList(bizRemList.getPripid(), permission, abnList.getDecorg(), abnList.getIntoDecorg());
                        if (userList == null || userList.isEmpty()) {
                            log.error("分派失败，权限用户列表为空,bizRemList为：{},权限为：{}，abnList为{}", bizRemList, permission, abnList);
                            throw new BusinessException("权限用户列表为空！");
                        }
                        // 将这些人的待办设置为在办，并且用同一个workflowid
                        for (AICUser aicUser : userList) {
                            if (aicUser.getPrimaryKey().equals(tsTaskList.getSignuserid())) {// 一开始的经办人，无需再设置
                                continue;
                            } else {
                                LambdaQueryWrapper<TSTaskList> wrapper = new LambdaQueryWrapper<>();
                                wrapper.eq(TSTaskList::getBizseqid, bizseq)
                                        .eq(TSTaskList::getSignuserid, aicUser.getPrimaryKey());
                                TSTaskList taskListDB = taskListService.getOne(wrapper, false);
                                if (taskListDB == null) {
                                    TSTaskList taskListNew = new TSTaskList();
                                    BeanUtils.copyProperties(tsTaskList, taskListNew);
                                    taskListNew.setTasklistid(null);
                                    //设置受理号
//                                    taskListNew.setAcceptno(aicUser.getRegionID().substring(0, Math.min(aicUser.getRegionID().length(), 6)) + uuidUtil.getCurAcceptNo());
                                    //因xr_id_maker容易被锁，临时用新的生成规则生成受理编号
                                    LocalDateTime nowLocalDateTime = LocalDateTime.now();  // 获取当前日期和时间
                                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  // 定义格式化模式
                                    String formattedDate = nowLocalDateTime.format(formatter);  // 将日期格式化为字符串
                                    String acceptno = "7" + formattedDate + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
                                    taskListNew.setAcceptno(acceptno);

                                    //设置签收人信息
                                    taskListNew.setSignuserid(aicUser.getPrimaryKey());
                                    taskListNew.setSignloginname(aicUser.getName());
                                    taskListService.save(taskListNew);
                                    log.info("回退时，经办人{}{}没有待办，重新创建待办：{}", aicUser.getName(), aicUser.getEname(), taskListNew.getTasklistid());
                                } else {
                                    taskListDB.setWorkflowid(tsTaskList.getWorkflowid());// 重设workflowid，才可回显之前意见记录
                                    taskListDB.setSendername(tsTaskList.getSendername());
                                    taskListDB.setSendertime(tsTaskList.getSendertime());
                                    taskListDB.setSenderuserid(tsTaskList.getSenderuserid());
                                    taskListDB.setSigntime(tsTaskList.getSigntime());
                                    taskListDB.setBusstatus(tsTaskList.getBusstatus());
                                    taskListDB.setLauptime(now);
                                    taskListService.updateById(taskListDB);
                                    log.info("回退时，经办人{}{}有待办，更新待办：{}", aicUser.getName(), aicUser.getEname(), taskListDB.getTasklistid());
                                }
                            }
                        }
                        // 重新设置业务表为未认领状态
                        bizRemList.setRemSponsor(null);
                        bizRemList.setRemSponsorID(null);
                        bizRemList.setLauptime(now);
                        updateById(bizRemList);
                    }
                }
                if (ids.length == 1 && com.chinaweal.aiccs.common.util.StringUtils.equals(user.getPrimaryKey(), ids[0])) {
                    resultMap.put("bizseq", tsBizRemListModel.getBizseq());
                    resultMap.put("nextNodeId", nextNodeID);
                    resultMap.put("taskListId", tasklistid);
                    resultMap.put("workFlowId", taskListModel.getWorkflowid());
                }
            } catch (Exception e) {
                log.error("移出经营异常名录审核审批出错", e);
                throw new BusinessException("移出经营异常名录审核审批出错");
            }
        }
        return RestResult.ok(resultMap);
    }

    @Override
    public RestResult<?> canProcessSmart(EBaseinfo eBaseInfo, TSTaskList taskListModel, List<TSBizRemList> bizRemListModelList) {
        TSBizRemList tsBizRemList = bizRemListModelList.get(0);
        if ("1".equals(tsBizRemList.getSpecause())) {
            // 如果异常名录列入原因编码为1，则查询企业9月30日前，是否已补报上年度年报，是则创建申请信用修复审批待办，并直接办结。
            // LocalDate now = LocalDate.now();
            LocalDate abntime = tsBizRemList.getAbntime();
//            if (now.getYear() != abntime.getYear()) {
//                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "不是本年因未填报年报列入的，不予智能办结");
//            }
            // 查询年报当年该填报的年报信息  年报列异无时间字段，会存在无法判断情况。
            List<TREntBaseInfoSplit> reportList = trEntBaseInfoSplitService.getByWrapper(trEntBaseInfoSplitService.lambdaQuery()
                            .ne(TREntBaseInfoSplit::getDstate, "2").eq(TREntBaseInfoSplit::getEntityno, tsBizRemList.getPripid()).getWrapper(),
                    abntime.getYear() - 1, false);
            if (CollectionUtils.isEmpty(reportList)) {
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "未补报年报，不予智能办结");
            }
            // 如果是个体户，已补报则直接允许智能办结
            if (StringUtils.equals(tsBizRemList.getType(), "individual")) {
                return RestResult.ok();
            }
            // 校验填报时间
            TREntBaseInfoSplit report = reportList.get(0);
            if (report.getRegistdate() == null || report.getRegistdate()
                    .isAfter(LocalDateTime.of(Integer.parseInt(report.getReportyear()) + 1, Month.DECEMBER, 30, 23, 59, 59)))
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "非12月30日前补报，不予智能办结");

            // 返回应该执行智能办结
            return RestResult.ok();
        } else if ("4".equals(tsBizRemList.getSpecause())) {
            // 如果异常名录列入原因编码为4（登记住所查无）,且在FORGIVEPRUDENTOBJECT表中查不到企业名单，
            // 且有地址变更登记记录，且企业登记的住所信息中，不包含“集群”两字，则创建申请信用修复审批待办，并直接办结
            if (eBaseInfo == null) {
                return RestResult.error(ResultCode.PARAM_IS_BLANK, "未传入市场主体信息，缺少判断依据，不予智能办结");
            }
            // 1、"集群"注册地址判断
            if (StringUtils.contains(eBaseInfo.getDom(), "集群")) {
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "集群注册地址，不予智能办结");
            }
            // 2、"审慎"名单判断  -- 去除不调用双随机的 yuanjw 2025-3-24
            /*Integer exists = forgiveprudentObjectService.lambdaQuery().eq(ForgiveprudentObject::getEntno, eBaseInfo.getPripid()).count();
            if (exists > 0) {
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "企业在审慎名单中，不予智能办结");
            }*/
            //2.1 新增番禺的审慎监管限制，1-经济发展的重点企业 2-涉嫌逃避监管的企业 3-有多次被列入经营异常名录记录企业 4-现场核查被投诉企业
            Integer exists = iTPyBlacklistService.lambdaQuery().eq(TPyBlacklist::getUniscid, eBaseInfo.getUniscid()).ne(TPyBlacklist::getTagType, "1").count();
            if (exists > 0)
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "企业在审慎监管名单中，不予智能办结");

            // 3、校验是否之前发生过地址列异
            exists = tsAbnListService.lambdaQuery().eq(TSAbnList::getPripid, eBaseInfo.getPripid())
                    .eq(TSAbnList::getSpecause, "4").ne(TSAbnList::getAbnlistid, tsBizRemList.getAbnlistid()).count();
            if (exists > 0) {
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "企业之前发生过因登记地址原因而列异，不予智能办结");
            }
            // 4、查询是否有列入后的变更记录
            if (BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_RESTORE.equals(taskListModel.getBustype())) {
                // 个体
                exists = eGtAlterRecoderService.lambdaQuery().ge(EGtAlterRecoder::getAltdate, tsBizRemList.getAbntime())
                        .eq(EGtAlterRecoder::getPripid, eBaseInfo.getPripid()).eq(EGtAlterRecoder::getAltitem, "02").count();
            } else {
                // 企业农专
                exists = eAlterRecoderService.lambdaQuery().ge(EAlterRecoder::getAltdate, tsBizRemList.getAbntime())
                        .eq(EAlterRecoder::getPripid, eBaseInfo.getPripid()).eq(EAlterRecoder::getAltitem, "02").count();
            }
            if (exists < 1) {
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "未查询到符合条件的市场主体地址变更记录，不予智能办结");
            }
            // 返回应该执行智能办结
            return RestResult.ok();
        }
        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "未匹配到智能办结条件，不予智能办结");
    }

    @Override
    public RestResult<?> processSmart(EBaseinfo eBaseInfo, TSTaskList taskListModel, List<TSBizRemList> bizRemListModelList, String decorg, String applicant) {
        // 创建经办
        AICUser smartProcessUser = findSmartProcessUser(decorg);
        taskListModel = saveAbnListStart(smartProcessUser, taskListModel, bizRemListModelList);
        taskListModel.setIsSmartProcessing("1");
        if (StringUtils.isNotBlank(applicant)) {
            taskListModel.setSendername(applicant);
        }
        taskListService.updateById(taskListModel);
        // 执行审查
        for (TSBizRemList each : bizRemListModelList) {
            // 生成文书
            String writType = "individual".equals(each.getType()) ? WorkNoUtil.WORKNOTYPE_59 : WorkNoUtil.WORKNOTYPE_56;
            Tswrittemplate writs = tswrittemplateService.generateWrits(writType, each.getBizseq(), each.getType(), smartProcessUser);
            if (writs.getBizseq() == null) {
                writs.setBizseq(each.getBizseq()).setIsTemplate("0").setWritsType(writType).setTemplateId(StringUtils.getUUID())
                        .setCreateUserId(smartProcessUser.getPrimaryKey()).setCreateTime(LocalDateTime.now());
                tswrittemplateService.save(writs);
            }
            each.setIsAccept("1");
            each.setIsAgreeRepair("1");
            if ("1".equals(each.getSpecause())) {
                each.setRemexcpres("1");
            } else if ("3".equals(each.getSpecause())) {
                each.setRemexcpres("3");
            }

            TSOpinion opinion = new TSOpinion();
            opinion.setBizseq(each.getBizseq());
            opinion.setWorkflowid(taskListModel.getWorkflowid());
            opinion.setOpiniontype("1");
            opinion.setOpinioncontent("拟同意");
            opinion.setHandlerid(smartProcessUser.getPrimaryKey());
            opinion.setHandler(smartProcessUser.getEname());
            bizRemoveNext(smartProcessUser, each, opinion, taskListModel.getTasklistid(),
                    smartProcessUser.getPrimaryKey(), smartProcessUser.getName(), "handleExptlist", null);
        }
        // 执行审查
        for (TSBizRemList each : bizRemListModelList) {
            if ("1".equals(each.getSpecause())) {
                each.setRemexcpres("1");
            } else if ("3".equals(each.getSpecause())) {
                each.setRemexcpres("3");
            }
            TSOpinion opinion = new TSOpinion();
            opinion.setBizseq(each.getBizseq());
            opinion.setWorkflowid(taskListModel.getWorkflowid());
            opinion.setOpiniontype("2");
            opinion.setOpinioncontent("同意");
            opinion.setHandlerid(smartProcessUser.getPrimaryKey());
            opinion.setHandler(smartProcessUser.getEname());
            bizRemoveNext(smartProcessUser, each, opinion, taskListModel.getTasklistid(),
                    smartProcessUser.getPrimaryKey(), smartProcessUser.getName(), "approvelist", null);
        }
        // 执行办结
        for (TSBizRemList each : bizRemListModelList) {
            if ("1".equals(each.getSpecause())) {
                each.setRemexcpres("1");
            } else if ("3".equals(each.getSpecause())) {
                each.setRemexcpres("3");
            }
            TSOpinion opinion = new TSOpinion();
            opinion.setBizseq(each.getBizseq());
            opinion.setWorkflowid(taskListModel.getWorkflowid());
            opinion.setOpiniontype("3");
            opinion.setOpinioncontent("同意");
            opinion.setHandlerid(smartProcessUser.getPrimaryKey());
            opinion.setHandler(smartProcessUser.getEname());
            bizRemoveNext(smartProcessUser, each, opinion, taskListModel.getTasklistid(),
                    smartProcessUser.getPrimaryKey(), smartProcessUser.getName(), "endExptlist", null);
        }

        return RestResult.ok();
    }


    /**
     * 查询机构下的智能办理账号
     *
     * @param aicId 机构编码
     * @return 办理账号
     * @author lroyia
     * @since 2025年2月25日19:29:16
     */
    private AICUser findSmartProcessUser(String aicId) {
        if (aicId == null) {
            aicId = "150000";
        }
        if (aicId.length() > 6) {
            aicId = aicId.substring(0, 6);
        }
        String username = BaseDataConstant.SMART_PROCESS_USER_MAP.get(aicId);
        if (username == null) {
            aicId = "150000";
            username = BaseDataConstant.SMART_PROCESS_USER_MAP.get(aicId);
        }
        return aicorgService.queryUserByUserName(username);
    }
}
