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.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAttachment;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSBizRemList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.abnormal.service.impl.GzaiccodeServiceImpl;
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.WorkFlowService;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntBaseService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalDiss;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalRem;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalDissService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalRemService;
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.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.enums.OpPositionEnum;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.entity.TUsers;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
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.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.BeanUtils;
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 javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Transactional
@RequestMapping("/bizSerIllegalRem")
public class BizSerIllegalRemController extends BaseController implements ServletContextListener {

    @Autowired
    private TSBizSerIllegalRemService tsBizSerIllegalRemService;
    @Autowired
    private TSSerIllegalListService tsSerIllegalListService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TREntBaseService trEntBaseService;
    @Autowired
    private TSBizSerIllegalDissService tsBizSerIllegalDissService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private TUsersService usersService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private AicorgService aicorgService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    private UuidUtil uuidUtil;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private GzaiccodeServiceImpl gzaiccodeService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private DeadlinestasService deadlinestasService;

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

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        executorService.shutdown();
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
    }

    /**
     * 移出前 信息验证
     */
    @RequestMapping(value = "/validateBiz.do", method = RequestMethod.POST)
    public RestResult<?> validateBiz(HttpServletRequest request, String illegallistids) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        Map<String, String> resultMap = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();
        String[] illegallistidArr = illegallistids.split(Constant.SEMICOLON);
        for (String illegallistid : illegallistidArr) {
            String validateResult = this.validate(illegallistid);
            TSSerIllegalList serIllegalListModel = tsSerIllegalListService.getById(illegallistid);
            if(!"该记录正在被移出".equals(validateResult)){
                int days = (int) ((int)LocalDate.now().toEpochDay() - serIllegalListModel.getAbntime().toEpochDay());
//            Period period = Period.between(serIllegalListModel.getAbntime(),LocalDate.now());
                if (days < 1095){
                    resultMap.put("reason", "企业需满足列入严重违法失信满3年才能发起移出严重违法失信流程，请重新选择");
                    return RestResult.ok(resultMap);
                }
            }

            if (!"success".equals(validateResult)) {

                resultMap.put("regno", serIllegalListModel.getRegno());
                resultMap.put("entname", serIllegalListModel.getEntname());
                resultMap.put("pripid", serIllegalListModel.getPripid());
                resultMap.put("illegallistid", illegallistid);
                resultMap.put("reason", validateResult);
                list.add(resultMap);
            }
        }
        if (CollectionUtils.isNotEmpty(list)) return RestResult.ok(list);

        return OK;
    }

    /**
     * 移出前信息验证 方法
     */
    private String validate(String illegallistid) {
        //验证 是否存在移出待办
        TSBizSerIllegalRem tsBizSerIllegalRemModel = new TSBizSerIllegalRem();
        tsBizSerIllegalRemModel.setIllegalListID(illegallistid);
        List<TSBizSerIllegalRem> resultList = tsBizSerIllegalRemService.selectBRMserIllegalList(tsBizSerIllegalRemModel);
        if (CollectionUtils.isEmpty(resultList)) {
            return "success";  //移出业务表不存在记录 通过
        }
        //业务表不空的情况下：
        for (TSBizSerIllegalRem bizSerIllegalRemModel : resultList) {
//            if ("3".equals(bizSerIllegalRemModel.getStatus())) {
//                return "success";  //移出业务表存在记录 --审批未通过状态→ 通过
//            }
            if ("1".equals(bizSerIllegalRemModel.getHandleStatus())) {
                return "该记录正在被移出";//存在待办中 处于经办或审查状态，不通过
            }else {
                return "success";
            }
        }

        //校验是否存在 异议待办
        TSBizSerIllegalDiss paramModel = new TSBizSerIllegalDiss();
        paramModel.setIllegalListID(illegallistid);
        List<TSBizSerIllegalDiss> tsBizDissentList = tsBizSerIllegalDissService.selectbizDissentList(paramModel);
        if (CollectionUtils.isNotEmpty(tsBizDissentList)) {
            for (TSBizSerIllegalDiss bizSerIllegalDissModel : tsBizDissentList) {
                List<TSTaskList> tsTaskListModels = taskListService.selectByBizSeqID(bizSerIllegalDissModel.getBizSeq());
                for (TSTaskList tsTaskListModel : tsTaskListModels) {
                    if (BaseDataConstant.BUSINESS_STATUS_TRANSACT.equals(tsTaskListModel.getBusstatus())) {
                        return "该记录正在进行异议业务";
                    }
                }
            }
        }
        return "success";
    }

    /**
     * 通过主体pripid创建严重违法失信企业移出业务（信用修复业务）
     *
     * @param pripid  主体pripid
     * @param request 请求信息
     * @return 获取
     * @author lroyia
     * @since 2021年3月25日 16:42:34
     */
    @Transactional
    @ApiOperation("创建信用修复移出任务")
    @PostMapping("createCreditRepairTaskByPripid")
    public RestResult<?> createCreditRepairTaskByPripid(HttpServletRequest request, @ApiParam("主体数据pripid") String pripid) {
        AssertUtils.isNotBlank(pripid);
        OpLogUtil.modifyLog(OpPositionEnum.CREDIT_REPAIR_TASK_CREATE, MapUtils.buildMap("pripid", pripid).build());

        // 列入信息查询
        List<TSSerIllegalList> serIllegalLists = tsSerIllegalListService.list(new LambdaQueryWrapper<TSSerIllegalList>()
                .eq(TSSerIllegalList::getPripid, pripid)
                .orderByDesc(TSSerIllegalList::getAbntime));

        // 列入信息校验主体状态
        if (CollectionUtils.isEmpty(serIllegalLists)) {
            log.error("通过主体pripid：{}创建严重违法失信企业移出业务（信用修复业务）时，找不到列入记录", pripid);
            throw new BusinessException("找不到列入记录");
        }
        TSSerIllegalList latestRecord = serIllegalLists.get(0);
        // TODO:业务状态校验，暂时只通过移出日期校验是否已移出，理论上应该还要检查移出业务表，确定业务是否已经被创建
        if (latestRecord.getRemdate() != null) {
            throw new BusinessException("主体状态错误");
        }

        // 调用移出接口，发起移出业务
        return approvalnext(request, new TSTaskList(), latestRecord.getIllegallistid(), "credit");
    }

    /**
     * 启动流程下一步
     */
    @Transactional
    @RequestMapping(value = "/next.do")
    public RestResult<?> approvalnext(HttpServletRequest request, TSTaskList taskListModel, String illegallistids, String type) {
//        AICUser user = (AICUser) request.getSession().getAttribute(ConstantsUtil.USER_SESSION_NAME);
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {
            String bizseq = UUID.randomUUID().toString();

            List<TSBizSerIllegalRem> bizRemList = new ArrayList<>();
            String[] illegallistidArr = illegallistids.split(";");
            String decorgCode = aicorgService.getRegionCodeByUser(user);
            for (String illegallistid : illegallistidArr) {
                //添加到 移出业务表
                TSSerIllegalList tsSerIllegalListModel = tsSerIllegalListService.getById(illegallistid);

                //添加的是同一条业务前修改之前的移除业务状态
                Map<String,Object> parambizRem = new HashMap<>();
                parambizRem.put("illegalListID",tsSerIllegalListModel.getIllegallistid());
                parambizRem.put("priPid",tsSerIllegalListModel.getPripid());
                List<TSBizSerIllegalRem> bizSerIllegalRemList = tsBizSerIllegalRemService.selectbizRemByPriPid(parambizRem);
                if (bizSerIllegalRemList.size()>0){
                    for (int i = 0; i < bizSerIllegalRemList.size(); i++) {
                        bizSerIllegalRemList.get(i).setHandleStatus("5");
                        tsBizSerIllegalRemService.saveOrUpdate(bizSerIllegalRemList.get(i));
                    }
                }

                TSBizSerIllegalRem tsBizSerIllegalRemModel = new TSBizSerIllegalRem();
                tsBizSerIllegalRemModel.setBizSeq(bizseq);
                tsBizSerIllegalRemModel.setIllegalListID(tsSerIllegalListModel.getIllegallistid());
                tsBizSerIllegalRemModel.setPriPID(tsSerIllegalListModel.getPripid());
                tsBizSerIllegalRemModel.setRegNO(tsSerIllegalListModel.getRegno());
                tsBizSerIllegalRemModel.setEntName(tsSerIllegalListModel.getEntname());
                tsBizSerIllegalRemModel.setSerIllRea(tsSerIllegalListModel.getSerillrea());
                tsBizSerIllegalRemModel.setAbnTime(tsSerIllegalListModel.getAbntime());

                tsBizSerIllegalRemModel.setDecOrg(decorgCode);
                tsBizSerIllegalRemModel.setAreaCode(decorgCode);
                tsBizSerIllegalRemModel.setApplyTime(LocalDateTime.now());
                tsBizSerIllegalRemModel.setAppOrPc("1");
                tsBizSerIllegalRemModel.setHandleStatus("1");
                //01-依申请移出，02-期限届满移出, 03-信用修复移出
                if ("apply".equals(type)) {
                    tsBizSerIllegalRemModel.setRemType("01");
                } else if ("timeout".equals(type)) {
                    tsBizSerIllegalRemModel.setRemType("02");
                } else if ("credit".equals(type)) {
                    tsBizSerIllegalRemModel.setRemType("03");
                }
                bizRemList.add(tsBizSerIllegalRemModel);
            }

            //添加待办
            taskListModel.setBizseqid(bizseq);
            if ("credit".equals(type)) {
                taskListModel.setBustype(BaseDataConstant.CREDIT_REPAIR_ILLEGAL_BIZ);
            } else {
                taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_REMOVE);//移出严重违法失信
            }
            StringBuffer entName = new StringBuffer("");
            for (int i = 0; i < bizRemList.size(); i++) {
                if (i > 1) {
                    entName.append("等企业");
                    break;
                }
                if (i > 0) entName.append(",");
                entName.append(bizRemList.get(i).getEntName());
            }
            taskListModel.setBusname(entName.toString());
            taskListModel = tsBizSerIllegalRemService.saveSerListStart(user, taskListModel, bizRemList);
        }

        TSTaskList taskListModel1 = taskListService.selectByTasklistID(taskListModel.getTasklistid());
        List<TSBizSerIllegalRem> list = tsBizSerIllegalRemService.selectbizRembizseq(taskListModel1.getBizseqid());
        if (CollectionUtils.isNotEmpty(list)) {
            StringBuffer pripids = new StringBuffer();
            for (TSBizSerIllegalRem bizSerIllegalRemModel : list) {
                if (pripids.length() > 0) pripids.append(";");
                pripids.append(bizSerIllegalRemModel.getPriPID());
            }
            TSBizSerIllegalRem tsBizSerIllegalRemModel = list.get(0);
            if ("01".equals(tsBizSerIllegalRemModel.getRemType())) {
                type = "apply";
            } else if ("02".equals(tsBizSerIllegalRemModel.getRemType())) {
                type = "timeout";
            } else if ("03".equals(tsBizSerIllegalRemModel.getRemType())) {
                type = "credit"; // 信用修复移出
            }
            resultMap.put("type", type);// 申请移出type=apply 或是 期限届满移出type=timeout
            resultMap.put("tsBizSerIllegalRemModel", tsBizSerIllegalRemModel);
            resultMap.put("ReconsiderationOrg", list.get(0).getReconsiderationOrg());
            resultMap.put("GovernmentOrg", list.get(0).getGovernmentOrg());
            resultMap.put("LitiOrg", list.get(0).getLitiOrg());
            resultMap.put("pripids", pripids);
        }

        List<SequenceFlowModel> nextSequenceFlowList = workFlowService.findNextSequenceFlowList(taskListModel1.getWorkflowid());
        TSTwfProcessNode currentNode = workFlowService.findCurrentNode(taskListModel1.getWorkflowid());
        String opinionType = BaseDataConstant.getOpinionTypeByWorkFlowNode(currentNode.getCurrentnode());
        if (opinionType == null) opinionType = "1";
        resultMap.put("opinionList", opinionService.selectByAuditingID(taskListModel1.getWorkflowid()));
        resultMap.put("nextSequenceFlowList", nextSequenceFlowList);
        resultMap.put("tasklistid", taskListModel1.getTasklistid());
        resultMap.put("bizSeq", taskListModel1.getBizseqid());
        resultMap.put("workflowId", taskListModel1.getWorkflowid());
        resultMap.put("currentNode", currentNode.getCurrentnode());
        resultMap.put("currentLinkTypeID", opinionType);
        resultMap.put("currentNodeName", WorkFlowUtil.getNodeName(currentNode.getCurrentnode()));
        return RestResult.ok(resultMap);
    }

    /**
     * 转办
     */
    @Transactional
    @RequestMapping(value = "/serIllegalRemTransfer.do")
    public RestResult<?> serIllegalRemTransfer(HttpServletRequest request, String bizSerRemID,
                                               String tasklistid, String transferOrg, String opinion){
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        Map<String, Object> resultMap = new HashMap<>();

        if (org.apache.commons.lang.StringUtils.isBlank(bizSerRemID)){
            resultMap.put("flag","error");
            resultMap.put("msg","业务主体为空！");
            return RestResult.ok(resultMap);
        }

        TSBizSerIllegalRem tsBizSerIllegalRemModel = tsBizSerIllegalRemService.getById(new TSBizSerIllegalRem().setBizSerRemID(bizSerRemID));
        if (tsBizSerIllegalRemModel == null || StringUtils.isBlank(tsBizSerIllegalRemModel.getBizSeq())){
            resultMap.put("flag","error");
            resultMap.put("msg","业务主体为空！");
            return RestResult.ok(resultMap);
        }

        if (StringUtils.isBlank(transferOrg)){
            resultMap.put("flag","error");
            resultMap.put("msg","需转办机关为空！");
            return RestResult.ok(resultMap);
        }

        if (StringUtils.isBlank(tasklistid)){
            resultMap.put("flag","error");
            resultMap.put("msg","待办记录为空");
            return RestResult.ok(resultMap);
        }

        //查找需要转办所的userid
        List<AICUser> userList = orgUM.findUsersByOrgAndPermission(orgUM.findOrgByRegion(transferOrg).getPrimaryKey(), "illegalRemoveAccept");
        if (CollectionUtils.isEmpty(userList)){
            resultMap.put("flag","error");
            resultMap.put("msg","转办机关没有人有经办权限");
            return RestResult.ok(resultMap);
        }

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

            //生成新业务号，更新列严表的移出业务号
            String bizseqUp = UUID.randomUUID().toString();

            if (CollectionUtils.isNotEmpty(tsTaskLists)) {
                for (int i = 0; i < tsTaskLists.size(); i++) {
                    //清空待办表tstasklist
                    TSTaskList task = tsTaskLists.get(i);
                    task.setBusstatus(BaseDataConstant.BUSINESS_STATUS_XYXF_END);
                    taskListService.updateById(task);

                    //清空业务表tsbizserillegalrem
                    AICUser user1 = orgUM.findUserByPrimaryKey(task.getSignuserid());
                    LambdaQueryWrapper<TSBizSerIllegalRem> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TSBizSerIllegalRem::getBizSeq, task.getBizseqid())
                            .eq(TSBizSerIllegalRem::getRemSponsorIllegal, user1.getEname());
                    TSBizSerIllegalRem serIllegalRemDB = tsBizSerIllegalRemService.getOne(queryWrapper);
                    if (serIllegalRemDB != null) {
                        serIllegalRemDB.setBizSeq("");
                        tsBizSerIllegalRemService.updateById(serIllegalRemDB);
                    }
                }
            } else {
                resultMap.put("flag","error");
                resultMap.put("msg","没有待办记录！");
                return RestResult.ok(resultMap);
            }

            LambdaQueryWrapper<TSTaskList> taskWrapper = new LambdaQueryWrapper<>();
            taskWrapper.eq(TSTaskList::getTasklistid, tasklistid);
            TSTaskList taskListModel = taskListService.getOne(taskWrapper);

            //新建业务和待办记录
            for (int z = 0; z < userList.size(); z++) {
                String decorgCode = aicorgService.getRegionCodeByUser(user);
                List<TSBizSerIllegalRem> bizRemList = new ArrayList<TSBizSerIllegalRem>();

                TSSerIllegalList tsSerIllegalListModel = tsSerIllegalListService.getById(tsBizSerIllegalRemModel.getIllegalListID());
                tsSerIllegalListModel.setYcbizseq(bizseqUp);
                tsSerIllegalListService.saveOrUpdate(tsSerIllegalListModel);

                TSBizSerIllegalRem newRemModel = new TSBizSerIllegalRem();
                newRemModel.setBizSeq(bizseqUp);
                newRemModel.setIllegalListID(tsSerIllegalListModel.getIllegallistid());
                newRemModel.setPriPID(tsSerIllegalListModel.getPripid());
                newRemModel.setRegNO(tsSerIllegalListModel.getRegno());
                newRemModel.setEntName(tsSerIllegalListModel.getEntname());
                newRemModel.setSerIllRea(tsSerIllegalListModel.getSerillrea());
                newRemModel.setAbnTime(tsSerIllegalListModel.getAbntime());
                newRemModel.setLauptime(LocalDateTime.now());
                newRemModel.setApplyTime(tsBizSerIllegalRemModel.getApplyTime());
                newRemModel.setDecOrg(decorgCode);
                newRemModel.setAreaCode(decorgCode);
                newRemModel.setApplicant(tsBizSerIllegalRemModel.getApplicant());
                newRemModel.setApplicantNo(tsBizSerIllegalRemModel.getApplicantNo());
                newRemModel.setApplicantId(tsBizSerIllegalRemModel.getApplicantId());
                newRemModel.setCerno(tsBizSerIllegalRemModel.getCerno());
                newRemModel.setAppOrPc("0");//移动端0，pc端1
                newRemModel.setHandleStatus("1");
                newRemModel.setRemType(tsBizSerIllegalRemModel.getRemType());
                bizRemList.add(newRemModel);

                TSTaskList newTaskModel = new TSTaskList();
                newTaskModel.setBizseqid(bizseqUp);
                newTaskModel.setBustype(taskListModel.getBustype());
                newTaskModel.setBusname(taskListModel.getBusname());

                //新建业记录和待办记录，新建流程节点
                newTaskModel = tsBizSerIllegalRemService.saveSerListStart(userList.get(z), newTaskModel, bizRemList);

                newTaskModel.setSenderuserid("");
                newTaskModel.setSenderorgid("");
                newTaskModel.setSendername(tsBizSerIllegalRemModel.getApplicant());
                taskListService.updateById(newTaskModel);

                //新建业务办理期限
                deadlinestasService.init(newTaskModel.getWorkflowid(), LocalDate.now());
            }

            //更新移动端上传附件的bizseq
            LambdaQueryWrapper<TSAttachment> attachWapper = new LambdaQueryWrapper<>();
            attachWapper.eq(TSAttachment::getBizseq, tsBizSerIllegalRemModel.getBizSeq())
                    .in(TSAttachment::getAttachtype,
                            new String[] { WorkNoUtil.ABN_WORKNOTYPE_1,
                                    WorkNoUtil.SER_WORKNOTYPE_1,
                                    WorkNoUtil.SER_WORKNOTYPE_2,
                                    WorkNoUtil.SER_WORKNOTYPE_3,
                                    WorkNoUtil.SER_WORKNOTYPE_6,
                                    WorkNoUtil.SER_WORKNOTYPE_8,
                                    WorkNoUtil.SER_WORKNOTYPE_7,
                                    WorkNoUtil.SER_WORKNOTYPE_4});
            List<TSAttachment> tsAttachments = attachmentService.list(attachWapper);
            if (tsAttachments.size() > 0) {
                for (int i = 0; i < tsAttachments.size(); i++) {
                    tsAttachments.get(i).setBizseq(bizseqUp);
                    attachmentService.saveOrUpdate(tsAttachments.get(i));
                }
            }

            // 存在转办记录的话，要更新转办记录的流程节点id
            LambdaQueryWrapper<TSOpinion> opinionWrapper = new LambdaQueryWrapper<>();
            opinionWrapper.eq(TSOpinion::getBizseq, tsBizSerIllegalRemModel.getBizSeq())
                    .eq(TSOpinion::getOpiniontype, "55");
            List<TSOpinion> tsOpinions = opinionService.list(opinionWrapper);
            if (CollectionUtils.isNotEmpty(tsOpinions)) {
                for (TSOpinion each : tsOpinions) {
                    each.setBizseq(bizseqUp);
                    opinionService.updateById(each);
                }
            }

            //保存转办意见
            opinionService.save(new TSOpinion().setBizseq(bizseqUp)
                    .setOpiniontype("55")
                    .setHandler(user.getName())
                    .setHandlerid((user.getPrimaryKey()))
                    .setOperOpinion(opinion)
                    .setHandledate(LocalDateTime.now()));

            resultMap.put("bizseq", bizseqUp);
        }catch (Exception e){
            e.printStackTrace();
            resultMap.put("flag","error");
            return RestResult.ok(resultMap);
        }

        resultMap.put("flag","success");
        return RestResult.ok(resultMap);
    }

    /**
     * 审批流程
     */
    @Transactional
    @RequestMapping(value = "/serIllegalNext.do")
    public RestResult<?> serIllegalNext(HttpServletRequest request, Model model, TSBizSerIllegalRem tsBizSerIllegalRemModel, TSOpinion opinionModel, String tasklistid,
                                        String nextPerformerids, String nextPerformerNames, String nextNodeID) {
//        AICUser user = (AICUser) request.getSession().getAttribute(ConstantsUtil.USER_SESSION_NAME);
        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 = tsBizSerIllegalRemService.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 = tsBizSerIllegalRemService.getOne(queryWrapper);
                                    if (serIllegalRemDB != null) {
                                        serIllegalRemDB.setBizSeq("");
                                        tsBizSerIllegalRemService.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 = tsBizSerIllegalRemService.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());// 移出主办人(账号)
                    }
                }
