package com.chinaweal.aiccs.aiccs.seriousillegal.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.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.TSAttachmentMapper;
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.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.entity.TSBizSerIllegalRem;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSForIllOperatingList;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.mapper.TSBizSerIllegalRemMapper;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalRemService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSForIllOperatingListService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.DeadlinestasService;
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.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.org.entity.OrgUnits;
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 com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
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 org.springframework.ui.Model;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
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-26
 */
@Slf4j
@Service
public class TSBizSerIllegalRemServiceImpl extends BaseServiceImpl<TSBizSerIllegalRemMapper, TSBizSerIllegalRem> implements TSBizSerIllegalRemService {

    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSSerIllegalListService tsSerIllegalListService;
    @Autowired
    private TSWorkNoService workNoService;
    @Autowired
    private TSWritService tsWritService;
    @Lazy
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TSForIllOperatingListService tsForIllOperatingListService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TswrittemplateService tswrittemplateService;
    @Autowired
    private CreatePdfService createPdfService;
    @Autowired
    private DeadlinestasService deadlinestasService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Lazy
    @Autowired
    private IGzaiccodeService gzaiccodeService;
    @Autowired
    private TSTwfProcessNodeService tsTwfProcessNodeService;
    @Resource
    private TSOpinionMapper tsOpinionMapper;
    @Resource
    private TSAttachmentMapper tsAttachmentMapper;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSOpinionService opinionService;
    @Resource
    private UuidUtil uuidUtil;

    @Override
    public List<TSBizSerIllegalRem> selectBRMserIllegalList(TSBizSerIllegalRem tsBizSerIllegalRemModel) {
        return baseMapper.selectBRMserIllegalList(tsBizSerIllegalRemModel);
    }

    @Override
    public List<TSBizSerIllegalRem> queryBRMserIllegalList(TSBizSerIllegalRem tsBizSerIllegalRemModel) {
        return baseMapper.queryBRMserIllegalList(tsBizSerIllegalRemModel);
    }

