package com.chinaweal.aiccs.aiccs.seriousillegal.controller;

import com.alibaba.fastjson.JSONObject;
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.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
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.entity.dto.TaskListUnionDto;
import com.chinaweal.aiccs.aiccs.business.rules.model.SequenceFlowModel;
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.claim.entity.TSEntBase;
import com.chinaweal.aiccs.aiccs.claim.entity.TSEntBaseAddr;
import com.chinaweal.aiccs.aiccs.claim.service.TSEntBaseAddrService;
import com.chinaweal.aiccs.aiccs.claim.service.TSEntBaseService;
import com.chinaweal.aiccs.aiccs.entbase.entity.TREntBase;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntBaseService;
import com.chinaweal.aiccs.aiccs.query.entity.TSEntBaseQuery;
import com.chinaweal.aiccs.aiccs.query.service.TSEntBaseQueryService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.*;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSForIllOperatingBnService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSForIllOperatingListService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.ExcelUtil;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.WorkFlowUtil;
import com.chinaweal.aiccs.org.entity.OrgUnits;
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.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import com.chinaweal.youfool.framework.springboot.util.DateTimeUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/bizSerIllegal")
public class BizSerIllegalController extends BaseController {

    @Autowired
    private TSBizSerIllegalService tsBizSerIllegalService;
    @Autowired
    private TSSerIllegalListService tsSerIllegalListService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private TSEntBaseService tsEntBaseService;
    @Autowired
    private TSEntBaseAddrService tsEntBaseAddrService;
    @Autowired
    private TSBizDissentService tsBizDissentService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private TSBizAbnRevokeService tsbizAbnRevokeService;
    @Autowired
    private TREntBaseService trEntBaseService;
    @Autowired
    private TSEntBaseQueryService entBaseQueryService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TSForIllOperatingBnService tsForIllOperatingBnService;
    @Autowired
    private IGzaiccodeService iGzaiccodeService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TSForIllOperatingListService tsForIllOperatingListService;
    @Autowired
    private TSTwfProcessNodeService tsTwfProcessNodeService;

    /**
     * 线程池
     **/
    private final ExecutorService executorService = Executors.newFixedThreadPool(50);


    @PreDestroy
    public void destroyed() {
        executorService.shutdown();
    }

    // 批量列入严重违法失信  Excel表属性集合，顺序与批量导入的Excel文件中的列一致
    public static final List<String> PRIPERSON_FIELD_LIST = initPriPersonFieldList();

    private static List<String> initPriPersonFieldList() {
        List<String> list = new ArrayList<String>();
        list.add("entname");//企业名称
        list.add("regno");  //注册号
        list.add("serillrea"); //列入事实和法律依据 (编码、勾选)
        list.add("lostcreditexplain"); //列入事实和法律依据 (编辑)
        return Collections.unmodifiableList(list);
    }

    /**
     * 异常名录期限届满列入严重违法前 主体信息验证
     */
    @RequestMapping(value = "/validateBiz.do", method = RequestMethod.POST)
    public RestResult<?> validateBiz(HttpServletRequest request, String abnlistids, String pripids, String type) {
//        AICUser aicUser = (AICUser) request.getSession().getAttribute(ConstantsUtil.USER_SESSION_NAME);
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        if ("timeout".equals(type) && StringUtils.isNotBlank(abnlistids)) {//经营异常名录期限届满 列入
            List list = new ArrayList();
            String[] abnlistIDs = abnlistids.split(Constant.SEMICOLON);
            for (String abnlistid : abnlistIDs) {
                TSAbnList tsAbnListModel = tsAbnListService.getById(abnlistid);
                String validateResult = this.validate(tsAbnListModel);
                if (!"success".equals(validateResult)) {
                    Map<String, String> resultMap = new HashMap<String, String>();
                    resultMap.put("regno", tsAbnListModel.getRegno());
                    resultMap.put("entname", tsAbnListModel.getEntname());
                    resultMap.put("pripid", tsAbnListModel.getPripid());
                    resultMap.put("abnlistid", abnlistid);
                    resultMap.put("reason", validateResult);
                    list.add(resultMap);
                }
            }
            if (list.size() > 0) return RestResult.ok(list);

        } else if (("assist".equals(type) || "action".equals(type)) && StringUtils.isNotBlank(pripids)) {//协助执行、存在严重违法失信行为 列入
            List list = new ArrayList();
            String[] priPIDs = pripids.split(";");
            for (String pripid : priPIDs) {
                String result = this.validate(aicUser, pripid);
                if (!"success".equals(result)) {
                    Map<String, String> resultMap = new HashMap<String, String>();
                    TREntBase paramModel = new TREntBase();
                    paramModel.setPripid(pripid);
                    TREntBase entBaseModel = trEntBaseService.getTrEntBase(paramModel);
                    resultMap.put("regno", StringUtils.isUscc(entBaseModel.getUscc()) ? entBaseModel.getUscc() : entBaseModel.getRegno());
                    resultMap.put("entname", entBaseModel.getEntname());
                    resultMap.put("pripid", pripid);
                    if ("exist".equals(result)) { //曾因XX被列入过，提示用户
                        TSSerIllegalList serModel = new TSSerIllegalList();
                        serModel.setPripid(pripid);
                        List<TSSerIllegalList> serIllegalList = tsSerIllegalListService.selectEntList(serModel);
                        StringBuilder reason = new StringBuilder();
                        if (CollectionUtils.isNotEmpty(serIllegalList)) {
                            for (TSSerIllegalList model : serIllegalList) {
                                if (model.getRemdate() == null && StringUtils.isNotBlank(model.getSerillreaString())) {
                                    if (StringUtils.isNotBlank(reason)) reason.append("; ");
                                    reason.append(model.getSerillreaString());
                                }
                            }
                        }
                        resultMap.put("reason", "主体曾因(" + reason.toString() + ")被列入且未移出");
                        resultMap.put("flag", "1");

                    } else {
                        resultMap.put("reason", result);
                        resultMap.put("flag", "0");
                    }
                    list.add(resultMap);
                }
            }
            if (list.size() > 0) return RestResult.ok(list);
        }

        return OK;
    }