//                if (FlowUtil.SERILLEGALWORKFLOW_OVERSERILLEGAL.equals(nextNodeID)){
//                    bizSerIllegalRemModel.setIsAccept(tsBizSerIllegalRemModel.getIsAccept());
//                    bizSerIllegalRemModel.setBackProposal(tsBizSerIllegalRemModel.getBackProposal());
//
//                }
            }
            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 = tsBizSerIllegalRemService.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 = iGzaiccodeService.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());
                            }
                        }
                    }
                    // 重新设置业务表为未认领状态
//                    tsBizSerIllegalRem.setRemSponsorIllegal(null);
//                    tsBizSerIllegalRem.setLauptime(now);
//                    tsBizSerIllegalRemService.updateById(tsBizSerIllegalRem);
                }
            }
            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);
    }


    /**
     * 打印文书页面
     */
    @RequestMapping(value = "/printTSWrit.do")
    public RestResult<?> printTSWrit(String printstatus, TSBizSerIllegalRem tsBizSerIllegalRemModel, String workflowid) {
        Map<String, Object> resultMap = new HashMap<>();
        if ("1".equals(printstatus)) {//决定书打印
            tsBizSerIllegalRemModel = tsBizSerIllegalRemService.getById(tsBizSerIllegalRemModel.getBizSerRemID());
            TSWrit writQueryModel = new TSWrit();
            writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_25);
            writQueryModel.setPripid(tsBizSerIllegalRemModel.getPriPID());
            writQueryModel.setBizseq(tsBizSerIllegalRemModel.getBizSeq());
            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
            }
            resultMap.put("tsBizSerIllegalRemModel", tsBizSerIllegalRemModel);
            resultMap.put("ReconsiderationOrgInfo", tsBizSerIllegalRemModel.getReconsiderationOrg()); // 回显文书 行政复议机关
            resultMap.put("nowTime", LocalDate.now());
            if ("01".equals(tsBizSerIllegalRemModel.getRemType()) || "03".equals(tsBizSerIllegalRemModel.getRemType())) {
                return RestResult.ok(resultMap);
            }

        } else if ("3".equals(printstatus)) {//审批表打印
            TSTaskList taskListModel = taskListService.selectByWorkflowID(workflowid);
            StringBuffer regno = new StringBuffer();
            StringBuffer ename = new StringBuffer();
            List<TSBizSerIllegalRem> list = tsBizSerIllegalRemService.selectbizRembizseq(taskListModel.getBizseqid());
            if (CollectionUtils.isNotEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    if (i > 2) {
                        regno.append("等");
                        ename.append("等企业");
                        break;
                    }
                    if (i > 0) {
                        ename.append(", ");
                        regno.append(", ");
                    }
                    ename.append(list.get(i).getEntName());
                    regno.append(list.get(i).getRegNO());
                }
            }
            List<TSOpinion> opinionList = opinionService.selectByAuditingID(workflowid);
            resultMap.put("opinionList", opinionList);
            resultMap.put("decorgString", list.get(0).getDecOrg());
            resultMap.put("regno", regno);
            resultMap.put("ename", ename);
            resultMap.put("lostCreditExplainrem", list.get(0).getLostCreditExplainrem());
            resultMap.put("remtype", list.get(0).getRemType());
            resultMap.put("list", list);
            //届满日期
            resultMap.put("expirationDate", list.get(0).getAbnTime().plusYears(5));
        } else if ("4".equals(printstatus)) { //申请受理回执单打印
            TSWrit writQueryModel = new TSWrit();
            writQueryModel.setPripid(tsBizSerIllegalRemModel.getPriPID());
            writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_26);
            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
            }
            tsBizSerIllegalRemModel = tsBizSerIllegalRemService.getById(tsBizSerIllegalRemModel.getBizSerRemID());
            resultMap.put("tsBizSerIllegalRemModel", tsBizSerIllegalRemModel);
            resultMap.put("nowTime", LocalDate.now());
        }
        return RestResult.ok(resultMap);
    }

    /**
     * 查严重违法失信移出业务表
     */
    @RequestMapping(value = "/selectbizRemlist.do", method = RequestMethod.POST)
    public RestResult<?> selectbizRemlist(TSBizSerIllegalRem tsBizSerIllegalRemModel, int rows, int page) {
        return RestResult.ok(tsBizSerIllegalRemService.selectbizRemlist(rows, page, tsBizSerIllegalRemModel));
    }

    /**
     * 继续添加 移出主体信息
     */
    @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);

        TSSerIllegalList serIllegalListModel = new TSSerIllegalList();
        serIllegalListModel.setRegno(regno);
        serIllegalListModel.setEntname(entname);