    @Override
    public TSTaskList saveSerListStart(AICUser user, TSTaskList taskListModel, List<TSBizSerIllegalRem> bizRemList) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            for (TSBizSerIllegalRem tsBizSerIllegalRemModel : bizRemList) {
                tsBizSerIllegalRemModel.setRemSponsorIllegal(user.getEname()); // 流程启动人(主办人手机号)移出严重违法失信
                tsBizSerIllegalRemModel.setStatus("9"); //流程启动把状态设置为 "受理中"
                saveOrUpdate(tsBizSerIllegalRemModel);
            }
            String definedname = FlowUtil.SERILLEGALWORKFLOW;//严重违法失信名单 流程模板
            //新待办
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, user);
            //开始工作流
            taskListService.startWorkFlow(taskListModel, user, definedname);
        }
        return taskListModel;
    }

    @Override
    public TSTaskList saveSerListStartApp(AICUser user, List<String> userIdList, TSTaskList taskListModel, List<TSBizSerIllegalRem> bizRemList) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            for (TSBizSerIllegalRem tsBizSerIllegalRemModel : bizRemList) {
                tsBizSerIllegalRemModel.setRemSponsorIllegal(user.getEname()); // 流程启动人(主办人手机号)移出严重违法失信
                tsBizSerIllegalRemModel.setStatus("9"); //流程启动把状态设置为 "受理中"
                saveOrUpdate(tsBizSerIllegalRemModel);
            }
            String definedName = FlowUtil.SERILLEGALWORKFLOW;//严重违法失信名单 流程模板
            //新待办
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel);
            //开始工作流
            taskListService.startWorkFlow(taskListModel, userIdList, user.getRegionID().substring(0, 6), definedName);
        }
        return taskListModel;
    }

    @Override
    public List<TSBizSerIllegalRem> selectbizRembizseq(String bizseqid) {
        return list(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq, bizseqid));
    }

    @Override
    public TSTaskList saveBizRemListAuditProcess(AICUser user, TSTaskList taskListModel, List<TSBizSerIllegalRem> tsBizSerIllegalRemModels, TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames, boolean isReturn) {
        taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
        String decOrgCode = aicorgService.getRegionCodeByUser(user);
        for (TSBizSerIllegalRem bizRem : tsBizSerIllegalRemModels) {
            if (FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) {//下一步审核
                deadlinestasService.update(taskListModel.getWorkflowid(), LocalDate.now(), null, null, isReturn);
                if ("0".equals(bizRem.getIsAgreeRepair())) {
                    bizRem.setStatus("3"); //不予修复
                } else {
                    bizRem.setStatus("1"); // 审批流程中把状态设置成 "审批中"
                }
                saveOrUpdate(bizRem);
            }
            if (FlowUtil.SERILLEGALWORKFLOW_APPORSERILLEGALENTER.equals(nextNodeID)) {//下一步审批
                deadlinestasService.update(taskListModel.getWorkflowid(), null, LocalDate.now(), null, isReturn);

            }

            if (FlowUtil.SERILLEGALWORKFLOW_ENDSERILLEGAL.equals(nextNodeID)) {//完结时
                TSSerIllegalList serModel = tsSerIllegalListService.getById(bizRem.getIllegalListID());
                TSSerIllegalList tsSerIllegalListModel = new TSSerIllegalList();
                tsSerIllegalListModel.setIllegallistid(serModel.getIllegallistid());

                if ("03".equals(bizRem.getRemType())) {//信用修复环节把企业回退到经营异常名录
                    //文书号暂无分别对应规则 三类主体一样
                    LocalDateTime now = LocalDateTime.now();
                    TSWrit tsWritModel = new TSWrit();
                    String tswritId = UUID.randomUUID().toString();
                    tsWritModel.setWritsid(tswritId);
                    String workNoType = "";
                    String path = "";
                    if ("0".equals(bizRem.getIsAgreeRepair())) {
                        workNoType = WorkNoUtil.WORKNOTYPE_52; //严重违法-不予信用修复决定书
                        path = "static" + File.separator + "template" + File.separator + "noRepairDec.docx";
                        bizRem.setHandleStatus("4");
                    } else if ("1".equals(bizRem.getIsAgreeRepair())) {
                        workNoType = WorkNoUtil.WORKNOTYPE_53; //严重违法-准予信用修复决定书
                        path = "static" + File.separator + "template" + File.separator + "repairDec.docx";
                        bizRem.setHandleStatus("3");
                        tsSerIllegalListModel.setRemexcpres(bizRem.getRemExcpRes());
                        Map<String, TRBaseCode> remCodeMap = baseCodeService.getBaseCodeMapFormCache("CD74");
                        TRBaseCode remCode = remCodeMap.get(bizRem.getRemExcpRes());
                        if (remCode != null) {
                            tsSerIllegalListModel.setLostcreditexplainrem(remCode.getName());// 移出原因对应中文
                        } else {
                            throw new BusinessException("严重违法信用修复移出事由中文名称为空！");
                        }
                        tsSerIllegalListModel.setRemSponsorIllegal(bizRem.getRemSponsorIllegal()); //移出严重违法失信主办人
                        tsSerIllegalListModel.setRemdate(LocalDate.now());
                        tsSerIllegalListModel.setOperationStatus("1");//（0列入，1已修复，2移出, 3撤销）
                        if (bizRem.getDecOrg() == null || "".equals(bizRem.getDecOrg())) {
                            throw new BusinessException("严重违法信用修复移出做出决定机关为空！");
                        }
                        tsSerIllegalListModel.setRemdecorg(bizRem.getDecOrg());
                        String decOrgName = gzaiccodeService.getNameByCode(bizRem.getDecOrg());
                        tsSerIllegalListModel.setRemdecorgCn(decOrgName);// 移出决定机关中文
                        tsSerIllegalListModel.setLauptime(now);
                    }
                    LambdaQueryWrapper<Tswrittemplate> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(Tswrittemplate::getBizseq, bizRem.getBizSeq())
                            .eq(Tswrittemplate::getIsTemplate, "0")
                            .eq(Tswrittemplate::getWritsType, workNoType);
                    Tswrittemplate tswrittemplate = tswrittemplateService.getOne(wrapper);
                    tsWritModel.setBizseq(bizRem.getBizSeq());
                    //获取用户所在部门辖区码值
                    tsWritModel.setAreaCode(decOrgCode);

                    tsWritModel.setWritsno(workNoService.getOperatingWrirsno(workNoType, tsWritModel.getAreaCode())); //当前用户的regionID
                    tsWritModel.setWritstype(workNoType);
                    tsWritModel.setPripid(bizRem.getPriPID());
                    tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
                    tsWritModel.setCreatetime(now);
                    tsWritModel.setLauptime(now);
                    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.toLocalDate(), "yyyy年MM月dd日");
                    map.put("approveDate", approveDate);

                    String pdfPath = createPdfService.createPdfWithHtmlTemplate(bizRem.getBizSeq(), path, map);
                    if (StringUtils.isNotBlank(pdfPath)) {
                        tsWritModel.setPath(pdfPath);
                    }
                    tsWritService.save(tsWritModel);
                    tsSerIllegalListModel.setRemwritid(tswritId);
                    if ("0".equals(bizRem.getAppOrPc())) {
                        if ("0".equals(bizRem.getIsAgreeRepair())) { // 移动端才需要
                            workNoType = WorkNoUtil.WORKNOTYPE_54; //严重违法-不予信用修复决定书--无印章
                            String path1 = "static" + File.separator + "template" + File.separator + "noRepairDecNoSeal.docx";
                            map.put("htmlContent", tsWritModel.getContent());
                            String pdfPath1 = createPdfService.createPdfWithHtmlTemplate(bizRem.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(bizRem.getIsAgreeRepair())) {
                            workNoType = WorkNoUtil.WORKNOTYPE_61; //严重违法-准予信用修复决定书--无印章
                            String path1 = "static" + File.separator + "template" + File.separator + "repairDecNoSeal.docx";
                            map.put("htmlContent", tsWritModel.getContent());
                            String pdfPath1 = createPdfService.createPdfWithHtmlTemplate(bizRem.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 {
                    TSWrit tsWritModel = new TSWrit();
                    String tswritId = UUID.randomUUID().toString();
                    tsWritModel.setWritsid(tswritId);
                    String writsno = workNoService.getOperatingWrirsno(WorkNoUtil.WORKNOTYPE_25, user.getRegionID());//移出 决定书文号
                    tsWritModel.setBizseq(bizRem.getBizSeq());
                    tsWritModel.setWritsno(writsno);
                    tsWritModel.setWritstype(WorkNoUtil.WORKNOTYPE_25);
                    tsWritModel.setPripid(bizRem.getPriPID());
                    tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(WorkNoUtil.WORKNOTYPE_25));
                    tsWritModel.setCreatetime(LocalDateTime.now());
                    tsSerIllegalListModel.setRemwritid(tswritId);
                    tsWritService.save(tsWritModel);
                }
                tsSerIllegalListService.saveOrUpdate(tsSerIllegalListModel);

                bizRem.setApprovalDate(LocalDate.now()); //核准时间
                if (!"3".equals(bizRem.getStatus())) {
                    bizRem.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
                }
                updateById(bizRem);
                deadlinestasService.update(taskListModel.getWorkflowid(), null, null, LocalDate.now(), isReturn);

            }
            //  审批中选择不同意> 结束流程
            if (FlowUtil.SERILLEGALWORKFLOW_OVERFINISH.equals(nextNodeID)) {
                bizRem.setApprovalDate(LocalDate.now()); //核准时间
                bizRem.setHandleStatus("5");// 回退至申请人
                bizRem.setStatus("3");// 9 受理中、1 审批中、2 已通过、3 不通过
                updateById(bizRem);
            }
            if (FlowUtil.SERILLEGALWORKFLOW_OVERSERILLEGAL.equals(nextNodeID)) {
                bizRem.setApprovalDate(LocalDate.now()); //核准时间
                bizRem.setStatus("3");// 9 受理中、1 审批中、2 已通过、3 不通过
                updateById(bizRem);
            }

            if (FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) {//依申请移出 生成申请回执文号
                if (!"03".equals(bizRem.getRemType())) {
                    TSWrit tsWritModel = new TSWrit();
                    tsWritModel.setWritsid(UUID.randomUUID().toString());
                    String writsno = workNoService.getOperatingWrirsno(WorkNoUtil.WORKNOTYPE_26, user.getRegionID());//移出严重违法失信名单 受理申请回执单

                    tsWritModel.setBizseq(bizRem.getBizSeq());
                    tsWritModel.setWritsno(writsno);
                    tsWritModel.setWritstype(WorkNoUtil.WORKNOTYPE_26);
                    tsWritModel.setPripid(bizRem.getPriPID());
                    tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(WorkNoUtil.WORKNOTYPE_26));
                    tsWritModel.setCreatetime(LocalDateTime.now());
                    tsWritService.save(tsWritModel);
                }
            }
        }
        return taskListModel;
    }

    @Override
    public IPage<TSBizSerIllegalRem> selectbizRemlist(int rows, int page, TSBizSerIllegalRem tsBizSerIllegalRemModel) {
        return baseMapper.selectbizRemByPagelist(new Page<>(page, rows), tsBizSerIllegalRemModel);
    }

    @Override
    public TSTaskList saveSerListStartApp(TSTaskList taskListModel, List<TSBizSerIllegalRem> bizRemList) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            for (TSBizSerIllegalRem tsBizSerIllegalRemModel : bizRemList) {
                tsBizSerIllegalRemModel.setStatus("9"); //流程启动把状态设置为 "受理中"
                saveOrUpdate(tsBizSerIllegalRemModel);
            }
            String definedname = FlowUtil.SERILLEGALWORKFLOW;//严重违法失信名单 流程模板
            //新待办
            taskListModel = HandleWorkFlowUtil.createTaskListApp(taskListModel);
            //开始工作流
            taskListService.startWorkFlowApp(taskListModel,definedname);
        }
        return taskListModel;
    }

    @Override
    public TSTaskList saveBizRemListAuditProcessApp(TSTaskList taskListModel, List<TSBizSerIllegalRem> tsBizSerIllegalRemModels, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames) {
        for (TSBizSerIllegalRem bizRem : tsBizSerIllegalRemModels) {
            if (FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) {//审批
                bizRem.setStatus("1"); // 审批流程中把状态设置成 "审批中"
                saveOrUpdate(bizRem);
            }

            if (FlowUtil.SERILLEGALWORKFLOW_ENDSERILLEGAL.equals(nextNodeID)) {//完结时
                TSSerIllegalList serModel = tsSerIllegalListService.getById(bizRem.getIllegalListID());
                TSSerIllegalList tsSerIllegalListModel = new TSSerIllegalList();
                tsSerIllegalListModel.setIllegallistid(serModel.getIllegallistid());
                tsSerIllegalListModel.setRemexcpres(bizRem.getRemExcpRes());
                tsSerIllegalListModel.setLostcreditexplainrem(bizRem.getLostCreditExplainrem());
                tsSerIllegalListModel.setReconsiderationOrg(bizRem.getReconsiderationOrg());
                tsSerIllegalListModel.setGovernmentOrg(bizRem.getGovernmentOrg());
                tsSerIllegalListModel.setLitiOrg(bizRem.getLitiOrg());
                tsSerIllegalListModel.setRemSponsorIllegal(bizRem.getRemSponsorIllegal()); //移出严重违法失信主办人
                tsSerIllegalListModel.setRemdate(LocalDate.now());
                tsSerIllegalListService.saveOrUpdate(tsSerIllegalListModel);

                if("03".equals(bizRem.getStatus())){//信用修复环节把企业回退到经营异常名录
                    //获取主体信息
                    EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, bizRem.getPriPID()));
                    TSForIllOperatingList tsForIllOperating = tsForIllOperatingListService.getOne(new LambdaQueryWrapper<TSForIllOperatingList>().eq(TSForIllOperatingList::getPripid, bizRem.getPriPID())
                            .eq(TSForIllOperatingList::getOperationStatus,'0'));
                    TSAbnList tsAbnList = new TSAbnList();
                    tsAbnList.setAbnlistid(UUID.randomUUID().toString());
                    tsAbnList.setPripid(bizRem.getPriPID());
                    tsAbnList.setRegno(bizRem.getRegNO());
                    tsAbnList.setEntname(bizRem.getEntName());
                    if(eBaseinfo != null){
                        tsAbnList.setUniscid(eBaseinfo.getUniscid());
                        tsAbnList.setEnttype(eBaseinfo.getEnttype());
                    }
                    if (tsForIllOperating != null){
                        tsAbnList.setSpecause(tsForIllOperating.getSpeCause());
                        tsAbnList.setSpecauseCn(tsForIllOperating.getSpeCauseStr());
                        tsAbnList.setSpereasons(tsForIllOperating.getSpeReasons());
                    }
                    tsAbnList.setAbntime(LocalDate.now());
                    tsAbnList.setAreaCode(bizRem.getAreaCode());
                    tsAbnList.setLauptime(LocalDateTime.now());
                    tsAbnList.setOperatestatus("1");
                    tsAbnList.setGovernmentOrg(bizRem.getGovernmentOrg());
                    tsAbnListService.save(tsAbnList);

                }

                bizRem.setApprovalDate(LocalDate.now()); //核准时间
                bizRem.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
                updateById(bizRem);

                TSWrit tsWritModel = new TSWrit();
                tsWritModel.setWritsid(UUID.randomUUID().toString());
                tsWritModel.setBizseq(bizRem.getBizSeq());
                tsWritModel.setWritstype(WorkNoUtil.WORKNOTYPE_25);
                tsWritModel.setPripid(bizRem.getPriPID());
                tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(WorkNoUtil.WORKNOTYPE_25));
                tsWritModel.setCreatetime(LocalDateTime.now());
                tsWritService.save(tsWritModel);
            }
            //  审批中选择不同意> 结束流程
            if (FlowUtil.SERILLEGALWORKFLOW_OVERSERILLEGAL.equals(nextNodeID)) {
                bizRem.setApprovalDate(LocalDate.now()); //核准时间
                bizRem.setStatus("3");// 9 受理中、1 审批中、2 已通过、3 不通过
                updateById(bizRem);
            }

            if (FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) {//依申请移出 生成申请回执文号
                TSWrit tsWritModel = new TSWrit();
                tsWritModel.setWritsid(UUID.randomUUID().toString());
                tsWritModel.setBizseq(bizRem.getBizSeq());
                tsWritModel.setWritstype(WorkNoUtil.WORKNOTYPE_26);
                tsWritModel.setPripid(bizRem.getPriPID());
                tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(WorkNoUtil.WORKNOTYPE_26));
                tsWritModel.setCreatetime(LocalDateTime.now());
                tsWritService.save(tsWritModel);
            }
        }
        taskListService.updateWorkFlowApp(taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
        return taskListModel;
    }

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

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

    @Override
    public TSBizSerIllegalRem getOneByBizseq(String bizseq) {
        LambdaQueryWrapper<TSBizSerIllegalRem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSBizSerIllegalRem::getBizSeq,bizseq);
        wrapper.eq(TSBizSerIllegalRem::getHandleStatus,"1");
        return getOne(wrapper);
    }

    @Override
    public void cancelBusiness(String bizseq) {
        TSBizSerIllegalRem tsBizSerIllegalRem = getOne(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq,bizseq)
        .eq(TSBizSerIllegalRem::getHandleStatus,"2"));
        tsBizSerIllegalRem.setStatus("3");
        tsBizSerIllegalRem.setHandleStatus("5");
        tsBizSerIllegalRem.setLauptime(LocalDateTime.now());
        updateById(tsBizSerIllegalRem);
        TSTaskList taskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid,bizseq)
                .eq(TSTaskList::getBusstatus,"5"));
        List<TSTwfProcessNode> tsTwfProcessNodes = tsTwfProcessNodeService.queryByPROCESSIDAndCURRENTNODE(taskList.getWorkflowid(),FlowUtil.SERILLEGALWORKFLOW_SERILLEGALENTER);
        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.SERILLEGALWORKFLOW_OVERFINISH, ids, names);
    }

    @Override
    public RestResult<?> queryHistorgBizRemInfo(String SAPPROVECODE) {
        Map<String,Object> resultMap = new HashMap<>();
        TSBizSerIllegalRem tsBizSerIllegalRem = baseMapper.queryHistorgBizRemInfo(SAPPROVECODE);
        if (StringUtils.isNotBlank(tsBizSerIllegalRem.getIllegalListID())) {
            TSSerIllegalList tsSerIllegalList = tsSerIllegalListService.getById(tsBizSerIllegalRem.getIllegalListID());
            if (tsSerIllegalList != null && StringUtils.isBlank(tsSerIllegalList.getDecorgCn())) {
                OrgUnits orgUnits = aicorgService.queryByOrgNumber(tsSerIllegalList.getDecorg());
                if (orgUnits != null) {
                    tsSerIllegalList.setDecorgCn(orgUnits.getOrgUnitName());
                }
            }
            resultMap.put("tsSerIllegalList", tsSerIllegalList);
        }
        resultMap.put("tsBizSerIllegalRem", tsBizSerIllegalRem);
        List<TSOpinion> tsOpinions = tsOpinionMapper.queryOldSerillegaOpninion(SAPPROVECODE);
        resultMap.put("tsOpinions", tsOpinions);
        List<TSAttachment> tsAttachments = tsAttachmentMapper.queryFileByHistory(SAPPROVECODE);
        resultMap.put("tsAttachments", tsAttachments);
        String content = baseMapper.querynoticecontent(SAPPROVECODE);
        resultMap.put("content", content);
        return RestResult.ok(resultMap);
    }

    @Override
    public RestResult<?> serIllegalNext(HttpServletRequest request, Model model, TSBizSerIllegalRem tsBizSerIllegalRemModel, TSOpinion opinionModel, String tasklistid,
                                        String nextPerformerids, String nextPerformerNames, String nextNodeID) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        if ("handleSerIllegal".equals(nextNodeID) || "overFinish".equals(nextNodeID)) {
            if (tsBizSerIllegalRemModel != null && StringUtils.isNotBlank(tsBizSerIllegalRemModel.getBizSeq())) {
                //更新其他人待办状态
                LambdaQueryWrapper<TSTaskList> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TSTaskList::getBizseqid, tsBizSerIllegalRemModel.getBizSeq())
                        .ne(TSTaskList::getBusstatus, BaseDataConstant.BUSINESS_STATUS_XYXF_END);
                List<TSTaskList> tsTaskLists = taskListService.list(wrapper);
                List<TSBizSerIllegalRem> tsBizSerIllegalRemModels = this.selectbizRembizseq(tsBizSerIllegalRemModel.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 (tsBizSerIllegalRemModels.size() > 1) {
                                    AICUser user1 = orgUM.findUserByPrimaryKey(task.getSignuserid());

                                    LambdaQueryWrapper<TSBizSerIllegalRem> queryWrapper = new LambdaQueryWrapper<>();
                                    queryWrapper.eq(TSBizSerIllegalRem::getBizSeq, task.getBizseqid())
                                            .eq(TSBizSerIllegalRem::getRemSponsorIllegal, user1.getEname());
                                    TSBizSerIllegalRem serIllegalRemDB = this.getOne(queryWrapper);
                                    if (serIllegalRemDB != null) {
                                        serIllegalRemDB.setBizSeq("");
                                        this.updateById(serIllegalRemDB);
                                    }
                                }

                            }
                        } 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 (StringUtils.isNotBlank(tsBizSerIllegalRemModel.getBizSeq())) {
            List<TSBizSerIllegalRem> tsBizSerIllegalRemModels = this.selectbizRembizseq(tsBizSerIllegalRemModel.getBizSeq());
            if (CollectionUtils.isEmpty(tsBizSerIllegalRemModels)) {
                throw new BusinessException(ResultCode.BUSINESS_LOGIC_ERROR);
            }
            for (TSBizSerIllegalRem bizSerIllegalRemModel : tsBizSerIllegalRemModels) {
                if (FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) {
                    bizSerIllegalRemModel.setRemExcpRes(tsBizSerIllegalRemModel.getRemExcpRes());
                    bizSerIllegalRemModel.setLostCreditExplainrem(StringUtils.isNotBlank(tsBizSerIllegalRemModel.getLostCreditExplainrem()) ? tsBizSerIllegalRemModel.getLostCreditExplainrem().trim() : StringUtils.EMPTY);
                    bizSerIllegalRemModel.setReconsiderationOrg(tsBizSerIllegalRemModel.getReconsiderationOrg()); // 行政复议机关
                    bizSerIllegalRemModel.setGovernmentOrg(tsBizSerIllegalRemModel.getGovernmentOrg()); // 人民政府
                    bizSerIllegalRemModel.setLitiOrg(tsBizSerIllegalRemModel.getLitiOrg()); // 讼诉机关
                    bizSerIllegalRemModel.setApplyRemRea(tsBizSerIllegalRemModel.getApplyRemRea());
                    if (StringUtils.isNotEmpty(tsBizSerIllegalRemModel.getIsAccept())) {
                        bizSerIllegalRemModel.setIsAccept(tsBizSerIllegalRemModel.getIsAccept());
                    }
                    if (StringUtils.isNotEmpty(tsBizSerIllegalRemModel.getIsAgreeRepair())) {
                        bizSerIllegalRemModel.setIsAgreeRepair(tsBizSerIllegalRemModel.getIsAgreeRepair());
                    }
                    if (StringUtils.isNotEmpty(tsBizSerIllegalRemModel.getRemark())) {
                        bizSerIllegalRemModel.setRemark(tsBizSerIllegalRemModel.getRemark());
                    }
                    if (StringUtils.isNotEmpty(tsBizSerIllegalRemModel.getApplicant())) {
                        bizSerIllegalRemModel.setApplicant(tsBizSerIllegalRemModel.getApplicant());
                    }
                    if ("0".equals(bizSerIllegalRemModel.getAppOrPc())) {
                        bizSerIllegalRemModel.setRemSponsorIllegal(user.getEname());// 移出主办人(账号)
                    }
                }
            }
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            boolean isReturn = false;
            if (StringUtils.isBlank(nextPerformerids)) {
                TSTwfProcessNode processNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
                int order = WorkFlowUtil.checkNextOrder(processNode.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) {
                    isReturn = true;
                    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, ",");
            String[] names = StringUtils.split(nextPerformerNames, ",");
            resultMap.put("tasklistid", tasklistid);
            TSTaskList tsTaskList = this.saveBizRemListAuditProcess(user, taskListModel, tsBizSerIllegalRemModels, opinionModel, nextNodeID, ids, names, isReturn);
            if (FlowUtil.SERILLEGALWORKFLOW_SERILLEGALENTER.equals(nextNodeID)) {
                LocalDateTime now = LocalDateTime.now();
                // 回退时，所有有权限经办人都可以看到并办理
                TSBizSerIllegalRem tsBizSerIllegalRem = tsBizSerIllegalRemModels.get(0);
                if ("0".equals(tsBizSerIllegalRem.getAppOrPc())) {// 移动端发起的业务才需要更新
                    String bizseq = tsBizSerIllegalRem.getBizSeq();
                    TSSerIllegalList illegalList = tsSerIllegalListService.getById(tsBizSerIllegalRem.getIllegalListID());
                    // 先获取所有有权限的人
                    List<AICUser> userList = gzaiccodeService.byPermissionListHandleUserList(tsBizSerIllegalRem.getPriPID(), "illegalRemoveAccept", illegalList.getDecorg(), illegalList.getDecorgCn());
                    if (userList == null || userList.isEmpty()) {
                        log.error("分派失败，权限用户列表为空,illegalList为：{},权限为：{}", illegalList, "illegalRemoveAccept");
                        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());
                            }
                        }
                    }
                }
            }
            if (ids.length == 1 && StringUtils.equals(user.getPrimaryKey(), ids[0])) {
                resultMap.put("bizseq", tsBizSerIllegalRemModel.getBizSeq());
                if (FlowUtil.SERILLEGALWORKFLOW_ENDSERILLEGAL.equals(nextNodeID)) {
                    resultMap.put("workflowid", taskListModel.getWorkflowid());
                } else if ("01".equals(tsBizSerIllegalRemModel.getRemType())
                        && FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) {
                    resultMap.put("bizseq", tsBizSerIllegalRemModel.getBizSeq());
                    resultMap.put("flag", "applyReceipt");
                }
            } else if ("01".equals(tsBizSerIllegalRemModel.getRemType())
                    && FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) {
                resultMap.put("bizseq", tsBizSerIllegalRemModel.getBizSeq());
                resultMap.put("flag", "applyReceipt");

            }
        }
        return RestResult.ok(resultMap);
    }
}