    /**
     * 协助执行、存在严重违法失信行为：列入严重违法失信前校验方法
     */
    private String validate(AICUser aicUser, String pripid) {
        TSEntBase tsEntBaseModel = tsEntBaseService.findTsentbaseByID(pripid);
        if (tsEntBaseModel == null) return "主体尚未被认领,不能列入";

        TSEntBaseAddr tsentBaseAddrModel = tsEntBaseAddrService.findTsentBaseAddrBypripid(pripid);
        if (tsentBaseAddrModel != null) {
            if (!StringUtils.equals(StringUtils.trimToEmpty(aicUser.getRegionID()),
                    StringUtils.trimToEmpty(tsentBaseAddrModel.getLocaladm())))
                return "非本机构监管主体,不能列入";
        }

        //校验 是否正在被列入或已被列入严重违法
        TSBizSerIllegal bizModel = new TSBizSerIllegal();
        bizModel.setPripid(pripid);
        List<TSBizSerIllegal> resultList = tsBizSerIllegalService.selectBizSerIllegalModels(bizModel);
        if (CollectionUtils.isEmpty(resultList)) return "success";//TSBizSerIllegal业务表 不存在记录，验证通过

        TSSerIllegalList paramModel = new TSSerIllegalList();
        paramModel.setPripid(pripid);
        List<TSSerIllegalList> serIllegalList = tsSerIllegalListService.selectEntList(paramModel);
        if (CollectionUtils.isEmpty(serIllegalList)) return "主体正在被列入";//业务表不空,且TSSerIllegalList无记录，存在待办

        for (TSSerIllegalList model : serIllegalList) {
            if (model.getRemdate() == null) return "exist";//严重违法企业名单 TSSerIllegalList 存在未移除的记录 提示用户
        }

        if (resultList.size() > serIllegalList.size()) {//业务存在正在受理
            return "主体正在被列入";
        }
        return "success";
    }

    /**
     * 异常名录期限届满列入严重违法前 校验方法
     */
    private String validate(TSAbnList tsAbnListModel) {
        /*
         * 校验该异常名录记录 是否存在相关待办
         */
        //异议待办
        TSBizDissent bizDissentModel = new TSBizDissent();
        bizDissentModel.setAbnlistid(tsAbnListModel.getAbnlistid());
        List<TSBizDissent> bizDissentModelList = tsBizDissentService.selectbizDissentList(bizDissentModel);
        if (CollectionUtils.isNotEmpty(bizDissentModelList)) {
            for (TSBizDissent tsBizDissentModel : bizDissentModelList) {
                List<TSTaskList> tsTaskListModels = taskListService.selectByBizSeqID(tsBizDissentModel.getBizseq());
                for (TSTaskList tsTaskListModel : tsTaskListModels) {
                    if (tsTaskListModel.getBusstatus().equals(BaseDataConstant.BUSINESS_STATUS_TRANSACT)) { //存在待办未办结
                        return "主体正在进行异议业务";
                    }
                }
            }
        }
        //移出待办
        TSBizRemList tsBizRemListModel = new TSBizRemList();
        tsBizRemListModel.setAbnlistid(tsAbnListModel.getAbnlistid());
        List<TSBizRemList> tsBizRemListModelList = tsBizRemListService.selectBRMexptlist(tsBizRemListModel);
        if (CollectionUtils.isNotEmpty(tsBizRemListModelList)) {
            for (TSBizRemList bizRemListModel : tsBizRemListModelList) {
                if (bizRemListModel.getRemreasons() == null || bizRemListModel.getApprovaldate() == null) {
                    return "主体正在进行移出业务";
                }
            }
        }
        //撤销待办
        boolean b = tsbizAbnRevokeService.validateBizRevoke(tsAbnListModel.getAbnlistid(), BaseDataConstant.BUSINESS_TYPE_REVOKEABN);
        if (!b) return "主体正在进行撤销业务";
        //修改待办
        List<TSTaskList> taskListModels = taskListService.selectByBizSeqID(tsAbnListModel.getAbnlistid());//原记录的id 作为新记录的业务号
        for (TSTaskList taskListModel : taskListModels) {
            if (taskListModel.getBusstatus().equals(BaseDataConstant.BUSINESS_STATUS_TRANSACT)) { //存在修改待办  未办结
                return "主体正在进行修改业务";
            }
        }

        /*
         * 校验 是否正在被列入或已被列入严重违法
         */
        TSBizSerIllegal bizModel = new TSBizSerIllegal();
        bizModel.setAbnlistid(tsAbnListModel.getAbnlistid());
        List<TSBizSerIllegal> resultList = tsBizSerIllegalService.selectBizSerIllegalModels(bizModel);
        if (CollectionUtils.isEmpty(resultList)) {//TSBizSerIllegal业务表 不存在记录，验证通过
            return "success";
        }

        TSSerIllegalList paramModel = new TSSerIllegalList();
        paramModel.setAbnlistid(tsAbnListModel.getAbnlistid());
        List<TSSerIllegalList> serIllegalList = tsSerIllegalListService.selectEntList(paramModel);
        if (CollectionUtils.isEmpty(serIllegalList)) {// 业务表不空,且TSSerIllegalList无记录，说明业务存在正在受理，验证不通过
            return "主体正在被列入";
        }

        for (TSSerIllegalList model : serIllegalList) {
            if (model.getRemdate() == null) { //严重违法企业名单 TSSerIllegalList 存在未移除的记录，验证不通过
                return "主体已被列入";
            }
        }
        if (resultList.size() > serIllegalList.size()) {//说明业务存在正在受理
            return "主体正在被列入";
        }
        return "success";
    }

    /**
     * 严重违法失信  受理呈报审批
     */
    @Transactional
    @RequestMapping(value = "/saveAccept.do")
    public RestResult<?> saveAccept(HttpServletRequest request, String serialIds, String pripids, String type,
                                    String serillreaCode, String batchAndCase, String bustype, String sourceType, String illoperatingid) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        String bizSeq = UUID.randomUUID().toString();