//        serIllegalListModel.setDecorg(aicUser.getRegionID());//只查询 本机构做出决定的记录
        IPage<TSSerIllegalList> dataGrid = tsSerIllegalListService.selectTSSerIllegalList(3, 1, serIllegalListModel, type);
        if (CollectionUtils.isEmpty(dataGrid.getRecords())) {
            return RestResult.error(ResultCode.DATA_NONE);
        } else {
            serIllegalListModel = dataGrid.getRecords().get(0);
        }

        if (serIllegalListModel != null && StringUtils.isNotBlank(serIllegalListModel.getIllegallistid())) {
            TSBizSerIllegalRem bizRemModel = new TSBizSerIllegalRem();
            bizRemModel.setBizSeq(bizseq);
            bizRemModel.setIllegalListID(serIllegalListModel.getIllegallistid());
            List<TSBizSerIllegalRem> bizRemModelList = tsBizSerIllegalRemService.selectBRMserIllegalList(bizRemModel);
            if (CollectionUtils.isEmpty(bizRemModelList)) {//避免重复增加
                String validateResult = this.validate(serIllegalListModel.getIllegallistid());
                if ("success".equals(validateResult)) {
                    TSBizSerIllegalRem tsBizSerIllegalRemModel = new TSBizSerIllegalRem();
                    tsBizSerIllegalRemModel.setBizSeq(bizseq);
                    tsBizSerIllegalRemModel.setIllegalListID(serIllegalListModel.getIllegallistid());
                    tsBizSerIllegalRemModel.setPriPID(serIllegalListModel.getPripid());
                    tsBizSerIllegalRemModel.setRegNO(serIllegalListModel.getRegno());
                    tsBizSerIllegalRemModel.setEntName(serIllegalListModel.getEntname());
                    tsBizSerIllegalRemModel.setSerIllRea(serIllegalListModel.getSerillrea());
                    tsBizSerIllegalRemModel.setAbnTime(serIllegalListModel.getAbntime());
                    tsBizSerIllegalRemModel.setDecOrg(aicUser.getRegionID());
                    if ("apply".equals(type)) {  //01-依申请移出，02-期限届满移出
                        tsBizSerIllegalRemModel.setRemType("01");
                    } else if ("timeout".equals(type)) {
                        tsBizSerIllegalRemModel.setRemType("02");
                    } else if ("credit".equals(type)) {
                        tsBizSerIllegalRemModel.setRemType("03");
                    }
                    tsBizSerIllegalRemService.saveOrUpdate(tsBizSerIllegalRemModel);
                    return OK;
                } else {
                    throw new BusinessException(validateResult);
                }
            }
        }
        throw new BusinessException("无法查找到该主体信息，请确认查询条件或检查是否已在列表中");
    }

    /**
     * 删除 待移出信息
     */
    @RequestMapping(value = "/delSerIllegal.do", method = RequestMethod.POST)
    public RestResult<?> delSerIllegal(String bizserremid) {
        tsBizSerIllegalRemService.removeById(bizserremid);
        return OK;
    }

    /**
     * 可移出违法企业分页
     *
     * @param pageRequestDto 分页参数
     * @return 分页结果
     * @author lroyia
     * @since 2021年3月11日 09:27:04
     */
    @ApiOperation("可移出违法企业分页")
    @PostMapping("removable/commonPage")
    public RestResult<?> removableCompanyPage(@ApiParam("常规参数") @RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AssertUtils.isNotNull(pageRequestDto);
        pageRequestDto.checkDefault(1, 10, "abntime");
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        return RestResult.ok(tsSerIllegalListService.defaultPaging(pageRequestDto, w -> {
            LambdaQueryWrapper<TSSerIllegalList> wrapper = w.lambda();
            Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
            if(customParamMap == null) return;
            String abntime = StringUtils.tranObject(customParamMap.get("abntime"));
            if(StringUtils.isNotBlank(abntime)){
                wrapper.ge(TSSerIllegalList::getAbntime, abntime.split(",")[0]);
                wrapper.le(TSSerIllegalList::getAbntime, abntime.split(",")[1]);
            }
            wrapper.eq(TSSerIllegalList::getOperationStatus,"0");
            String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
            if(StringUtils.isNotBlank(searchUscc)){
                //判断入参为统一码还是注册号
                if(StringUtils.isUscc(searchUscc)){
                    LambdaQueryWrapper<EBaseinfo> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.select(EBaseinfo::getPripid).eq(EBaseinfo::getUniscid,searchUscc);
                    EBaseinfo baseinfo = eBaseinfoService.getOne(queryWrapper, false);
                    wrapper.eq(TSSerIllegalList::getPripid,baseinfo.getPripid());
                }else {
                    wrapper.eq(TSSerIllegalList::getRegno,searchUscc);
                }
            }
//            wrapper.isNotNull(TSSerIllegalList::getAbntime).isNull(TSSerIllegalList::getRemdate);
        }, each -> {
            TRBaseCode code = codeMap.get(each.getSerillrea());
            if (code != null) {
                each.setSerillreaString(code.getName());
            }
        }));
    }

    /**
     * 列出严重违法失信企业移出业务记录
     *
     * @param bizSeq 业务号
     * @return 查询结果
     * @author lroyia
     * @since 2021年3月11日 14:11:28
     */
    @ApiOperation("列出严重违法失信企业移出业务记录")
    @PostMapping("listIllegalRem")
    public RestResult<?> listIllegalRem(@ApiParam("业务号") String bizSeq) {
        Map rs = new HashMap();
        List<TSBizSerIllegalRem> list = tsBizSerIllegalRemService.list(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq, bizSeq));
        // 获取列入原因
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        Map<String, TRBaseCode> codeMap1 = baseCodeService.getBaseCodeMapFormCache("CD74");
        String creator = list.get(0).getRemSponsorIllegal();
        TUsers createUser = usersService.getOne(new LambdaQueryWrapper<TUsers>().eq(TUsers::getUsername, creator));
        list.forEach(each -> {
            EBaseinfo baseinfo = eBaseinfoService.getOneByPripid(each.getPriPID());
            each.setUniscid(baseinfo.getUniscid());
            rs.put("lerep",baseinfo.getLerep());
//            each.setCreatorName(createUser.getRealname());
            TRBaseCode code = codeMap.get(each.getSerIllRea());
            if (code != null) {
                each.setSerIllReaString(code.getName());
            }
            if (StringUtils.isNotBlank(each.getRemExcpRes())) {
                code = codeMap1.get(each.getRemExcpRes());
                if (code != null) {
                    each.setRemExcpResString(code.getName());
                }
            }
        });
        rs.put("tsbizserillegalrem",list);
        TSSerIllegalList tsSerIllegalList = tsSerIllegalListService.getById(list.get(0).getIllegalListID());
        if (StringUtils.isBlank(tsSerIllegalList.getDecorgCn())) {
            OrgUnits orgUnits = aicorgService.queryByOrgNumber(tsSerIllegalList.getDecorg());
            if (orgUnits != null) {
                tsSerIllegalList.setDecorgCn(orgUnits.getOrgUnitName());
            }
        }
        rs.put("tsSerIllegalList",tsSerIllegalList);

        //获取转办记录
        LambdaQueryWrapper<TSOpinion> opinionWrapper = new LambdaQueryWrapper<>();
        opinionWrapper.eq(TSOpinion::getBizseq, list.get(0).getBizSeq())
                .eq(TSOpinion::getOpiniontype, "55")
                .orderByAsc(TSOpinion::getHandledate);
        List<TSOpinion> tsOpinions = opinionService.list(opinionWrapper);
        List<String> orgName = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(tsOpinions)) {
            for(TSOpinion each : tsOpinions){
                AICUser user = orgUM.findUserByPrimaryKey(each.getHandlerid());
                orgName.add(user.getOrgName());
            }
            rs.put("tranferRecord",tsOpinions);
            rs.put("orgName",orgName);
        }
