package com.chinaweal.aiccs.aiccs.abnormal.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.RemBatchVo;
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.market.entity.TSUsualInspect;
import com.chinaweal.aiccs.aiccs.market.service.ITSUsualInspectService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalRem;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalRemService;
import com.chinaweal.aiccs.aiccs.system.service.DeadlinestasService;
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.*;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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.util.*;
import java.util.concurrent.*;

/**
 * 异常名录移出接口
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/1/25 17:12
 **/
@RestController
@Transactional
@Slf4j
@RequestMapping("/bizRemList")
public class BizRemListController extends BaseController implements ServletContextListener {

    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSBizRemListService tsBizRemListService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private TSBizDissentService tsBizDissentService;
    @Autowired
    private TSBizAbnRevokeService tsbizAbnRevokeService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private AicorgService aicorgService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    private UuidUtil uuidUtil;
    @Autowired
    private GzaiccodeServiceImpl gzaiccodeService;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private DeadlinestasService deadlinestasService;
    @Autowired
    private TSBizSerIllegalRemService tsBizSerIllegalRemService;
    @Resource
    private ITSUsualInspectService iTSUsualInspectService;

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

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

    @Override
    public void contextInitialized(ServletContextEvent sce) {
    }

    /**
     * 查看待移出企业名单
     */
//    @PostMapping("/selectbizRemlist.do")
//    public RestResult<?> selectbizRemlist(TSBizRemList tsBizRemListModel, int pageSize, int currentPage){
//        return RestResult.ok(tsBizRemListService.selectbizRemlist(new Page<>(currentPage, pageSize), tsBizRemListModel));
//    }