        List<TSBizSerIllegal> bizSerList = new ArrayList<TSBizSerIllegal>();
        if ("timeout".equals(type) && StringUtils.isNotBlank(serialIds)) {//异常名录期限届满  录入
            String[] serialIdList = serialIds.split(";");
            String decOrgCode = aicorgService.getRegionCodeByUser(aicUser);
            for (int i = 0; i < serialIdList.length; i++) {
                TSForIllOperatingList tsForllOperatingList = tsForIllOperatingListService.getById(serialIdList[i]);
                TSAbnList tsAbnListModel = tsAbnListService.getById(tsForllOperatingList.getAbnlistid());
                TSBizSerIllegal tsBizSerIllegalModel = new TSBizSerIllegal();
                tsBizSerIllegalModel.setSerialId(tsForllOperatingList.getSerialId());
                tsBizSerIllegalModel.setAbnlistid(tsAbnListModel.getAbnlistid());
                tsBizSerIllegalModel.setBizseq(bizSeq);
                tsBizSerIllegalModel.setPripid(tsAbnListModel.getPripid());
                tsBizSerIllegalModel.setRegno(tsAbnListModel.getRegno());
                tsBizSerIllegalModel.setUniscid(tsAbnListModel.getUniscid());
                tsBizSerIllegalModel.setEntname(tsAbnListModel.getEntname());

                tsBizSerIllegalModel.setDecorg(decOrgCode);
                if (StringUtils.isNotBlank(batchAndCase) && !"undefined".equals(batchAndCase)) {
                    tsBizSerIllegalModel.setBatchAndCase(batchAndCase);
                }
                if (StringUtils.isNotBlank(serillreaCode))
                    tsBizSerIllegalModel.setSerillrea(serillreaCode);
                bizSerList.add(tsBizSerIllegalModel);

                tsForllOperatingList.setOperationStatus("5");
                tsForIllOperatingListService.updateById(tsForllOperatingList);

            }

        } else if (("assist".equals(type) || "action".equals(type)) && StringUtils.isNotBlank(pripids)) {//协助执行、存在严重违法失信行为 录入
            String[] pripid = pripids.split(";");
            List<EBaseinfo> companyDetails = eBaseinfoService.list(new LambdaQueryWrapper<EBaseinfo>().in(EBaseinfo::getPripid, pripid));
            Map<String, EBaseinfo> companyDetailsMap = companyDetails.stream().collect(Collectors.toMap(EBaseinfo::getPripid, each -> each));
            for (int i = 0; i < pripid.length; i++) {
//                TSEntBase tsEntBaseModel = tsEntBaseService.findTsentbaseByID(pripid[i]);
                EBaseinfo each = companyDetailsMap.get(pripid[i]);
                TSBizSerIllegal tsBizSerIllegalModel = new TSBizSerIllegal();
                tsBizSerIllegalModel.setBizseq(bizSeq);
                tsBizSerIllegalModel.setPripid(pripid[i]);
                tsBizSerIllegalModel.setRegno(each.getRegno());
                tsBizSerIllegalModel.setUniscid(each.getUniscid());
                tsBizSerIllegalModel.setEntname(each.getEntname());
                tsBizSerIllegalModel.setDecorg(aicUser.getRegionID());
                if (StringUtils.isNotBlank(batchAndCase) && !"undefined".equals(batchAndCase)) {
                    tsBizSerIllegalModel.setBatchAndCase(batchAndCase);
                }
                if ("action".equals(type) && StringUtils.isNotBlank(serillreaCode)) {
                    tsBizSerIllegalModel.setSerillrea(serillreaCode);
                }
                //来源类型 2021-11-28
                tsBizSerIllegalModel.setSourceType(sourceType);
                bizSerList.add(tsBizSerIllegalModel);

                TSForIllOperatingBn tSForIllOperatingBn = new TSForIllOperatingBn();
                tSForIllOperatingBn.setIlloperatingid(illoperatingid);
                tSForIllOperatingBn.setOperationStatus("4");//正在进行列入操作
                tSForIllOperatingBn.setLauptime(LocalDateTime.now());
                tsForIllOperatingBnService.updateById(tSForIllOperatingBn);
            }
        }
        if (bizSerList.size() == 0) throw new BusinessException("尚未查找到企业相关信息");