//        if (list.get(0).getAppOrPc() == "0"){
//
//        }
        return RestResult.ok(rs);
    }

    @PostMapping("listIllegalRemByName")
    public RestResult<?> listIllegalRemByName(String bizSeq, String entName) {
        List<TSBizSerIllegalRem> list = tsBizSerIllegalRemService.list(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq, bizSeq)
                .like(StringUtils.isNotBlank(entName),TSBizSerIllegalRem::getEntName,entName));
        // 获取列入原因
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        Map<String, TRBaseCode> codeMap1 = baseCodeService.getBaseCodeMapFormCache("CD74");
        String creator = list.get(0).getRemSponsorIllegal();
        TUsers createUser = usersService.getOne(new LambdaQueryWrapper<TUsers>().eq(TUsers::getUsername, creator));
        list.forEach(each -> {
//            each.setCreatorName(createUser.getRealname());
            TRBaseCode code = codeMap.get(each.getSerIllRea());
            if (code != null) {
                each.setSerIllReaString(code.getName());
            }
            if (StringUtils.isNotBlank(each.getRemExcpRes())) {
                code = codeMap1.get(each.getRemExcpRes());
                if (code != null) {
                    each.setRemExcpResString(code.getName());
                }
            }
        });
        return RestResult.ok(list);
    }

    /**
     * 通过移出业务记录id移出业务记录
     *
     * @param remIds 移出信息id，多个;号隔开
     * @return 移出结果
     * @author lroyia
     * @since 2021年3月11日 15:12:31
     */
    @ApiOperation("通过移出业务记录id移出业务记录")
    @PostMapping("removeByRemId")
    public RestResult<?> removeByRemId(@ApiParam("移出业务记录的id") String remIds) {
        tsBizSerIllegalRemService.remove(new LambdaQueryWrapper<TSBizSerIllegalRem>().in(TSBizSerIllegalRem::getBizSerRemID, remIds.split(Constant.SEMICOLON)));
        return OK;
    }

    /**
     * lwd
     * 信用修复移出前 信息验证
     * 2021-09-02
     */
    @RequestMapping(value = "/creditValidateBiz.do", method = RequestMethod.POST)
    public RestResult<?> creditValidateBiz(HttpServletRequest request, String illegallistids) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }

        Map<String, String> resultMap = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();
        //这一步进行判断，且允许上级办理下级的信用修复
        Map<String, String> map = new HashMap<>();
        map.put("orgNumber", aicUser.getRegionID());
        map.put("deleted", "0");
        map.put("unittype", "1");
        OrgUnits org = aicorgService.queryByOrgNumberMap(map);
        boolean isSame = true;

        if (org != null) {
            String[] illegallistidArr = illegallistids.split(Constant.SEMICOLON);
            for (String illegallistid : illegallistidArr) {
                TSSerIllegalList serIllegalListModel = tsSerIllegalListService.getById(illegallistid);
                Integer orgLevel = org.getOrgLevel();
                //根据机构等级判断
                if (orgLevel == 1) {    //省局
                    isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                            StringUtils.substring(aicUser.getRegionID(), 0, 2),
                            StringUtils.substring(serIllegalListModel.getDecorg(), 0, 2));
                } else if (orgLevel == 2) {    //市局
                    isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                            StringUtils.substring(aicUser.getRegionID(), 0, 4),
                            StringUtils.substring(serIllegalListModel.getDecorg(), 0, 4));
                } else if (orgLevel == 3) {    //区局
                    isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                            StringUtils.substring(aicUser.getRegionID(), 0, 6),
                            StringUtils.substring(serIllegalListModel.getDecorg(), 0, 6));
                } else if (orgLevel >= 4) {    //所
                    isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                            StringUtils.substring(aicUser.getRegionID(), 0, 6),
                            StringUtils.substring(serIllegalListModel.getDecorg(), 0, 6));
                }

                if(!isSame){
                    resultMap.put("regno", serIllegalListModel.getRegno());
                    resultMap.put("entname", serIllegalListModel.getEntname());
                    resultMap.put("pripid", serIllegalListModel.getPripid());
                    resultMap.put("illegallistid", illegallistid);
                    resultMap.put("reason", "列入机关与当前用户所属机关不匹配！");
                    list.add(resultMap);
                    return RestResult.ok(list);
                }

                String validateResult = this.validate(illegallistid);
                int days = (int) ((int)LocalDate.now().toEpochDay() - serIllegalListModel.getAbntime().toEpochDay());