    /**
     * 查看待移出企业信息及事实理由
     */
    @PostMapping("/getBizRemInfo")
    public RestResult<?> selectbizRemlist(String bizseq) {
        Map<String, Object> resultMap = new HashMap<>();
        QueryWrapper<TSBizRemList> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(StringUtils.isNotBlank(bizseq), TSBizRemList::getBizseq, bizseq);
        //待移出企业业务表
        List<TSBizRemList> bizRemLists = tsBizRemListService.list(wrapper);

        if (bizRemLists.size() > 0) {
            TSBizRemList bizRemListModel = bizRemLists.get(0);
            resultMap.put("bizRemListMOdel", bizRemListModel);
//            //获取业务移出原因
//            String remreasons = bizRemLists.get(0).getRemreasons();
//            resultMap.put("remreasons", remreasons);
//            // 移出备注
//            String remRemark = bizRemLists.get(0).getRemRemark();
//            resultMap.put("remRemark", remRemark);
            //遍历业务表中企业pripid
            List<String> pripids = new ArrayList<>();
            for (TSBizRemList bizRemList : bizRemLists) {
                pripids.add(bizRemList.getPripid());
            }

            LambdaQueryWrapper<EBaseinfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(EBaseinfo::getPripid, pripids);
            List<EBaseinfo> list = eBaseinfoService.list(queryWrapper);
            if (list.size() > 0) {
                resultMap.put("bizList", list);
            }
            TSAbnList tsAbnList = tsAbnListService.getById(bizRemListModel.getAbnlistid());
            resultMap.put("tsAbnList", tsAbnList);
        }

        //获取转办记录
        LambdaQueryWrapper<TSOpinion> opinionWrapper = new LambdaQueryWrapper<>();
        opinionWrapper.eq(TSOpinion::getBizseq, bizseq)
                .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());
            }
            resultMap.put("tranferRecord", tsOpinions);
            resultMap.put("orgName", orgName);
        }

        //查询是否有关联的现场核查
        TSUsualInspect tsUsualInspect = iTSUsualInspectService.getbyXyfxbizSeq(bizseq);
        if (tsUsualInspect != null) {
            if ("1".equals(tsUsualInspect.getStatus())) {
                resultMap.put("glflag", "1");
            }else {
                resultMap.put("glflag", "0");
            }
        }else {
            resultMap.put("glflag", "1");
        }

        return RestResult.ok(resultMap);

    }

    /**
     * 查看待移出企业信息及事实理由
     */
    @PostMapping("/selectHistorybizRemlist")
    public RestResult<?> selectHistorybizRemlist(String bizseq) {
        return tsBizRemListService.selectHistorybizRemlist(bizseq);
    }

    @PostMapping("checknb")
    public RestResult<?> checknb(String abnlistid) {
        TSAbnList tsaBnList = tsAbnListService.getById(abnlistid);
        LocalDate abntime = tsaBnList.getAbntime();
        int year = abntime.getYear();
        LocalDate boundary = LocalDate.of(year, 7, 1);
        int check = 0;
        Boolean isnb = false;
        if (abntime.isBefore(boundary)) { // 查两年前是否年报
            check = tsAbnListService.checknb(tsaBnList.getPripid(), String.valueOf(year - 2));
        } else {
            // 查去年是否年报
            check = tsAbnListService.checknb(tsaBnList.getPripid(), String.valueOf(year - 1));
        }
        if (check > 0) isnb = true;
        return RestResult.ok(isnb);
    }

    /**
     * 通过业务号id企业id删除业务表中待移出主体
     *
     * @param bizseq  业务号id
     * @param pripids 企业id
     * @return
     */
    @ApiOperation(value = "通过业务号id企业id删除业务表中待移出主体")
    @RequestMapping("remove_bizRemList_by_splistid")
    public RestResult<?> removeBizRemListBySplistid(String tasklistid, String bizseq, String pripids) {
        AssertUtils.isNotBlank(bizseq, pripids);
        String[] pripidArray = pripids.split(Constant.SEMICOLON);
        boolean isDelete = tsBizRemListService.remove(new LambdaQueryWrapper<TSBizRemList>().eq(TSBizRemList::getBizseq, bizseq).in(TSBizRemList::getPripid, pripidArray));
        if (isDelete) {
            //待办列表企业名称回显
            StringBuffer entname = new StringBuffer("");
            List<TSBizRemList> bizRemListModelList = tsBizRemListService.list(new LambdaQueryWrapper<TSBizRemList>().eq(TSBizRemList::getBizseq, bizseq));
            for (int i = 0; i < bizRemListModelList.size(); i++) {
                if (i > 1) {
                    entname.append("等企业");
                    break;
                } //要改
                if (i > 0) entname.append("、");
                entname.append(bizRemListModelList.get(i).getEntname());
            }
            TSTaskList taskListModel = new TSTaskList();
            taskListModel.setTasklistid(tasklistid);
            taskListModel.setBusname(entname.toString());
            taskListService.updateById(taskListModel);
            return OK;
        } else {
            return RestResult.error(ResultCode.MYSTERIOUS_ERROR, "数据库异常，删除失败");
        }
    }

    /**
     * 移出前 监管主体校验
     */
    @PostMapping("/validateBiz.do")
    public RestResult<?> validateBiz(HttpServletRequest request, String abnlistid) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");

        List<Map<String, String>> list = new ArrayList<>();
        TSAbnList tsAbnList = tsAbnListService.getById(abnlistid);

        //这一步进行判断，且允许上级办理下级的信用修复
        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) {
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(EBaseinfo::getPripid, tsAbnList.getPripid());
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
            Integer orgLevel = org.getOrgLevel();
            //主体的判断机关，如果没有属地就取登记机关
            String entOrg = StringUtils.isNotEmpty(eBaseinfo.getSuporg()) ? eBaseinfo.getSuporg() : eBaseinfo.getRegorg();
            //根据机构等级判断
            if (orgLevel == 1) {    //省局
                isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                        StringUtils.substring(aicUser.getRegionID(), 0, 2),
                        StringUtils.substring(entOrg, 0, 2));
            } else if (orgLevel == 2) {    //市局
                isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                        StringUtils.substring(aicUser.getRegionID(), 0, 4),
                        StringUtils.substring(entOrg, 0, 4));
            } else if (orgLevel == 3) {    //区局
                isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                        StringUtils.substring(aicUser.getRegionID(), 0, 6),
                        StringUtils.substring(entOrg, 0, 6));
            } else if (orgLevel >= 4) {    //所
                isSame = com.chinaweal.aiccs.common.util.StringUtils.equals(
                        StringUtils.substring(aicUser.getRegionID(), 0, 6),
                        StringUtils.substring(entOrg, 0, 6));
            }
        } else {
            return RestResult.error(ResultCode.MYSTERIOUS_ERROR, "当前用户所属机关不存在");
        }

        if(isSame){ //登记机关码值等于用户所在单位
            String validateResult = this.validate(abnlistid);
            if (!"success".equals(validateResult)) {
                TSAbnList tsAbnListModel = tsAbnListService.getById(abnlistid);
                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);
            }
        } else {
            Map<String, String> resultMap = new HashMap<String, String>();
            resultMap.put("regno", tsAbnList.getRegno());
            resultMap.put("entname", tsAbnList.getEntname());
            resultMap.put("pripid", tsAbnList.getPripid());
            resultMap.put("abnlistid", abnlistid);
            resultMap.put("reason", "属地机关与当前用户所属机关不匹配！");
            list.add(resultMap);
            return RestResult.ok(list);
        }
        return RestResult.ok(list);
    }

    /**
     * 移出前 监管主体校验方法
     */
    private String validate(String abnlistid) {
        //验证 移出经营异常名录业务表 是否存在
        TSBizRemList tsBizRemListModel = new TSBizRemList();
        tsBizRemListModel.setAbnlistid(abnlistid);
        List<TSBizRemList> resultList = tsBizRemListService.selectBRMexptlist(tsBizRemListModel);
//        if (CollectionUtils.isEmpty(resultList)) {
//            return "success";//不存在，通过
//        }


        if (CollectionUtils.isNotEmpty(resultList)) {
            //业务表不空的情况下：
            for (TSBizRemList bizRemListModel : resultList) {
                List<TSTaskList> tsTaskListModels = taskListService.selectByBizSeqID(bizRemListModel.getBizseq());
                for (TSTaskList tsTaskListModel : tsTaskListModels) {
                    if (BaseDataConstant.BUSINESS_STATUS_TRANSACT.equals(tsTaskListModel.getBusstatus())) { //存在待办未办结
                        return "该记录正在进行移出业务";
                    }
                }
            }
        }

        //校验是否存在 异议待办
        TSBizDissent bizDissentModel = new TSBizDissent();
        bizDissentModel.setAbnlistid(abnlistid);
        List<TSBizDissent> tsBizDissentList = tsBizDissentService.selectbizDissentList(bizDissentModel);
        if (CollectionUtils.isNotEmpty(tsBizDissentList)) {
            for (TSBizDissent tsBizDissentModel : tsBizDissentList) {
                List<TSTaskList> tsTaskListModels = taskListService.selectByBizSeqID(tsBizDissentModel.getBizseq());
                for (TSTaskList tsTaskListModel : tsTaskListModels) {
                    if (BaseDataConstant.BUSINESS_STATUS_TRANSACT.equals(tsTaskListModel.getBusstatus())) { //存在待办未办结
                        return "该记录正在进行异议申请业务";
                    }
                }
            }
        }
/*
        //校验是否存在 撤销待办
        boolean b = tsbizAbnRevokeService.validateBizRevoke(abnlistid, BaseDataConstant.BUSINESS_TYPE_REVOKEABN);
        if (!b) throw new BusinessException("该记录正在进行撤销业务");

        //校验是否存在 修改待办
        List<TSTaskList> taskListModels = taskListService.selectByBizSeqID(abnlistid);
        for (TSTaskList taskListModel : taskListModels) {
            if (taskListModel.getBusstatus().equals(BaseDataConstant.BUSINESS_STATUS_TRANSACT)) { //存在修改待办  未办结
                throw new BusinessException("该记录正在进行修改业务");
            }
        }*/

        return "success";
    }

    /**
     * 转办
     */
    @Transactional
    @RequestMapping(value = "/abnRemTransfer.do")
    public RestResult<?> abnRemTransfer(HttpServletRequest request, String remlistid, String enttype,
                                        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 (StringUtils.isBlank(remlistid)) {
            resultMap.put("flag", "error");
            resultMap.put("msg", "业务主体为空！");
            return RestResult.ok(resultMap);
        }

        TSBizRemList tsBizRemListModel = tsBizRemListService.getById(new TSBizRemList().setRemlistid(remlistid));
        if (StringUtils.isBlank(tsBizRemListModel.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
        String permission;
        if ("9910".equals(enttype) || "9999".equals(enttype)) {
            //个体
            permission = "individualRecoverAccept";
        } else {
            //企业和农合
            permission = "exptRemoveEnter";
        }
        List<AICUser> userList = orgUM.findUsersByOrgAndPermission(orgUM.findOrgByRegion(transferOrg).getPrimaryKey(), permission);

        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, tsBizRemListModel.getBizseq())
                    .ne(TSTaskList::getBusstatus, BaseDataConstant.BUSINESS_STATUS_XYXF_END);
            List<TSTaskList> tsTaskLists = taskListService.list(wrapper);

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

            //清空待办表tstasklist
            if (CollectionUtils.isNotEmpty(tsTaskLists)) {
                for (int i = 0; i < tsTaskLists.size(); i++) {
                    TSTaskList task = tsTaskLists.get(i);
                    task.setBusstatus(BaseDataConstant.BUSINESS_STATUS_XYXF_END);
                    taskListService.updateById(task);
                }
            } else {
                resultMap.put("flag", "error");
                resultMap.put("msg", "没有待办记录！");
                return RestResult.ok(resultMap);
            }

            TSBizRemList newRemModel = new TSBizRemList();
            newRemModel.setBizseq(bizseqUp);
            newRemModel.setAbnlistid(tsBizRemListModel.getAbnlistid());
            newRemModel.setPripid(tsBizRemListModel.getPripid());
            newRemModel.setRegno(tsBizRemListModel.getRegno());
            newRemModel.setEntname(tsBizRemListModel.getEntname());
            newRemModel.setSpecause(tsBizRemListModel.getSpecause());
            newRemModel.setAbntime(tsBizRemListModel.getAbntime());
            newRemModel.setSpereasons(tsBizRemListModel.getSpereasons());
            newRemModel.setApplicant(tsBizRemListModel.getApplicant());
            newRemModel.setApplicantNo(tsBizRemListModel.getApplicantNo());
            newRemModel.setApplicantId(tsBizRemListModel.getApplicantId());
            newRemModel.setCerno(tsBizRemListModel.getCerno());
            newRemModel.setType(tsBizRemListModel.getType());
            newRemModel.setLauptime(LocalDateTime.now());
            newRemModel.setAppOrPc("0");//移动端
            newRemModel.setApplyTime(tsBizRemListModel.getApplyTime());
            newRemModel.setHandleStatus("1");
            List<TSBizRemList> bizRemListModelList = new ArrayList<TSBizRemList>();
            bizRemListModelList.add(newRemModel);

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

            //新建待办记录
            for (int z = 0; z < userList.size(); z++) {
                TSTaskList newTaskModel = new TSTaskList();
                newTaskModel.setBizseqid(bizseqUp);
                newTaskModel.setBustype(taskListModel.getBustype());
                newTaskModel.setBusname(taskListModel.getBusname());

                //新建业记录和待办记录，新建流程节点
                newTaskModel = tsBizRemListService.saveAbnListStart(userList.get(z), newTaskModel, bizRemListModelList);
                //移动端过来的数据要更新为申请人的信息
                newTaskModel.setSenderuserid("");
                newTaskModel.setSenderorgid("");
                newTaskModel.setSendername(tsBizRemListModel.getApplicant());
                taskListService.updateById(newTaskModel);

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

            //更新移动端上传附件的bizseq
            LambdaQueryWrapper<TSAttachment> attachWapper = new LambdaQueryWrapper<>();
            attachWapper.eq(TSAttachment::getBizseq, tsBizRemListModel.getBizseq())
                    .in(TSAttachment::getAttachtype,
                            new String[]{WorkNoUtil.ABN_WORKNOTYPE_1,
                                    WorkNoUtil.ABN_WORKNOTYPE_8,
                                    WorkNoUtil.ABN_WORKNOTYPE_7,
                                    WorkNoUtil.ABN_WORKNOTYPE_9,
                                    WorkNoUtil.ABN_WORKNOTYPE_2,
                                    WorkNoUtil.ABN_WORKNOTYPE_3,
                                    WorkNoUtil.ABN_WORKNOTYPE_88,
                                    WorkNoUtil.ABN_WORKNOTYPE_4,
                                    WorkNoUtil.ABN_WORKNOTYPE_99});
            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, tsBizRemListModel.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()));

            //清空业务表tsbizremlist
            tsBizRemListModel.setBizseq("");
            tsBizRemListModel.setHandleStatus("5");
            tsBizRemListService.updateById(tsBizRemListModel);

            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);
    }

    /**
     * 异常移出审核审批流程
     */
    @PostMapping(value = "/bizRemoveNext")
    public RestResult<?> bizRemoveNext(HttpServletRequest request, TSBizRemList tsBizRemListModel, TSOpinion opinionModel,
                                       String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID, String entertype) {
        AICUser user = getLoginUser(request);
//        return tsBizRemListService.bizRemoveNext(user, tsBizRemListModel, opinionModel, tasklistid, nextPerformerids, nextPerformerNames, nextNodeID, entertype);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

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

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

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

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

                    }
                }

            }
        }



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

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

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


            //发送
            String[] ids = com.chinaweal.aiccs.common.util.StringUtils.split(nextPerformerids, Constant.COMMA);
            String[] names = com.chinaweal.aiccs.common.util.StringUtils.split(nextPerformerNames, Constant.COMMA);
            try {
                TSTaskList tsTaskList = tsBizRemListService.saveBizRemListAuditProcess(user, taskListModel, tsBizRemLists, opinionModel, nextNodeID, ids, names);
                if (ids.length == 1 && com.chinaweal.aiccs.common.util.StringUtils.equals(user.getPrimaryKey(), ids[0])) {
                    resultMap.put("bizseq", tsBizRemListModel.getBizseq());
                    resultMap.put("nextNodeId", nextNodeID);
                    resultMap.put("taskListId", tasklistid);
                    resultMap.put("workFlowId", taskListModel.getWorkflowid());
                }
            } catch (Exception e) {
                log.error("移出经营异常名录审核审批出错", e);
                throw new BusinessException("移出经营异常名录审核审批出错");
            }
        }
        return RestResult.ok(resultMap);
    }

    @RequestMapping(value = "/removeCheck")
    public RestResult<?> removeCheck(String abnlistid, String specause) {
        if (StringUtils.isNotBlank(specause) && specause.equals("4")) {
            TSAbnList tsAbnListModel = tsAbnListService.getById(abnlistid);
            List<TSAbnList> lists = tsAbnListService.queryTSAbnByREMDATE(tsAbnListModel.getPripid());
            //一年内有移出记录
            if (lists.size() > 0) {
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, lists);
            }
        }
        return RestResult.ok();
    }

    /**
     * 启动流程 下一步
     */
    @RequestMapping(value = "/next.do")
    public RestResult<?> approvalnext(HttpServletRequest request, String tasklistId, String abnlistids, String entertype) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");

        Map<String, Object> resultMap = new HashMap<>();
        TSTaskList taskListModel = new TSTaskList();
        //没有待办任务id
        if (StringUtils.isBlank(tasklistId)) {
            String bizseq = UUID.randomUUID().toString();

            List<TSBizRemList> bizRemListModelList = new ArrayList<TSBizRemList>();
            String[] abnlistidArr = abnlistids.split(Constant.SEMICOLON);
            String decOrgCode = aicorgService.getRegionCodeByUser(aicUser);
            for (String abnlistid : abnlistidArr) {
                //添加到 移出异常名录业务表
                TSAbnList tsAbnListModel = tsAbnListService.getById(abnlistid);

                TSBizRemList tsBizRemListModel = new TSBizRemList();
                tsBizRemListModel.setBizseq(bizseq);
                tsBizRemListModel.setAbnlistid(tsAbnListModel.getAbnlistid());
                tsBizRemListModel.setPripid(tsAbnListModel.getPripid());
                tsBizRemListModel.setRegno(tsAbnListModel.getRegno());
                tsBizRemListModel.setEntname(tsAbnListModel.getEntname());
                tsBizRemListModel.setSpecause(tsAbnListModel.getSpecause());
                tsBizRemListModel.setAbntime(tsAbnListModel.getAbntime());
                tsBizRemListModel.setSpereasons(tsAbnListModel.getSpereasons());
                tsBizRemListModel.setDecorg(decOrgCode);
                tsBizRemListModel.setAreaCode(decOrgCode);
                tsBizRemListModel.setApplyTime(LocalDateTime.now());
                tsBizRemListModel.setHandleStatus("1");
                tsBizRemListModel.setType(entertype);
                tsBizRemListModel.setAppOrPc("1");
                String areaName = null;
                if (tsBizRemListModel.getDecorg() != null) {
                    areaName = ConstantsUtil.getAreaName(tsBizRemListModel.getDecorg());
                }
                tsBizRemListModel.setDecorgName(areaName + "市场监督管理局");
                bizRemListModelList.add(tsBizRemListModel);
            }
            //添加待办
            taskListModel.setBizseqid(bizseq);
            if ("individual".equals(entertype)) {
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_RESTORE);
            } else if ("farmer".equals(entertype)) {
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_REMOVE);
            } else {
                taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_REMOVE);
            }
            taskListModel.setBusname(bizRemListModelList.get(0).getEntname());
            taskListModel = tsBizRemListService.saveAbnListStart(aicUser, taskListModel, bizRemListModelList);

        }
        //有待办任务id
        TSTaskList taskListModel1 = taskListService.selectByTasklistID(StringUtils.isNotBlank(tasklistId) ? tasklistId : taskListModel.getTasklistid());
        //查出当前业务
        List<TSBizRemList> list = tsBizRemListService.selectbizRembizseq(taskListModel1.getBizseqid());
        //查到有业务
        if (CollectionUtils.isNotEmpty(list)) {
            //异常列表id
            StringBuilder abnlistIDs = new StringBuilder();
            //移出业务相关企业id
            StringBuilder pripids = new StringBuilder();
            //遍历获取
            for (TSBizRemList bizRemListModel : list) {
                if (abnlistIDs.length() > 0) abnlistIDs.append(";");
                if (abnlistIDs.length() > 0) pripids.append(";");
                abnlistIDs.append(bizRemListModel.getAbnlistid());
                pripids.append(bizRemListModel.getPripid());
            }

            TSBizRemList bizRemListModel = new TSBizRemList();
            bizRemListModel.setRemexcpres(list.get(0).getRemexcpres()); // 回显 移出原因
            resultMap.put("bizRemListModel", bizRemListModel);
            resultMap.put("remreasons", list.get(0).getRemreasons());//回显 移出事实理由
            resultMap.put("ReconsiderationOrg", list.get(0).getReconsiderationOrg());//回显 行政复议机关
            resultMap.put("GovernmentOrg", list.get(0).getGovernmentOrg());//回显 人民政府
            resultMap.put("LitiOrg", list.get(0).getLitiOrg());//回显 诉讼机关
            resultMap.put("abnlistids", abnlistIDs);
            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("currentNode", currentNode.getCurrentnode());
        resultMap.put("currentLinkTypeID", opinionType);
        resultMap.put("currentNodeName", WorkFlowUtil.getNodeName(currentNode.getCurrentnode()));
        resultMap.put("entertype", entertype);
        return RestResult.ok(resultMap);
    }

    /**
     * 审批流程
     */
    @RequestMapping(value = "/exptnext.do")
    public RestResult<?> opentexptlist(HttpServletRequest request, TSBizRemList tsBizRemListModel, TSOpinion opinionModel, String tasklistid,
                                       String nextPerformerids, String nextPerformerNames, String nextNodeID, String entertype) {
        AICUser user = getLoginUser(request);
        Map<String, Object> resultMap = new HashMap<>();
        //更新 移出异常名录业务表
        if (StringUtils.isNotBlank(tsBizRemListModel.getBizseq())) {
            List<TSBizRemList> bizRemListModelList = tsBizRemListService.selectbizRembizseq(tsBizRemListModel.getBizseq());
            for (TSBizRemList bizRemListModel : bizRemListModelList) {
                if (FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST.equals(nextNodeID)) {
                    bizRemListModel.setRemexcpres(tsBizRemListModel.getRemexcpres());
                    bizRemListModel.setRemreasons(tsBizRemListModel.getRemreasons());
                    bizRemListModel.setReconsiderationOrg(tsBizRemListModel.getReconsiderationOrg());
                    bizRemListModel.setGovernmentOrg(tsBizRemListModel.getGovernmentOrg());
                    bizRemListModel.setLitiOrg(tsBizRemListModel.getLitiOrg());
                }
            }

            //发送
            String[] ids = StringUtils.split(nextPerformerids, ",");
            String[] names = StringUtils.split(nextPerformerNames, ",");
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            tsBizRemListService.saveBizRemListAuditProcess(user, taskListModel, bizRemListModelList, opinionModel, nextNodeID, ids, names);
            if (ids.length == 1 && StringUtils.equals(user.getPrimaryKey(), ids[0])) {
                resultMap.put("bizseq", tsBizRemListModel.getBizseq());
                resultMap.put("nextNodeID", nextNodeID);
                resultMap.put("tasklistid", tasklistid);
                resultMap.put("workflowid", taskListModel.getWorkflowid());
            }
        }
        return RestResult.ok(resultMap);
    }

    /**
     * 打印文书页面
     */
    @PostMapping("/printTSWrit.do")
    public RestResult<?> printTSWrit(HttpServletRequest request, String printstatus, TSBizRemList tsBizRemListModel, String workflowid) {
        Calendar ca = Calendar.getInstance();//当前时间
        Map<String, Object> resultMap = new HashMap<>();
        if (printstatus.equals("1")) {
            tsBizRemListModel = tsBizRemListService.getById(tsBizRemListModel.getRemlistid());
            TSWrit writQueryModel = new TSWrit();//获取文书号
            writQueryModel.setWritstype(WorkNoUtil.WORKNOTYPE_15);
            writQueryModel.setPripid(tsBizRemListModel.getPripid());
            writQueryModel.setBizseq(tsBizRemListModel.getBizseq());
            List<TSWrit> tsWritQueryModels = tsWritService.listTswrit(writQueryModel);
            if (tsWritQueryModels.size() > 0) {
                resultMap.put("wrirsno", tsWritQueryModels.get(0).getWritsno());
            }
            resultMap.put("tsBizRemListModel", tsBizRemListModel);
            resultMap.put("ReconsiderationOrgInfo", tsBizRemListModel.getReconsiderationOrg());// 回显文书 行政复议机关
            resultMap.put("nowTime", ca.getTime());
            return RestResult.ok(resultMap);

        } else if (printstatus.equals("3")) {
            TSTaskList taskListModel = taskListService.selectByWorkflowID(workflowid);
            StringBuilder regno = new StringBuilder();
            StringBuilder ename = new StringBuilder();
            List<TSBizRemList> list = tsBizRemListService.selectbizRembizseq(taskListModel.getBizseqid());
            if (CollectionUtils.size(list) > 5) {
                for (TSBizRemList bizRemListModel : list) {
                    if (regno.length() > 0) regno.append(",");
                    regno.append(bizRemListModel.getRegno());
                    if (ename.length() > 0) ename.append(",");
                    ename.append(bizRemListModel.getEntname());
                }
                regno.append("等");
                ename.append("等");
            } else {
                for (TSBizRemList bizRemListModel : list) {
                    if (regno.length() > 0) regno.append(",");
                    regno.append(bizRemListModel.getRegno());
                    if (ename.length() > 0) ename.append(",");
                    ename.append(bizRemListModel.getEntname());
                }
            }
            List<TSOpinion> opinionList = opinionService.selectByAuditingID(workflowid);
            resultMap.put("opinionList", opinionList);
            resultMap.put("regno", regno);
            resultMap.put("ename", ename);
            resultMap.put("remreasons", list.get(0).getRemreasons());
            resultMap.put("list", list);
            return RestResult.ok(resultMap);
        }
        return RestResult.ok(resultMap);
    }

    /**
     * 通过业务id获取异常移出审批表信息
     *
     * @param bizseq
     * @return
     */
    @GetMapping("/getBizRemListPrintInfo")
    public RestResult<?> getBizRemListPrintInfo(String bizseq) {
        List<TSBizRemList> bizRemLists = tsBizRemListService.list(new LambdaQueryWrapper<TSBizRemList>().eq(StringUtils.isNotBlank(bizseq), TSBizRemList::getBizseq, bizseq));
        List<String> abnListIds = new ArrayList<>();
        for (TSBizRemList bizRemList : bizRemLists) {
            abnListIds.add(bizRemList.getAbnlistid());
        }
        List<TSAbnList> resultList = tsAbnListService.list(new LambdaQueryWrapper<TSAbnList>().in(TSAbnList::getAbnlistid, abnListIds).eq(TSAbnList::getOperatestatus, "0"));//暂时耦合为0
//        return RestResult.ok(resultList.stream().map(tsAbnList -> tsAbnList.setRemDecorg(ConstantsUtil.getAreaName(tsAbnList.getAreaCode()) + "市场监督管理局")).collect(Collectors.toList()));
        return RestResult.ok(resultList);
    }


    /**
     * 继续增加移出主体信息
     */
    @PostMapping("/addMoreEnt.do")
    public RestResult<?> addMoreEnt(HttpServletRequest request, String entertype, String blicNO, String entName, String bizSeq) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) throw new BusinessException("登录超时，请重新登录");

        TSAbnList tsAbnListModel = new TSAbnList();
        tsAbnListModel.setRegno(blicNO);
        tsAbnListModel.setEntname(entName);