        //待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        if ("0".equals(bustype)) {//区分是拟列入违法还是列入违法
            taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_INCLUDEDILLEGAL);//拟列入严重违法失信
        } else {
            taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_ENTERSERILLEGAL);//列入严重违法失信
        }

        StringBuilder entName = new StringBuilder();
        for (int i = 0; i < bizSerList.size(); i++) {
            if (i > 0) entName.append("、");
            if (i > 1) {
                entName.append("等企业");
                break;
            }
            entName.append(bizSerList.get(i).getEntname());
        }
        taskListModel.setBusname(entName.toString());
        //列入严重违法 受理保存
        taskListModel = tsBizSerIllegalService.saveSerIllegalAccept(aicUser, taskListModel, bizSerList);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizSeq);
            result.put("workflowId", taskListModel.getWorkflowid());
            result.put("batchAndCase", batchAndCase);
            return RestResult.ok(result);
        }

        throw new BusinessException("内部服务出错，请联系管理员!");
    }

    /**
     * 严重违法失信名单 审批
     */
    @RequestMapping(value = "/approvalnext.do")
    public RestResult<?> approvalnext(Model model, TSTaskList taskListModel, String type) {
        StringBuilder abnlistids = new StringBuilder();
        StringBuilder pripids = new StringBuilder();
        TSTaskList taskListModel1 = taskListService.selectByTasklistID(taskListModel.getTasklistid());
        TSBizSerIllegal paramModel = new TSBizSerIllegal();
        paramModel.setBizseq(taskListModel1.getBizseqid());
        Map<String, Object> resultMap = new HashMap<>();
        List<TSBizSerIllegal> list = tsBizSerIllegalService.selectBizSerIllegalModels(paramModel);
        if (list.size() > 0) {
            for (TSBizSerIllegal bizSerIllegalModel : list) {
                if (StringUtils.isNotBlank(pripids)) pripids.append(Constant.SEMICOLON);
                if (StringUtils.isNotBlank(abnlistids)) abnlistids.append(Constant.SEMICOLON);

                if (StringUtils.isNotBlank(bizSerIllegalModel.getAbnlistid()))
                    abnlistids.append(bizSerIllegalModel.getAbnlistid());
                if (StringUtils.isNotBlank(bizSerIllegalModel.getPripid()))
                    pripids.append(bizSerIllegalModel.getPripid());
            }
            //列入事实和法律依据 回显
            resultMap.put("serillrea", list.get(0).getSerillrea());
            resultMap.put("lostcreditexplain", list.get(0).getLostcreditexplain());
            resultMap.put("ReconsiderationOrg", list.get(0).getReconsiderationOrg());
            resultMap.put("GovernmentOrg", list.get(0).getGovernmentOrg());
            resultMap.put("LitiOrg", list.get(0).getLitiOrg());

        } else if ("action".equals(type)) { //因 存在严重违法失信行为 列入，列入原因默认选中
            resultMap.put("serillrea", list.get(0).getSerillrea());
        }

        List<SequenceFlowModel> nextSequenceFlowList = workFlowService.findNextSequenceFlowList(taskListModel1.getWorkflowid());
        TSTwfProcessNode currentNode = workFlowService.findCurrentNode(taskListModel1.getWorkflowid());
        String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(currentNode.getCurrentnode());

        //获取 严重违法失信企业列入原因及对应法律条款
        if (StringUtils.isBlank(type) && StringUtils.isNotBlank(abnlistids)) type = "timeout";
        List<TSBizSerIllegalReas> reasList = tsBizSerIllegalService.getSerillreas(type);

        if (opinionType == null) opinionType = "1";
        resultMap.put("opinionList", opinionService.selectByAuditingID(taskListModel1.getWorkflowid()));
        resultMap.put("nextSequenceFlowList", nextSequenceFlowList);
        resultMap.put("tasklistid", taskListModel1.getTasklistid());
        resultMap.put("abnlistids", abnlistids);
        resultMap.put("pripids", pripids);
        resultMap.put("bizSeq", taskListModel1.getBizseqid());
        resultMap.put("currentNode", currentNode.getCurrentnode());
        resultMap.put("currentLinkTypeID", opinionType);
        resultMap.put("currentNodeName", WorkFlowUtil.getNodeName(currentNode.getCurrentnode()));
        resultMap.put("type", type);
        resultMap.put("reasList", reasList);

        return RestResult.ok(resultMap);
    }

    /**
     * 查看待列入的企业名单
     */
    @RequestMapping(value = "/selectSerIllegalByPageList.do", method = RequestMethod.POST)
    public RestResult<?> selectSerIllegalByPageList(TSBizSerIllegal tsBizSerIllegalModel,
                                                    int rows, int page) {
        return RestResult.ok(tsBizSerIllegalService.selectSerIllegalByPageList(rows, page, tsBizSerIllegalModel));
    }

    /**
     * 删除列入信息
     */
    @RequestMapping(value = "/delSerIllegal.do", method = RequestMethod.POST)
    public RestResult<?> delSerIllegal(String illegallistid) {
        tsBizSerIllegalService.removeById(illegallistid);
        return OK;
    }

    /**
     * 增加列入信息
     */
    @RequestMapping(value = "/addMoreEnt.do", method = RequestMethod.POST)
    public RestResult<?> addMoreEnt(HttpServletRequest request, String regno, String entname, String bizseq, String type) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        if ("timeout".equals(type)) {//异常名录期限届满 录入
            TSAbnList tsAbnListModel = new TSAbnList();

            // 因为TSAbnList没有uscc
            TSEntBaseQuery entInfo = entBaseQueryService.queryEntBaseInfoByRegno(regno);
            tsAbnListModel.setRegno(entInfo.getRegNO());
            tsAbnListModel.setEntname(entname);
//            tsAbnListModel.setDecorg(aicUser.getRegionID());//只查询属于本机构做出决定的 异常名录主体
            IPage<TSAbnList> dataGrid = tsAbnListService.selectAbnListByPage(5, 1, tsAbnListModel);
            if (CollectionUtils.isEmpty(dataGrid.getRecords())) {
                throw new BusinessException("无法查到该主体经营异常信息,请确认查询条件");
            } else {
                tsAbnListModel = dataGrid.getRecords().get(0);
            }

            if (tsAbnListModel != null && StringUtils.isNotBlank(tsAbnListModel.getAbnlistid())) {
                TSBizSerIllegal bizSerIllegalModel = new TSBizSerIllegal();
                bizSerIllegalModel.setAbnlistid(tsAbnListModel.getAbnlistid());
                bizSerIllegalModel.setPripid(tsAbnListModel.getPripid());
                bizSerIllegalModel.setBizseq(bizseq);
                List<TSBizSerIllegal> bizModelList = tsBizSerIllegalService.selectBizSerIllegalModels(bizSerIllegalModel);
                if (CollectionUtils.isEmpty(bizModelList)) { //避免重复增加
                    String validateResult = this.validate(tsAbnListModel);
                    if ("success".equals(validateResult)) {
                        bizSerIllegalModel.setRegno(tsAbnListModel.getRegno());
                        bizSerIllegalModel.setEntname(tsAbnListModel.getEntname());
                        bizSerIllegalModel.setDecorg(aicUser.getRegionID());
                        tsBizSerIllegalService.saveOrUpdate(bizSerIllegalModel);
                        return OK;
                    } else {
                        Map<String, Object> resultMap = new HashMap<>();
                        resultMap.put("regno", tsAbnListModel.getRegno());
                        resultMap.put("entname", tsAbnListModel.getEntname());
                        return RestResult.ok(resultMap);
                    }
                }
            }

        } else {//协助执行、存在严重违法失信行为  录入
            TSEntBaseQuery entBaseModel = new TSEntBaseQuery();
            entBaseModel.setRegNO(regno);
            entBaseModel.setEntName(entname);
//            entBaseModel.setLocalAdm(aicUser.getRegionID()); //只查询本机构监管的主体
            IPage<TSEntBaseQuery> dataGrid = tsSerIllegalListService.serIllegalListByPage(5, 1, entBaseModel);
            if (CollectionUtils.isEmpty(dataGrid.getRecords())) {
                throw new BusinessException("无法查到该主体信息,请确认查询条件");
            } else {
                entBaseModel = dataGrid.getRecords().get(0);
            }

            if (entBaseModel != null && StringUtils.isNotBlank(entBaseModel.getPriPID())) {
                TSBizSerIllegal bizSerIllegalModel = new TSBizSerIllegal();
                bizSerIllegalModel.setBizseq(bizseq);
                bizSerIllegalModel.setPripid(entBaseModel.getPriPID());
                List<TSBizSerIllegal> bizModelList = tsBizSerIllegalService.selectBizSerIllegalModels(bizSerIllegalModel);
                if (CollectionUtils.isEmpty(bizModelList)) { //避免重复增加
                    String validateResult = this.validate(aicUser, entBaseModel.getPriPID());
                    if ("success".equals(validateResult) || "exist".equals(validateResult)) {
                        bizSerIllegalModel.setRegno(entBaseModel.getRegNO());
                        bizSerIllegalModel.setUniscid(entBaseModel.getUscc());
                        bizSerIllegalModel.setEntname(entBaseModel.getEntName());
                        bizSerIllegalModel.setDecorg(aicUser.getRegionID());
                        tsBizSerIllegalService.saveOrUpdate(bizSerIllegalModel);
                        return OK;
                    } else {
                        Map<String, Object> resultMap = new HashMap<>();
                        resultMap.put("regno", StringUtils.isUscc(entBaseModel.getUscc()) ? entBaseModel.getUscc() : entBaseModel.getRegNO());
                        resultMap.put("entname", entBaseModel.getEntName());
                        return RestResult.ok(resultMap);
                    }

                }
            }
        }
        throw new BusinessException("无法查找到该主体信息，请确认查询条件或检查是否已在列表中");
    }

    /**
     * 严重违法失信 审批流程
     * 保存列入严重违法失信  转接到待办列表中
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/serIllegalNext.do")
    public RestResult<?> serIllegalNext(HttpServletRequest request, TSBizSerIllegal tsBizSerIllegalModel, TSOpinion opinionModel, String forillOperaOrSerillega,
                                        String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID, String type, String batchAndCase) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        Map<String, Object> resultMap = new HashMap<>();
        //更新严重违法失信业务表
        if (StringUtils.isNotBlank(tsBizSerIllegalModel.getBizseq())) {
            TSBizSerIllegal paramModel = new TSBizSerIllegal();
            paramModel.setBizseq(tsBizSerIllegalModel.getBizseq());
            List<TSBizSerIllegal> tsBizSerIllegalModels = tsBizSerIllegalService.selectBizSerIllegalModels(paramModel);
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            for (TSBizSerIllegal bizSerIllegalModel : tsBizSerIllegalModels) {
                if (FlowUtil.SERILLEGALWORKFLOW_OVERSERILLEGAL.equals(nextNodeID)) {
                    // 判断是否为经办环节直接结束
                    TSTwfProcessNode tsTwfProcessNode = tsTwfProcessNodeService.getOne(new LambdaQueryWrapper<TSTwfProcessNode>()
                            .eq(TSTwfProcessNode::getProcessid, taskListModel.getWorkflowid())
                            .eq(TSTwfProcessNode::getStatus, "0"));
                    if (FlowUtil.SERILLEGALWORKFLOW_SERILLEGALENTER.equals(tsTwfProcessNode.getCurrentnode())) {
                        bizSerIllegalModel.setEndReason(tsBizSerIllegalModel.getEndReason());
                        bizSerIllegalModel.setEndApply(tsBizSerIllegalModel.getEndApply());
                        bizSerIllegalModel.setSerillrea(tsBizSerIllegalModel.getSerillrea());
                        bizSerIllegalModel.setLostcreditexplain(tsBizSerIllegalModel.getLostcreditexplain().trim());
                    }
                }
                if (FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) {
                    bizSerIllegalModel.setSerillrea(tsBizSerIllegalModel.getSerillrea());
                    bizSerIllegalModel.setLostcreditexplain(tsBizSerIllegalModel.getLostcreditexplain().trim());
                    bizSerIllegalModel.setReconsiderationOrg(tsBizSerIllegalModel.getReconsiderationOrg()); // 行政复议机关
                    bizSerIllegalModel.setGovernmentOrg(tsBizSerIllegalModel.getGovernmentOrg()); // 人民政府
                    bizSerIllegalModel.setLitiOrg(tsBizSerIllegalModel.getLitiOrg()); // 诉讼机关
//                    bizSerIllegalModel.setBatchAndCase(batchAndCase);//批量与个案标识,0为批量，1为个案
                    bizSerIllegalModel.setEndApply(tsBizSerIllegalModel.getEndApply());//是否申请结束
                    bizSerIllegalModel.setEndReason(tsBizSerIllegalModel.getEndReason());//结束原因

                    //行政处罚列严的时候，线下手动输入 开始
                    bizSerIllegalModel.setAbntime(tsBizSerIllegalModel.getAbntime());
                    bizSerIllegalModel.setWritsno(tsBizSerIllegalModel.getWritsno());
                    bizSerIllegalModel.setParty(tsBizSerIllegalModel.getParty());
                    bizSerIllegalModel.setCertificate(tsBizSerIllegalModel.getCertificate());
                    bizSerIllegalModel.setUsccId(tsBizSerIllegalModel.getUsccId());
                    bizSerIllegalModel.setIdNumber(tsBizSerIllegalModel.getIdNumber());
                    bizSerIllegalModel.setLegalName(tsBizSerIllegalModel.getLegalName());
                    bizSerIllegalModel.setPhone(tsBizSerIllegalModel.getPhone());
                    bizSerIllegalModel.setOtherCert(tsBizSerIllegalModel.getOtherCert());
                    bizSerIllegalModel.setResidence(tsBizSerIllegalModel.getResidence());
                    //行政处罚列严的时候，线下手动输入 结束
                }
            }

            if (StringUtils.isBlank(nextPerformerids)) {
                TSTwfProcessNode processNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
                int order = WorkFlowUtil.checkNextOrder(processNode.getCurrentnode(), nextNodeID);
                // 通过order判断为回退还是前进 >0前进
                if (order > 0) {
                    List<TSTwfProcessNode> tsTwfProcessNodes = tsTwfProcessNodeService.
                            queryByPROCESSIDAndCURRENTNODE(taskListModel.getWorkflowid(), FlowUtil.SERILLEGALWORKFLOW_SERILLEGALENTER);
                    nextPerformerids = tsTwfProcessNodes.get(0).getCurruserid();
                    nextPerformerNames = tsTwfProcessNodeService.queryRealName(tsTwfProcessNodes.get(0).getCurruserid());
                }
                // 回退时 获取上一个处理人
                if (order < 0) {
                    if (FlowUtil.SERILLEGALWORKFLOW_SERILLEGALENTER.equals(nextNodeID)) {
                        //审核人进行退回到经办人
                        TSOpinion tsOpinion = opinionService.getNewestOpinion(taskListModel.getWorkflowid(), "0");
                        nextPerformerids = tsOpinion.getHandlerid();
                        nextPerformerNames = tsOpinion.getHandler();
                    } else if (FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) {
                        //审批人进行退回到审核人
                        TSOpinion tsOpinion = opinionService.getNewestOpinion(taskListModel.getWorkflowid(), "1");
                        nextPerformerids = tsOpinion.getHandlerid();
                        nextPerformerNames = tsOpinion.getHandler();
                    }
                    // 不再以此为标识判断，如需判断经办环节是否为回退的，判断意见记录是否大于0，或者判断当前节点的`NODEFLOW`字段
                    // endApply 只标识审批通过后是否做列严
//                    for (TSBizSerIllegal bizSerIllegalModel : tsBizSerIllegalModels) {//回退时把endApply设置为2
//                        bizSerIllegalModel.setEndApply("2");
//                        tsBizSerIllegalService.saveOrUpdate(bizSerIllegalModel);
//                    }
                }
            }

            //发送
            String[] ids = StringUtils.split(nextPerformerids, ",");

            String[] names = StringUtils.split(nextPerformerNames, ",");

            tsBizSerIllegalService.saveSerIllegalAuditProcess(user, taskListModel, tsBizSerIllegalModels, opinionModel, nextNodeID, ids, names, type, forillOperaOrSerillega);
            resultMap.put("bizseq", tsBizSerIllegalModel.getBizseq());
            resultMap.put("type", type);
            resultMap.put("workflowid", taskListModel.getWorkflowid());
            resultMap.put("nextNodeID", nextNodeID);
            resultMap.put("tasklistid", tasklistid);
        }
        return RestResult.ok(resultMap);
    }

    /**
     * 严重违法失信批量审核/审核
     */
    @PostMapping("/batchReviewAndExamine")
    public RestResult<?> batchReviewAndExamine(@RequestBody Map<String, Object> data, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        List<TaskListUnionDto> taskList = JSONObject.parseArray(JSONObject.toJSONString(data.get("taskListUnionDto")), TaskListUnionDto.class);

        String nextNodeID = (String) data.get("nextNodeID");
        String opinion = (String) data.get("opinion");
        String batchType = (String) data.get("batchType");
        String handledateStr = (String) data.get("handledate");
        LocalDateTime handledate = LocalDateTime.parse(handledateStr, DateTimeUtils.DATETIME_FORMATTER);
        if ("end".equals(nextNodeID) && CollectionUtils.isNotEmpty(taskList) && taskList.size() > 100)
            throw new BusinessException("超出最大审批数量，最多不能超过100条。");

        String nextPerformerids = null;
        String nextPerformerNames = null;
        if (data.get("nextPerformerids") != null) {
            nextPerformerids = (String) data.get("nextPerformerids");
            nextPerformerNames = (String) data.get("nextPerformerNames");
        }
//        ExecutorService executorService = Executors.newFixedThreadPool(50);//最大同时50个线程池
        CountDownLatch countDownLatch = new CountDownLatch(taskList.size());

        //遍历批量审核列表参数，并调用方法
        for (TaskListUnionDto taskListUnionDto : taskList) {
            String finalNextPerformerids = nextPerformerids;
            String finalNextPerformerNames = nextPerformerNames;
            Runnable runnable = () -> {
                TSBizSerIllegal tsBizSerIllegalModel = new TSBizSerIllegal();
                tsBizSerIllegalModel.setBizseq(taskListUnionDto.getBizseqid());

                TSOpinion opinionModel = new TSOpinion();
                opinionModel.setWorkflowid(taskListUnionDto.getWorkflowid());
                opinionModel.setHandler(user.getName());
                opinionModel.setHandlerid(user.getPrimaryKey());
                opinionModel.setOpinioncontent(opinion);
                opinionModel.setHandledate(handledate);

                if (batchType.equals("review")) {
                    //审核
                    opinionModel.setOpiniontype("1");
                } else if (batchType.equals("examine")) {
                    //审批
                    opinionModel.setOpiniontype("2");
                }

                serIllegalNext(request, tsBizSerIllegalModel, opinionModel, null, taskListUnionDto.getTasklistid(),
                        finalNextPerformerids, finalNextPerformerNames, nextNodeID, null, null);
                countDownLatch.countDown();//减1
            };
            executorService.submit(runnable);
        }

        try {
            countDownLatch.await(5, TimeUnit.MINUTES);//5分钟超时
        } catch (Exception e) {
            log.error("批量审核/审批失败", e);
        }
        return OK;
    }

    /**
     * Excel批量列入严重违法失信 受理保存并生成待办
     */
    @RequestMapping("/saveBatchSerIllegalListAccept.do")
    public RestResult<?> batchSerIllegalList(HttpServletRequest request, MultipartFile file, String type) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        String bizSeq = UUID.randomUUID().toString();

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());//文件后缀
        String suffixList = "xls,xlsx"; //允许上传的文件类型
        if (!suffixList.contains(suffix.trim().toLowerCase())) {
            throw new BusinessException("不支持的文件类型,请上传Excel文件");
        }

        List<Map<String, String>> entList = ExcelUtil.parseExcel(file, PRIPERSON_FIELD_LIST);
        if (CollectionUtils.isEmpty(entList))
            throw new BusinessException("上传文件中尚未找到企业信息");

        List<TSBizSerIllegal> bizSerIllegalList = new ArrayList<TSBizSerIllegal>();
        if ("timeout".equals(type)) {//异常名录期限届满 列入
            for (Map<String, String> map : entList) {
                String regno = map.get("regno");// todo 注意这里有的是统一社会信用代码 TSAbnList 这个表没有uscc
                String entname = map.get("entname");
                if (StringUtils.isBlank(regno) || StringUtils.isBlank(entname)) continue; //忽略异常数据

                TSAbnList abnListModel = new TSAbnList();

                // queryEntBaseInfoByRegno
                TSEntBaseQuery entInfo = entBaseQueryService.queryEntBaseInfoByRegno(regno);
                // todo TSAbnList 这个表没有 uscc 所以只能通过查询企业信息拿到regno
                abnListModel.setRegno(entInfo.getRegNO());
                abnListModel.setEntname(entname);
//                abnListModel.setDecorg(aicUser.getRegionID());//只列入本机构做出决定的 经营异常名录
                IPage<TSAbnList> dataGrid = tsAbnListService.selectTSAbnByTimeout(3, 1, abnListModel);
                if (CollectionUtils.isNotEmpty(dataGrid.getRecords())) {
                    TSAbnList tsAbnListModel = dataGrid.getRecords().get(0);
                    //列入前校验,过滤掉不能列入的
                    if ("success".equals(this.validate(tsAbnListModel))) {
                        TSBizSerIllegal tsBizSerIllegalModel = new TSBizSerIllegal();
                        tsBizSerIllegalModel.setBizseq(bizSeq);
                        tsBizSerIllegalModel.setAbnlistid(tsAbnListModel.getAbnlistid());
                        tsBizSerIllegalModel.setPripid(tsAbnListModel.getPripid());
                        tsBizSerIllegalModel.setRegno(tsAbnListModel.getRegno());
                        tsBizSerIllegalModel.setUniscid(tsAbnListModel.getUniscid());
                        tsBizSerIllegalModel.setEntname(tsAbnListModel.getEntname());
                        tsBizSerIllegalModel.setSerillrea(map.get("serillrea").split("\\.")[0]);
                        tsBizSerIllegalModel.setLostcreditexplain(map.get("lostcreditexplain"));
                        tsBizSerIllegalModel.setDecorg(aicUser.getRegionID());
                        bizSerIllegalList.add(tsBizSerIllegalModel);
                    }
                }
            }

        } else {//存在严重违法失信行为 协助执行列入
            for (Map<String, String> map : entList) {
                String regno = map.get("regno");
                String entname = map.get("entname");
                if (StringUtils.isBlank(regno) || StringUtils.isBlank(entname)) continue; //忽略异常数据

                TSEntBaseQuery entBaseQueryModel = new TSEntBaseQuery();
                entBaseQueryModel.setRegNO(regno);
                entBaseQueryModel.setEntName(entname);
//                entBaseQueryModel.setLocalAdm(aicUser.getRegionID());//只查询本机构监管的主体
                IPage<TSEntBaseQuery> dataGrid = tsSerIllegalListService.serIllegalListByPage(3, 1, entBaseQueryModel);
                if (CollectionUtils.isNotEmpty(dataGrid.getRecords())) {
                    TSEntBaseQuery entBaseModel = dataGrid.getRecords().get(0);
                    //列入前校验,过滤掉不能列入的
                    if ("success".equals(this.validate(aicUser, entBaseModel.getPriPID()))) {
                        TSBizSerIllegal bizSerIllegalModel = new TSBizSerIllegal();
                        bizSerIllegalModel.setBizseq(bizSeq);
                        bizSerIllegalModel.setPripid(entBaseModel.getPriPID());
                        bizSerIllegalModel.setRegno(entBaseModel.getRegNO());
                        bizSerIllegalModel.setUniscid(entBaseModel.getUscc());
                        bizSerIllegalModel.setEntname(entBaseModel.getEntName());
                        bizSerIllegalModel.setSerillrea(map.get("serillrea").split("\\.")[0]);
                        bizSerIllegalModel.setLostcreditexplain(map.get("lostcreditexplain"));
                        bizSerIllegalModel.setDecorg(aicUser.getRegionID());
                        bizSerIllegalList.add(bizSerIllegalModel);
                    }
                }
            }
        }

        if (bizSerIllegalList.size() == 0)
            throw new BusinessException("上传文件中尚未查找到企业相关信息");

        //待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_ENTERSERILLEGAL);//列入严重违法失信
        StringBuffer entname = new StringBuffer("");
        for (int i = 0; i < bizSerIllegalList.size(); i++) {
            if (i > 1) {
                entname.append("等企业");
                break;
            }
            if (i > 0) {
                entname.append("、");
            }
            entname.append(bizSerIllegalList.get(i).getEntname());
        }
        taskListModel.setBusname(entname.toString());
        //列入严重违法失信受理保存
        taskListModel = tsBizSerIllegalService.saveSerIllegalAccept(aicUser, taskListModel, bizSerIllegalList);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("tasklistid", taskListModel.getTasklistid());
            resultMap.put("bizseq", bizSeq);
            return RestResult.ok(resultMap);
        }
        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
    }


    /**
     * 主体信息分页
     *
     * @param request        请求信息
     * @param pageRequestDto 分页参数
     * @return 分页结果
     * @author lwd
     * @since 2021年8月03日 19:45:32
     */
    @ApiOperation("主体信息分页")
    @PostMapping("entInfoPage")
    public RestResult<?> selectEntInfoPage(HttpServletRequest request, @ApiParam("分页参数") @RequestBody PageRequestDto pageRequestDto) {
        AssertUtils.isNotNull(pageRequestDto);
        Map<String, Object> paramMap = pageRequestDto.getParamMap();
        if (paramMap == null) {
            paramMap = new HashMap<>();
        }
        return RestResult.ok(eBaseinfoService.getComplexEntInfoPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), paramMap));
    }

    /**
     * 查询列入严重违法失信企业名单列表
     *
     * @return 分页结果
     * @author lwd
     * @since 2021年8月05日 19:05:38
     */
    @ApiOperation("查询列入严重违法失信企业名单列表")
    @PostMapping("selectSerillegalPage")
    public RestResult<?> selectForIllOperatingBnPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        Map<String, Object> resultMap = new HashMap<>();
        // 搜索统一码和注册号
        String searchUscc = StringUtils.tranObject(paramMap.get("searchUscc"));
        //判断入参为统一码还是注册号
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                paramMap.put("uniscid", searchUscc);
            } else {
                paramMap.put("regno", searchUscc);
            }
        }
        AICUser curUser = getLoginUser(request);
        //判断是否注册二处的
        if ("f7b2117a-ee80-4470-930e-03f106f3e031".equals(curUser.getUnitID())) {
            paramMap.put("acceptRegorg", "440129");//查询受理机关
        } else {
            LambdaQueryWrapper<Gzaiccode> glqw = Wrappers.lambdaQuery();
            glqw.eq(Gzaiccode::getOrgunitid, curUser.getOrgID());
            glqw.in(Gzaiccode::getSlevel, "3", "4");
            glqw.orderByAsc(Gzaiccode::getSlevel);
            Gzaiccode gzaiccode = iGzaiccodeService.list(glqw).get(0);
            paramMap.put("regorg", gzaiccode.getScountrycode());//查询登记机关
        }

        IPage<TSForIllOperatingBn> serillegalList = tsForIllOperatingBnService.selectForIllOperatingBn(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), paramMap);

        resultMap.put("serillegalList", serillegalList);

        return RestResult.ok(serillegalList);
    }

    /**
     * 严重违法启动经办环节
     */
    @PostMapping("/startIncludeIllegal")
    public RestResult<TSTaskList> startIncludeIllegal(@RequestBody TSBizSerIllegal tsBizSerIllegal, HttpServletRequest request) {

        AICUser aicUser = getLoginUser(request);
        // 判断是否有经办权限
        List<String> list = aicorgService.jurisdictionCheck("acceptSerIllegal", aicUser.getPrimaryKey());
        if (list.size() == 0) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "暂无发起权限");
        }
        // 是否来自拟列入表
        if (StringUtils.isNotBlank(tsBizSerIllegal.getIlloperatingid())) {
            TSBizSerIllegal tsbiz = tsBizSerIllegalService.getOne(
                    new LambdaQueryWrapper<TSBizSerIllegal>().eq(TSBizSerIllegal::getIlloperatingid, tsBizSerIllegal.getIlloperatingid()));
            // 判断是否已经生成待办
            if (tsbiz != null) {
                TSTaskList tsTaskList = taskListService.getOne(
                        new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, tsbiz.getBizseq()));
                return RestResult.ok(tsTaskList);
            }
        }

        TSTaskList taskList = tsBizSerIllegalService.startIncludeIllegal(tsBizSerIllegal);
        return RestResult.ok(taskList);
    }

    /**
     * 严重违法-下一步环节流转（主要有：办结作废、发送审核、发送审批、审批通过、审批不通过、退回）
     * currentLink 当前页面的环节：经办、审核、审查
     * nextNodeId 流转的节点  FlowUtil.ILLEGAL_*
     * nextHandleId 下一个处理人userId
     */
    @PostMapping("/nextProcessInclude")
    public RestResult<Boolean> nextProcessInclude(@RequestParam String currentLink, @RequestParam String nextNodeId, String nextHandleId,
                                                  @RequestBody TSBizSerIllegal tsBizSerIllegal) {
        boolean b = tsBizSerIllegalService.nextProcessInclude(currentLink, nextNodeId, nextHandleId, tsBizSerIllegal);
        return RestResult.ok(b);
    }

    /**
     * 判断用户机构是否能发起
     */
    @PostMapping("/checkIllegalStart")
    public RestResult<?> checkIllegalStart(@RequestBody TSBizSerIllegal tsBizSerIllegal, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        //进行判断，且允许上级办理下级的信用修复
        Map<String, String> map = new HashMap<>();
        map.put("orgNumber", aicUser.getRegionID());
        map.put("deleted", "0");
        map.put("unittype", "1");
        OrgUnits org = aicorgService.queryByOrgNumberMap(map);

        EBaseinfo eBaseinfo = eBaseinfoService.getOneByPripid(tsBizSerIllegal.getPripid());
        Integer orgLevel = org.getOrgLevel();
        boolean isSame = true;
        //根据机构等级判断
        if (orgLevel == 1) {    //省局
            isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                    StringUtils.substring(aicUser.getRegionID(), 0, 2),
                    StringUtils.substring(eBaseinfo.getRegorg(), 0, 2));
        } else if (orgLevel == 2) {    //市局
            isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                    StringUtils.substring(aicUser.getRegionID(), 0, 4),
                    StringUtils.substring(eBaseinfo.getRegorg(), 0, 4));
        } else if (orgLevel == 3) {    //区局
            isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                    StringUtils.substring(aicUser.getRegionID(), 0, 6),
                    StringUtils.substring(eBaseinfo.getRegorg(), 0, 6));
        } else if (orgLevel >= 4) {    //所
            isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                    StringUtils.substring(aicUser.getRegionID(), 0, 6),
                    StringUtils.substring(eBaseinfo.getRegorg(), 0, 6));
        }

        if (isSame) {
            return RestResult.ok(ResultCode.SUCCESS);
        } else {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "该主体登记机关是其他机关登记，无法发起");
        }
    }


}