//            Period period = Period.between(serIllegalListModel.getAbntime(),LocalDate.now());
//            if(!"该记录正在被移出".equals(validateResult)){
//                if (days < 365){
//                    resultMap.put("reason", "企业需满足列入严重违法失信满1年才能发起严重违法信用修复流程，请重新选择");
//                    return RestResult.ok(resultMap);
//                }
//            }

                if (!"success".equals(validateResult)) {
                    resultMap.put("regno", serIllegalListModel.getRegno());
                    resultMap.put("entname", serIllegalListModel.getEntname());
                    resultMap.put("pripid", serIllegalListModel.getPripid());
                    resultMap.put("illegallistid", illegallistid);
                    resultMap.put("reason", validateResult);
                    list.add(resultMap);
                }
            }
        } else {
            return RestResult.error(ResultCode.MYSTERIOUS_ERROR, "当前用户所属机关不存在");
        }
        if (CollectionUtils.isNotEmpty(list)) return RestResult.ok(list);

        return OK;
    }

    /**
     * 严重违法信用修复回退至申请人
     * @param tasklistid     待办id
     * @param bizSeq         业务号
     * @param backProposal   回退原因
     * @return
     */
    @PostMapping("returnToApplyer")
    public RestResult<?> returnToApplyer(HttpServletRequest request,String tasklistid, String bizSeq,String backProposal,String handler,String handlerid){

        AssertUtils.isNotBlank(tasklistid,bizSeq);
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        //更新其他人待办状态
        LambdaQueryWrapper<TSTaskList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSTaskList::getBizseqid,bizSeq)
                .ne(TSTaskList::getBusstatus,BaseDataConstant.BUSINESS_STATUS_XYXF_END);
        List<TSTaskList> tsTaskLists = taskListService.list(wrapper);
        if(CollectionUtils.isNotEmpty(tsTaskLists)){

            boolean isExist = false;
            if (tsTaskLists.size() > 1) {
                for (int i = 0; i < tsTaskLists.size(); i++) {
                    if (aicUser.getPrimaryKey().equals(tsTaskLists.get(i).getSignuserid())) {
                        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("1");
                        taskListService.updateById(task);
                        AICUser user = orgUM.findUserByPrimaryKey(task.getSignuserid());

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

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

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

        List<TSBizSerIllegalRem> tsBizSerIllegalRemsNow = tsBizSerIllegalRemService.selectbizRembizseq(bizSeq);

//        TSBizSerIllegalRem tsBizSerIllegalRem = tsBizSerIllegalRemService.getOneByBizseq(bizSeq);
        TSBizSerIllegalRem tsBizSerIllegalRem = tsBizSerIllegalRemsNow.get(0);
        if(tsBizSerIllegalRem != null) {
            // 改变业务表状态.
            tsBizSerIllegalRem.setRemSponsorIllegal(aicUser.getEname());
            tsBizSerIllegalRem.setIsAccept("0");
            tsBizSerIllegalRem.setHandleStatus("2");
            tsBizSerIllegalRem.setApprovalDate(LocalDate.now());
            tsBizSerIllegalRem.setBackProposal(backProposal);
            boolean save1 = tsBizSerIllegalRemService.updateById(tsBizSerIllegalRem);
            // 改变待办状态
            TSTaskList taskList = taskListService.getById(tasklistid);
            taskList.setBusstatus(BaseDataConstant.BUSINESS_STATUS_RETURN_APPLY);
            taskList.setIsBack("1");
            boolean save2 = taskListService.updateById(taskList);
            // 回退原因保存到意见表
            TSOpinion tsOpinion = new TSOpinion();
            tsOpinion.setWorkflowid(taskList.getWorkflowid());
            tsOpinion.setHandlerid(handlerid);
            tsOpinion.setHandler(handler);
            tsOpinion.setOpiniontype("0");
            tsOpinion.setOpinioncontent(backProposal);
            tsOpinion.setIsagree("2");
            tsOpinion.setLauptime(LocalDateTime.now());
            if(tsOpinion.getHandledate() == null){
                tsOpinion.setHandledate(LocalDateTime.now());
            }
            boolean save3 = opinionService.save(tsOpinion);
            // 更新工作时限
            if(!save1 || !save2 || !save3) {
                if(!save1)  log.info("========更新业务表失败=========表名:tsbizserillegalrem=======bizSeq:{}==========={}",bizSeq,tsBizSerIllegalRem);
                if(!save2)  log.info("========更新待办表失败=========表名:tstasklist=========tasklistid:{}======={}",tasklistid,taskList);
                if(!save3)  log.info("========保存意见表失败=========表名:tsopinion============={}",tsOpinion);
                throw new BusinessException(ResultCode.BUSINESS_LOGIC_ERROR);
            }
            return RestResult.ok(true);
        }
        log.info("=======获取业务表为空=========表名:tsbizserillegalrem==========bizSeq：{}======tsBizSerIllegalRem:{}",bizSeq,tsBizSerIllegalRem);
        throw new BusinessException(ResultCode.BUSINESS_LOGIC_ERROR);
    }

    /**
     * 更新列严多余的待办和业务
     * @param bizSeq         业务号
     * @return
     */
    @PostMapping("deleTaskAndillRem")
    public RestResult<?> deleTaskAndillRem(HttpServletRequest request,String bizSeq){
        AICUser user = getLoginUser(request);


        try {

            //删除待办
            List<TSTaskList> tsTaskLists = taskListService.selectTaskListByBizseqid(bizSeq);
            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.remove(tsTaskLists.get(i));
                            isExist = true;
                            break;
                        }
                    }
                    if (isExist){
                        for (int i = 0; i < tsTaskLists.size(); i++) {
                            taskListService.removeById(tsTaskLists.get(i).getTasklistid());
                        }
                    }else {
                        throw new BusinessException("业务办理错误");
                    }

                }else {
                    if(tsTaskLists.size()>0 && user.getPrimaryKey().equals(tsTaskLists.get(0).getSignuserid())) {
                        throw new BusinessException("业务已在办理中");
                    }
                }
            }
            //删除移除业务
            List<TSBizSerIllegalRem> tsBizSerIllegalRem = tsBizSerIllegalRemService.selectbizRembizseq(bizSeq);
            if (CollectionUtils.isNotEmpty(tsBizSerIllegalRem)){
                boolean isExist = false;
                if (tsBizSerIllegalRem.size() > 1) {
                    for (int i = 0; i < tsBizSerIllegalRem.size(); i++) {
                        if (user.getPrimaryKey().equals(tsBizSerIllegalRem.get(i).getRemSponsorIllegal())) {
                            tsBizSerIllegalRem.remove(tsBizSerIllegalRem.get(i));
                            isExist = true;
                            break;
                        }
                    }
                    if (isExist){
                        for (int i = 0; i < tsBizSerIllegalRem.size(); i++) {
                            tsBizRemListService.removeById(tsBizSerIllegalRem.get(i).getBizSerRemID());
                        }
                    }else {
                        throw new BusinessException("业务办理错误");
                    }
                }else {
                    if(tsBizSerIllegalRem.size()>0 && !user.getPrimaryKey().equals(tsBizSerIllegalRem.get(0).getRemSponsorIllegal())) {
                        throw new BusinessException("业务在办理中");
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return OK;
    }


    /**
     * 更新经营异常多余的待办和业务
     * @param bizSeq         业务号
     * @return
     */
    @PostMapping("deleAbnTaskAndillRem")
    public RestResult<?> deleAbnTaskAndillRem(HttpServletRequest request,String bizSeq){
        AICUser user = getLoginUser(request);


        try {
            //删除待办
            List<TSTaskList> tsTaskLists = taskListService.selectTaskListByBizseqid(bizSeq);
            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.remove(tsTaskLists.get(i));
                            isExist = true;
                            break;
                        }
                    }
                    if (isExist){
                        for (int i = 0; i < tsTaskLists.size(); i++) {
                            taskListService.removeById(tsTaskLists.get(i).getTasklistid());
                        }
                    }else {
                        throw new BusinessException("业务办理错误");
                    }
                }else {
                    if(tsTaskLists.size()>0 && !user.getPrimaryKey().equals(tsTaskLists.get(0).getSignuserid())) {
                        throw new BusinessException("业务已在办理中");
                    }
                }
            }
            //删除移除业务
            List<TSBizRemList> tsBizSerIllegalRem = tsBizRemListService.selectbizRembizseq(bizSeq);
            if (CollectionUtils.isNotEmpty(tsBizSerIllegalRem)){
                boolean isExist = false;
                if (tsBizSerIllegalRem.size() > 1) {
                    for (int i = 0; i < tsBizSerIllegalRem.size(); i++) {
                        if (user.getPrimaryKey().equals(tsBizSerIllegalRem.get(i).getRemSponsorID())) {
                            tsBizSerIllegalRem.remove(tsBizSerIllegalRem.get(i));
                            isExist = true;
                            break;
                        }
                    }
                    if (isExist){
                        for (int i = 0; i < tsBizSerIllegalRem.size(); i++) {
                            tsBizRemListService.removeById(tsBizSerIllegalRem.get(i).getRemlistid());
                        }
                    }else {
                        throw new BusinessException("业务办理错误");
                    }

                }else {
                    if(tsBizSerIllegalRem.size()> 0 && !user.getPrimaryKey().equals(tsBizSerIllegalRem.get(0).getRemSponsorID())) {
                        throw new BusinessException("业务在办理中");
                    }
                }
            }


        }catch (Exception e){
            e.printStackTrace();
        }

        return OK;
    }

    /**
     * 批量审核/审核
     */
    @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 = () -> {
                TSBizSerIllegalRem tsBizSerIllegalRemModel=new TSBizSerIllegalRem();
                tsBizSerIllegalRemModel.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, null, tsBizSerIllegalRemModel, opinionModel, taskListUnionDto.getTasklistid(), finalNextPerformerids, finalNextPerformerNames, nextNodeID);
                countDownLatch.countDown();//减1
            };
            executorService.submit(runnable);
        }

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

    @RequestMapping("queryHistorgBizRemInfo")
    public RestResult<?> queryHistorgBizRemInfo(String SAPPROVECODE) {
        return tsBizSerIllegalRemService.queryHistorgBizRemInfo(SAPPROVECODE);
    }

    /**
     * 退回移动端后撤销业务
     * @param bizSeq
     * @return
     */
    @PostMapping("cancelBusiness")
    public RestResult<?> cancelBusiness(String bizSeq) {
        tsBizSerIllegalRemService.cancelBusiness(bizSeq);
        return RestResult.ok();
    }
}