//        tsAbnListModel.setDecorg(aicUser.getRegionID());//只查询属于本机构做出决定的 异常名录主体
        IPage<TSAbnList> tsAbnListModelDataGrid = tsAbnListService.selectTSAbnByPageList(new Page<>(1, 5), tsAbnListModel, entertype);
        if (CollectionUtils.isEmpty(tsAbnListModelDataGrid.getRecords())) {
            throw new BusinessException("无法查到该主体信息,请确认查询条件");
        } else {
            tsAbnListModel = tsAbnListModelDataGrid.getRecords().get(0);
        }

        if (tsAbnListModel != null && StringUtils.isNotBlank(tsAbnListModel.getAbnlistid())) {
            TSBizRemList tsBizRemListModel = new TSBizRemList();
            tsBizRemListModel.setBizseq(bizSeq);
            tsBizRemListModel.setAbnlistid(tsAbnListModel.getAbnlistid());
            List<TSBizRemList> bizRemListModelList = tsBizRemListService.selectBRMexptlist(tsBizRemListModel);
            if (CollectionUtils.isEmpty(bizRemListModelList)) { //避免重复增加
                String validateResult = this.validate(tsAbnListModel.getAbnlistid());
                if ("success".equals(validateResult)) {
                    TSBizRemList bizRemListModel = new TSBizRemList();
                    bizRemListModel.setBizseq(bizSeq);
                    bizRemListModel.setAbnlistid(tsAbnListModel.getAbnlistid());
                    bizRemListModel.setPripid(tsAbnListModel.getPripid());
                    bizRemListModel.setRegno(tsAbnListModel.getRegno());
                    bizRemListModel.setEntname(tsAbnListModel.getEntname());
                    bizRemListModel.setSpecause(tsAbnListModel.getSpecause());
                    bizRemListModel.setAbntime(tsAbnListModel.getAbntime());
                    bizRemListModel.setSpereasons(tsAbnListModel.getSpereasons());
                    bizRemListModel.setDecorg(aicUser.getRegionID());
                    tsBizRemListService.saveOrUpdate(bizRemListModel);
                    return OK;
                } else {
                    throw new BusinessException(validateResult);
                }
            }
        }
        throw new BusinessException("无法查找该主体信息，请确认查询条件或检查是否已在列表中");
    }

    /**
     * 删除 移出信息
     */
    @PostMapping("/delBizSpeList.do")
    public RestResult<?> delBizSpeList(String remlistid) {
        tsBizRemListService.removeById(remlistid);
        return OK;
    }

    /**
     * 经营异常信用修复回退至申请人
     *
     * @param tasklistid   待办id
     * @param bizSeq       业务号
     * @param backProposal 回退原因
     * @return
     */
    @Transactional
    @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) throw new BusinessException("登录超时，请重新登录");

        //更新其他人待办状态
        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);
                    }
                } else {
                    throw new BusinessException("业务办理错误");
                }

            }
        }


        List<TSBizRemList> tsBizSerIllegalRemNow = tsBizRemListService.selectbizRembizseq(bizSeq);

        List<TSBizRemList> tsBizRemLists = tsBizSerIllegalRemNow;
        TSBizRemList bizRemList = null;
        if(CollectionUtils.isNotEmpty(tsBizRemLists)){
            bizRemList = tsBizRemLists.get(0);
        }
        if(bizRemList != null) {
            TSTaskList taskList = taskListService.getById(tasklistid);
            // 改变业务表状态.
            bizRemList.setIsAccept("0");
            bizRemList.setHandleStatus("2");
            bizRemList.setApprovaldate(LocalDate.now());
            bizRemList.setRemSponsorID(taskList.getCreateUserid());
            bizRemList.setRemSponsor(taskList.getCreateUsername());
            bizRemList.setBackProposal(backProposal);
            bizRemList.setLauptime(LocalDateTime.now());
            boolean save1 = tsBizRemListService.updateById(bizRemList);
            // 改变待办状态

            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("9");// 一开始为0，后改为9
            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("==============更新业务表失败=========表名:tsbizremlist=======bizSeq:{}==========={}",bizSeq,bizRemList);
                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("===========获取业务表为空=========表名:tsbizremlist==========bizSeq：{}======bizRemList:{}",bizSeq,bizRemList);
        throw new BusinessException(ResultCode.BUSINESS_LOGIC_ERROR);
    }

    private String checkTask(String tasklistId, String bizseq, AICUser user) {
        AssertUtils.isNotBlank(tasklistId, bizseq);
        TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistId);
        if (!taskListModel.getSignuserid().equals(user.getPrimaryKey()) || BaseDataConstant.BUSINESS_STATUS_XYXF_END.equals(taskListModel.getBusstatus())) {
            return "该业务在办理中";
        }
        LambdaQueryWrapper<TSTaskList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSTaskList::getBizseqid, bizseq)
                .ne(TSTaskList::getBusstatus, BaseDataConstant.BUSINESS_STATUS_XYXF_END);
        List<TSTaskList> taskLists = taskListService.list(wrapper);
        if (CollectionUtils.isEmpty(taskLists)) {
            return "数据未找到";
        }
        if (taskLists.size() > 1) {
            for (int i = 0; i < taskLists.size(); i++) {
                TSTaskList task = taskLists.get(i);
                if (!user.getPrimaryKey().equals(task.getSignuserid())) {
                    task.setBusstatus(BaseDataConstant.BUSINESS_STATUS_XYXF_END);
                    taskListService.updateById(task);
                }
            }
        }
        return "ok";
    }

    /**
     * 判断是否多次因地址列异
     * lwd
     * 2021-12-25
     */
    @RequestMapping(value = "/addrRemovCheck")
    public RestResult<Boolean> addrRemovCheck(String pripid, String abntime) {
        String[] split = abntime.split("-");

        Integer integer = Integer.valueOf(split[0]);
        String year = String.valueOf(integer - 1);
        String newAbnTime = year + "-" + split[1] + "-" + split[2];
        //查询企业的一年内列异
        List<TSAbnList> tsAbnLists = tsAbnListService.selectAbnListByPripid(pripid, newAbnTime, abntime);
        int addrcount = 0;
        //判断该企业是否一年内因地址被列异2次或以上
        for (int i = 0; i < tsAbnLists.size(); i++) {
            if (tsAbnLists.get(i).getEnttype().equals("9910") && tsAbnLists.get(i).getSpecause().equals("3")) {//个体户
                addrcount++;
            } else if (tsAbnLists.get(i).getEnttype().equals("9100") || tsAbnLists.get(i).getEnttype().equals("9200")) {//农业
                if (tsAbnLists.get(i).getSpecause().equals("3")) {
                    addrcount++;
                }
            } else {//企业
                if (tsAbnLists.get(i).getSpecause().equals("4")) {
                    addrcount++;
                }
            }
        }
        if (addrcount > 1) {
            return RestResult.ok(true);
        } else {
            return RestResult.ok(false);
        }
    }

    /**
     * 批量审核/审核
     */
    @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 isagree = (String) data.get("isagree");
        String handledateStr = (String) data.get("handledate");
        LocalDateTime handledate = LocalDateTime.parse(handledateStr, DateTimeUtils.DATETIME_FORMATTER);
        String nextPerformerids = null;
        String nextPerformerNames = null;
        if (data.get("nextPerformerids") != null) {
            nextPerformerids = (String) data.get("nextPerformerids");
            nextPerformerNames = (String) data.get("nextPerformerNames");
        }
        if ("end".equals(nextNodeID) && CollectionUtils.isNotEmpty(taskList) && taskList.size() > 100)
            throw new BusinessException("超出最大审批数量，最多不能超过100条。");
        CountDownLatch countDownLatch = new CountDownLatch(taskList.size());

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

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

                if (batchType.equals("review")) {
                    //审核
                    opinionModel.setOpiniontype("1");
                } else if (batchType.equals("examine")) {
                    //审批
                    opinionModel.setOpiniontype("2");
                }
                bizRemoveNext(request, tsBizRemListModel, opinionModel, taskListUnionDto.getTasklistid(), finalNextPerformerids, finalNextPerformerNames, nextNodeID, null);
                countDownLatch.countDown();//减1
            };
            executorService.submit(runnable);
        }

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

    /**
     * 严重违法、经营异常
     * 批量审核/审核
     */
    @PostMapping("/batchReviewAndExamineByAll")
    public RestResult<?> batchReviewAndExamineByAll(@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 isagree = (String) data.get("isagree");
        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 jyycNextPerformerids = null;
        String jyycNextPerformerNames = null;
        if (data.get("jyycNextPerformerids") != null) {
            jyycNextPerformerids = (String) data.get("jyycNextPerformerids");
            jyycNextPerformerNames = (String) data.get("jyycNextPerformerNames");
        }
        String yzwfNextPerformerids = null;
        String yzwfNextPerformerNames = null;
        if (data.get("yzwfNextPerformerids") != null) {
            yzwfNextPerformerids = (String) data.get("yzwfNextPerformerids");
            yzwfNextPerformerNames = (String) data.get("yzwfNextPerformerNames");
        }
        CountDownLatch countDownLatch = new CountDownLatch(taskList.size());
        List<Future<String>> futures = new ArrayList<>();
        //遍历批量审核列表参数，并调用方法
        for (TaskListUnionDto taskListUnionDto : taskList) {
            String bustype = taskListUnionDto.getBustype();
            String finalNextPerformerids = null;
            String finalNextPerformerNames = null;
            if (StringUtils.isBlank(bustype)) {
                log.error("批量审核/审批失败, biSeq: {},bustype业务类型为空", taskListUnionDto.getBizseqid());
                return RestResult.error(ResultCode.PARAM_IS_BLANK);
            } else if (bustype.equals("7") || bustype.equals("12") || bustype.equals("14")) {
                finalNextPerformerids = jyycNextPerformerids;
                finalNextPerformerNames = jyycNextPerformerNames;
            } else if (bustype.equals("33")) {
                finalNextPerformerids = yzwfNextPerformerids;
                finalNextPerformerNames = yzwfNextPerformerNames;
            } else {
                log.error("批量审核/审批失败, biSeq: {},bustype业务类型错误，类型为{}", taskListUnionDto.getBizseqid(), taskListUnionDto.getBustype());
                return RestResult.error(ResultCode.PARAM_IS_INVALID);
            }

            String finalNextPerformerids1 = finalNextPerformerids;
            String finalNextPerformerNames1 = finalNextPerformerNames;
            Callable<String> callable = () -> {
                Boolean jyycBoolean = false;
                Boolean yzwfBoolean = false;
                String nextNodeID1 = "";
                try {
                    TSBizRemList tsBizRemListModel = new TSBizRemList();
                    TSBizSerIllegalRem tsBizSerIllegalRemModel = new TSBizSerIllegalRem();
                    if (bustype.equals("7") || bustype.equals("12") || bustype.equals("14")) {
                        tsBizRemListModel.setBizseq(taskListUnionDto.getBizseqid());
                        if (nextNodeID.equals("approve")) {            //经营异常审核通过
                            nextNodeID1 = "approvelist";
                        } else if (nextNodeID.equals("enter")) {        //经营异常审核回退
                            nextNodeID1 = "exptlistEnter";
                        } else if (nextNodeID.equals("end")) {         //经营异常审批通过
                            nextNodeID1 = "endExptlist";
                        } else if (nextNodeID.equals("spEnter")) {     //经营异常审批回退
                            nextNodeID1 = "handleExptlist";
                        }
                        jyycBoolean = true;
                    } else if (bustype.equals("33")) {
                        tsBizSerIllegalRemModel.setBizSeq(taskListUnionDto.getBizseqid());
                        yzwfBoolean = true;
                        if (nextNodeID.equals("approve")) {           //严重违法审核通过
                            nextNodeID1 = "approveSerIllegal";
                        } else if (nextNodeID.equals("enter")) {       //严重违法审核回退
                            nextNodeID1 = "serIllegalEnter";
                        } else if (nextNodeID.equals("end")) {        //严重违法审批通过
                            nextNodeID1 = "endSerIllegal";
                        } else if (nextNodeID.equals("spEnter")) {    //严重违法审批回退
                            nextNodeID1 = "serIllegalEnter";
                        }
                    }
                    TSOpinion opinionModel = new TSOpinion();
                    opinionModel.setWorkflowid(taskListUnionDto.getWorkflowid());
                    opinionModel.setHandler(user.getName());
                    opinionModel.setHandlerid(user.getPrimaryKey());
                    opinionModel.setOpinioncontent(opinion);
                    opinionModel.setHandledate(handledate);
                    opinionModel.setIsagree(isagree);

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

                    if (jyycBoolean) {
                        tsBizRemListService.bizRemoveNext(request, tsBizRemListModel, opinionModel, taskListUnionDto.getTasklistid(), finalNextPerformerids1, finalNextPerformerNames1, nextNodeID1, null);
                    } else if (yzwfBoolean) {
                        tsBizSerIllegalRemService.serIllegalNext(request, null, tsBizSerIllegalRemModel, opinionModel, taskListUnionDto.getTasklistid(), finalNextPerformerids1, finalNextPerformerNames1, nextNodeID1);
                    }
                } catch (Exception e) {
                    log.error("批量审核/审批失败，taskListId：{}, nextNodeID:{}", taskListUnionDto.getTasklistid(), nextNodeID1, e);
                    countDownLatch.countDown();//减1
                    return "error";
                }
                countDownLatch.countDown();//减1
                return "success";
            };
            Future<String> future = executorService.submit(callable);
            futures.add(future);
        }
        Integer errorNumber = 0;
        try {
            countDownLatch.await(5, TimeUnit.MINUTES);//5分钟超时
            for (Future<String> future : futures) {
                String result = future.get();
                if (StringUtils.isBlank(result) || result.equals("error")) {
                    errorNumber++;
                }
            }
        } catch (Exception e) {
            log.error("批量审核/审批失败", e);
            throw new BusinessException("批量审核/审批失败");
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("errorNumber", errorNumber);
        resultMap.put("successNumber", taskList.size() - errorNumber);
        resultMap.put("total", taskList.size());
        return RestResult.ok(resultMap);
    }

    /**
     * 严重违法、经营异常
     * 批量审核/审核新增列表展示
     */
    @PostMapping("/getRemInfoByBatch")
    public RestResult<?> getRemInfoByBatch(@RequestBody Map<String, Object> data) {
        List<TaskListUnionDto> taskList = JSONObject.parseArray(JSONObject.toJSONString(data.get("taskListUnionDto")), TaskListUnionDto.class);
        List<RemBatchVo> remBatchVos = new ArrayList<>();
        for (TaskListUnionDto task : taskList) {      //循环遍历获取列表
            String bustype = task.getBustype();
            RemBatchVo remBatchVo = new RemBatchVo();
            remBatchVo.setBizSeqId(task.getBizseqid());
            remBatchVo.setBusname(task.getBusname());
            if (StringUtils.isNotBlank(task.getWorkflowid())) {           //获取最新一个意见
                TSOpinion opinionByOne = opinionService.getOpinionByOne(task.getWorkflowid());
                if (opinionByOne != null) {
                    remBatchVo.setOpinion(opinionByOne.getOpinioncontent());
                }
            }
            if (StringUtils.isBlank(bustype) || StringUtils.isBlank(task.getBizseqid())) {
                remBatchVos.add(remBatchVo);
                continue;
            } else if (bustype.equals("7") || bustype.equals("12") || bustype.equals("14")) {        //经营异常
                QueryWrapper<TSBizRemList> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(TSBizRemList::getBizseq, task.getBizseqid());
                //待移出企业业务表
                List<TSBizRemList> bizRemLists = tsBizRemListService.list(wrapper);
                if (bizRemLists.size() > 0) {
                    TSBizRemList bizRemListModel = bizRemLists.get(0);
                    remBatchVo.setRemreasons(bizRemListModel.getRemreasons());
                }
            } else if (bustype.equals("33")) {     //严重违法
                List<TSBizSerIllegalRem> serIllegalRems = tsBizSerIllegalRemService.list(new LambdaQueryWrapper<TSBizSerIllegalRem>().eq(TSBizSerIllegalRem::getBizSeq, task.getBizseqid()));
                if (serIllegalRems.size() > 0) {
                    TSBizSerIllegalRem serIllegalRem = serIllegalRems.get(0);
                    remBatchVo.setRemreasons(serIllegalRem.getLostCreditExplainrem());
                }
            }
            remBatchVos.add(remBatchVo);
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("remBatchVos", remBatchVos);
        return RestResult.ok(resultMap);

    }

    @PostMapping("cancelBusiness")
    public RestResult<?> cancelBusiness(String bizSeq) {
        tsBizRemListService.pcCancelBusiness(bizSeq);
        return RestResult.ok();
    }
}
