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

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
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.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.AbnProcessDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.BizSpetExcel;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.EntExcel;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.TSBizSpeListVO;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.auditing.service.TSTaskListEnterTypeService;
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.claim.service.TSEntBaseAddrService;
import com.chinaweal.aiccs.aiccs.claim.service.TSEntBaseService;
import com.chinaweal.aiccs.aiccs.entbase.entity.TREntPriseType;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntBaseService;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntPriseTypeService;
import com.chinaweal.aiccs.aiccs.market.entity.EntAddressChangeLog;
import com.chinaweal.aiccs.aiccs.market.service.IEntAddressChangeLogService;
import com.chinaweal.aiccs.aiccs.market.service.ITSSueInspectService;
import com.chinaweal.aiccs.aiccs.market.service.ITSUsualInspectService;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelIePortUtils;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelListener;
import com.chinaweal.aiccs.aiccs.query.entity.TSEntBaseQuery;
import com.chinaweal.aiccs.aiccs.query.service.TSEntBaseQueryService;
import com.chinaweal.aiccs.aiccs.revoke.Vo.DisableListVo;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
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.constant.PermissionConstant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.config.CommonConfig;
import com.chinaweal.aiccs.crgs.entbase.service.TCompanyDetailsService;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aiccs.redis.RedisService;
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.google.common.collect.Lists;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
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.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 异常名录业务接口
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/1/20 14:03
 **/
@RestController
@RequestMapping("/bizSpeList")
@Slf4j
public class BizSpeListController extends BaseController {

    @Autowired
    private TSEntBaseService tsEntBaseService;
    @Autowired
    private TSEntBaseAddrService tsEntBaseAddrService;
    @Autowired
    private TSBizSpeListService tsBizSpeListService;
    @Autowired
    private TSTaskListService tasklistService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private WorkFlowService workFlowService;
    @Autowired
    private TSOpinionService opinionService;
    @Autowired
    private TSEntBaseQueryService tsEntBaseQueryService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TREntBaseService trEntBaseService;
    @Autowired
    private TCompanyDetailsService companyDetailsService;
    @Autowired
    private TSAttachmentService attachmentService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Autowired
    private OrgUM orgUM;
    @Autowired
    private TSTaskListEnterTypeService taskListEnterTypeService;
    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private TREntPriseTypeService entPriseTypeService;
    @Autowired
    private ToincludeabnService toincludeabnService;
    @Resource
    private TSAttachmentService tsAttachmentService;
    @Resource
    private FileStorageService fileStorageService;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TUsersService tUsersService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    @Lazy
    private ITSUsualInspectService itsUsualInspectService;
    @Resource
    private ITSSueInspectService itsSueInspectService;
    @Autowired
    private ToinrosterService toinrosterService;
    @Resource
    private IEntAddressChangeLogService iEntAddressChangeLogService;
    @Resource
    private RedisService redisService;
    /**
     * 线程池
     **/
    private final ExecutorService executorService = Executors.newFixedThreadPool(50);

    private static final String CACHE_KEY_PREFIX = "abnormal:bizspe:";
    private static final int CACHE_EXPIRE_SECONDS = 15 * 60;

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

    /**
     * 获取经营异常录入审核人列表
     *
     * @param request 当前请求
     * @return 经营异常录入审核人列表
     * @author lroyia
     * @since 2021年2月5日 17:27:13
     */
    @GetMapping("getAbnormalReviewerList")
    public RestResult<?> getAbnormalReviewerList(HttpServletRequest request) {
        AICUser curUser = getLoginUser(request);
        List<AICUser> result = orgUM.findUsersByOrgAndPermission(curUser.getUnitID(), PermissionConstant.ABNORMAL_REVIEW);
        for (AICUser each : result) {
            each.setPassword(null);
        }
        return RestResult.ok(result);
    }

    /**
     * 作废 (需求更改)
     * 年报列异批量发起
     *
     * @return
     */
    @PostMapping("saveNbAccept")
    public RestResult<?> saveNbAccept() {
        List<String> tasklistids = new ArrayList<>();
        List<OrgUnits> orgUnitsList = tUsersService.queryAllOrg();
        for (OrgUnits orgUnits : orgUnitsList) {
            // 获取该区有经办权限的人员名单
            List<AICUser> aicUsers = new ArrayList<>();
            try {
                aicUsers = orgUM.findUsersByOrgAndPermission(orgUnits.getOrgUnitId(), "exptInclueEnter");
            } catch (Exception e) {
                continue;
            }
            if (aicUsers.size() == 0) continue;
            List<String> useridlist = new ArrayList<>();
            for (AICUser aicUser : aicUsers) {
                useridlist.add(aicUser.getPrimaryKey());
            }
            List<EBaseinfo> eBaseinfos = eBaseinfoService.queryForNb(orgUnits.getOrgNumber());
            // 添加业务表
            String bizSeq = UUID.randomUUID().toString();
            List<TSBizSpeList> bizSpeList = new ArrayList<>();
            // 批量插入业务表
            int i = 0;
            int total = eBaseinfos.size();
            for (EBaseinfo eBaseinfo : eBaseinfos) {
                TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
                tsBizSpeListModel.setBizseq(bizSeq);
                tsBizSpeListModel.setPripid(eBaseinfo.getPripid());
                tsBizSpeListModel.setRegno(eBaseinfo.getRegno());
                tsBizSpeListModel.setUniscid(eBaseinfo.getUniscid());
                tsBizSpeListModel.setEntname(eBaseinfo.getEntname());
                tsBizSpeListModel.setEnttype(eBaseinfo.getEnttype());
                tsBizSpeListModel.setIsRemove("0");
                tsBizSpeListModel.setType("company");
                tsBizSpeListModel.setDecorg(orgUnits.getOrgNumber());
                tsBizSpeListModel.setStatus("9"); // 流程启动把状态设置为 "受理中"
                tsBizSpeListModel.setLauptime(LocalDateTime.now());
                // 这里以组为接收单位，不设置列入主办人，在经办环节谁认领谁就是列入主办人
//                tsBizSpeListModel.setIntoSponsor(user.getName());//设置列入主办人
//                tsBizSpeListModel.setIntoSponsorId(user.getPrimaryKey());
                bizSpeList.add(tsBizSpeListModel);
                i++;
                if (i % 100 == 0 || i == total) {
                    tsBizSpeListService.saveTsbizspelistBatch(bizSpeList);
                    bizSpeList.clear();
                }
            }
            // 待办
            TSTaskList taskListModel = new TSTaskList();
            taskListModel.setBizseqid(bizSeq);
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP);//企业异常名录
            String type = "企业";
            taskListModel.setBusname("2022年" + type + "未年报批量列异");

            String definedname = FlowUtil.EXPTLISTWORKFLOW;//企业经营异常名录流程模板
            //新待办 设置待办信息
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel);
            //开始工作流
            String tasklistid = taskListService.startWorkFlow(taskListModel, useridlist, orgUnits.getOrgNumber(), definedname);
            tasklistids.add(tasklistid);
        }
        for (String tasklistid : tasklistids) {
            System.out.println(tasklistid + "===================");
        }
        return RestResult.ok(tasklistids);
    }

    /**
     * 年报列异批量发起
     *
     * @return
     */
    @PostMapping("saveNbAccept2")
    public RestResult<?> saveNbAccept2(String abnType) {
        List<String> tasklistids = new ArrayList<>();
        List<OrgUnits> orgUnitsList = tUsersService.queryAllOrg();
        for (OrgUnits orgUnits : orgUnitsList) {
            // 获取该区有经办权限的人员
            AICUser aicUser = null;
            try {
                String orgCode = orgUnits.getOrgNumber();
                // 指定分派经办人 （垃圾需求）
                switch (orgCode) {
                    case "440101":
                        aicUser = orgUM.findUserByPrimaryKey("8c62991a-b4ff-4e0d-810a-0ce91f117492");
                        break;
                    case "440129":
                        aicUser = orgUM.findUserByPrimaryKey("FCD87355-14BA-4FE2-9F7F-6DDA766977EE");
                        break;
                    case "440104":
                        aicUser = orgUM.findUserByPrimaryKey("5c76c5dc-a466-4486-ac05-90bbb8186ef5");
                        break;
                    case "440106":
                        aicUser = orgUM.findUserByPrimaryKey("402E9E7B-0E2A-48EC-ADE9-FEAF20FA977C");
                        break;
                    case "440105":
                        aicUser = orgUM.findUserByPrimaryKey("a77383de-93b9-4480-9854-a1bd7bba9d74");
                        break;
                    case "440103":
                        aicUser = orgUM.findUserByPrimaryKey("25426390-45af-415b-9152-6403e60cd2ad");
                        break;
                    case "440112":
                        aicUser = orgUM.findUserByPrimaryKey("289787ed-08b7-4a5b-a78b-b805a8efd71f");
                        break;
                    case "440111":
                        aicUser = orgUM.findUserByPrimaryKey("01ad3b09-de85-4476-b75d-1b05615f3e17");
                        break;
                    case "440121":
                        aicUser = orgUM.findUserByPrimaryKey("1e41b0f6-3e4f-4262-9b65-e749c9caeeb8");
                        break;
                    case "440122":
                        aicUser = orgUM.findUserByPrimaryKey("1fc0469f-7848-4cbf-bb8a-3d31a6bdb83f");
                        break;
                    case "440126":
                        aicUser = orgUM.findUserByPrimaryKey("ccb07215-80a6-403e-9a34-85eda81d149e");
                        break;
                    case "440110":
                        aicUser = orgUM.findUserByPrimaryKey("3851A61C-358B-460C-852C-E8D3D9865CDC");
                        break;
                    case "440125":
                        aicUser = orgUM.findUserByPrimaryKey("6fc4d0d0-2ff0-4158-b61c-0e5a21ca067f");
                        break;
                    default:
                }
            } catch (Exception e) {
                continue;
            }
            if (aicUser == null) continue;
            String busType = "";
            String type = "";
            List<EBaseinfo> eBaseinfos = new ArrayList<>();
            if (abnType.equals("company")) {
                eBaseinfos = eBaseinfoService.queryForNb(orgUnits.getOrgNumber());
                busType = BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP;
                type = "企业";
            } else if (abnType.equals("individual")) {
                eBaseinfos = eBaseinfoService.querygtForNb(orgUnits.getOrgNumber());
                busType = BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG;
                type = "个体户";
            } else if (abnType.equals("farmer")) {
                eBaseinfos = eBaseinfoService.querynzForNb(orgUnits.getOrgNumber());
                busType = BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD;
                type = "农合";
            } else {
                continue;
            }
            if (eBaseinfos.size() == 0) {
                continue;
            }
            // 添加业务表
            String bizSeq = UUID.randomUUID().toString();
            List<TSBizSpeList> bizSpeList = new ArrayList<>();
            // 批量插入业务表
            int i = 0;
            int total = eBaseinfos.size();
            for (EBaseinfo eBaseinfo : eBaseinfos) {
                TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
                tsBizSpeListModel.setBizseq(bizSeq);
                tsBizSpeListModel.setPripid(eBaseinfo.getPripid());
                tsBizSpeListModel.setRegno(eBaseinfo.getRegno());
                tsBizSpeListModel.setUniscid(eBaseinfo.getUniscid());
                tsBizSpeListModel.setEntname(eBaseinfo.getEntname());
                tsBizSpeListModel.setEnttype(eBaseinfo.getEnttype());
                tsBizSpeListModel.setIsRemove("0");
                tsBizSpeListModel.setType(abnType);
                tsBizSpeListModel.setDecorg(orgUnits.getOrgNumber());
                tsBizSpeListModel.setStatus("9"); // 流程启动把状态设置为 "受理中"
                tsBizSpeListModel.setLauptime(LocalDateTime.now());
                tsBizSpeListModel.setIntoSponsor(aicUser.getName());//设置列入主办人
                tsBizSpeListModel.setIntoSponsorId(aicUser.getPrimaryKey());
                bizSpeList.add(tsBizSpeListModel);
                i++;
                if (i % 100 == 0 || i == total) {
                    tsBizSpeListService.saveTsbizspelistBatch(bizSpeList);
                    bizSpeList.clear();
                }
            }
            // 待办
            TSTaskList taskListModel = new TSTaskList();
            taskListModel.setBizseqid(bizSeq);
            taskListModel.setBustype(busType);//企业异常名录

            taskListModel.setBusname("2021年" + type + "未年报批量列异");

            String definedname = FlowUtil.EXPTLISTWORKFLOW;//企业经营异常名录流程模板
            //新待办 设置待办信息
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, aicUser);
            //开始工作流
            String tasklistid = taskListService.startWorkFlow(taskListModel, aicUser, definedname);
            tasklistids.add(tasklistid);
        }
        for (String tasklistid : tasklistids) {
            System.out.println(tasklistid + "===================");
        }
        return RestResult.ok(tasklistids);
    }

    @RequestMapping("/saveIvdAccept")
    public RestResult<?> saveIvdAccept(String pripid, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotBlank(pripid);
        String code = aicorgService.getRegionCodeByUser(aicUser);
        String bizSeq = UUID.randomUUID().toString();
        EBaseinfo eBaseinfo = eBaseinfoService.getById(pripid);

//        //该主体登记机关是其他机关登记
//        if (!code.equals(eBaseinfo.getRegorg().substring(0, 6))) {
//            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "该主体登记机关是其他机关登记，请重新选择！");
//        }

        String entertype = "";
        String enttype = eBaseinfo.getEnttype();
        if ("9910".equals(enttype)) {
            entertype = "individual";
        } else if ("9100".equals(enttype) || "9200".equals(enttype)) {
            entertype = "farmer";
        } else {
            entertype = "company";
        }
        TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
        tsBizSpeListModel.setBizseq(bizSeq);
        tsBizSpeListModel.setPripid(eBaseinfo.getPripid());
        tsBizSpeListModel.setRegno(eBaseinfo.getRegno());
        tsBizSpeListModel.setUniscid(eBaseinfo.getUniscid());
        tsBizSpeListModel.setEntname(eBaseinfo.getEntname());
        tsBizSpeListModel.setEnttype(eBaseinfo.getEnttype());
        tsBizSpeListModel.setIsRemove("0");
        tsBizSpeListModel.setType(entertype);
        tsBizSpeListModel.setDecorg(code);
        List<TSBizSpeList> bizSpeList = new ArrayList<>();
        bizSpeList.add(tsBizSpeListModel);
        //待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        if (entertype.equals("individual")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG);//个体工商户
        } else if (entertype.equals("farmer")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD);////农合
        } else {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP);//企业异常名录
        }
        taskListModel.setBusname(eBaseinfo.getEntname());
        taskListModel = tsBizSpeListService.saveAbnListAccept(aicUser, taskListModel, bizSpeList);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, String> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizSeq);
            result.put("workflowId", taskListModel.getWorkflowid());
            return RestResult.ok(result);
        }
        return OK;
    }

    /**
     * 动态监管批量,发起列异
     *
     * @param id
     * @param entertype
     * @param request
     * @return
     */
    @RequestMapping("saveAcceptBatch")
    public RestResult<?> saveAcceptBatch(String id, String entertype, HttpServletRequest request) {
        return tsBizSpeListService.saveAcceptBatch(id, entertype, request);
    }

    /**
     * 保存待办受理
     *
     * @param ids       id 线索列异为toIncludeId，其他为pripid
     * @param entertype 主体类型
     * @param request   请求信息
     * @return 保存结果
     * @author Lee
     * @since 2021年1月22日 14:08:50
     */
    @Transactional
    @PostMapping(value = "/saveAccept.do")
    public RestResult<?> saveAccept(String ids, String abnType, String entertype, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotBlank(ids, entertype, abnType);
        //生成业务号
        String bizSeq = UUID.randomUUID().toString();
        List<TSBizSpeList> bizSpeList = new ArrayList<>();
        String[] idArray = ids.split(Constant.SEMICOLON);
        Toincludeabn toincludeabn = null;
        String dataFrom = null;
        String code = aicorgService.getRegionCodeByUser(aicUser);
        for (String id : idArray) {
            TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
            String pripid = null;
            String reaType = "";// 原因类型
            if ("CLUE".equals(abnType)) {// 线索列异
                toincludeabn = toincludeabnService.getOne(new LambdaQueryWrapper<Toincludeabn>().eq(Toincludeabn::getToIncludeId, id));
                if (toincludeabn == null) {
                    throw new BusinessException(ResultCode.PARAM_IS_INVALID);
                }
                pripid = toincludeabn.getPripid();
                reaType = toincludeabn.getIncludeType();
                tsBizSpeListModel.setToIncludeId(toincludeabn.getToIncludeId());
                dataFrom = toincludeabn.getDataFrom();
            } else if ("ADDRESS".equals(abnType)) {// 地址批量列异
                reaType = "4"; // 实地查无原因为 “4”
                pripid = id;
            }

            EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, pripid));
            tsBizSpeListModel.setBizseq(bizSeq);
            tsBizSpeListModel.setPripid(eBaseinfo.getPripid());
            tsBizSpeListModel.setRegno(eBaseinfo.getRegno());
            tsBizSpeListModel.setUniscid(eBaseinfo.getUniscid());
            tsBizSpeListModel.setEntname(eBaseinfo.getEntname());
            tsBizSpeListModel.setEnttype(eBaseinfo.getEnttype());
            tsBizSpeListModel.setIsRemove("0");
            tsBizSpeListModel.setType(entertype);// 区分主体类型：企业，个体户，农专
            if ("3".equals(reaType)) {//虚假公示
                if ("company".equals(entertype)) {
                    tsBizSpeListModel.setSpecause("3");
                } else {
                    tsBizSpeListModel.setSpecause("2");
                }
            } else if ("4".equals(reaType)) {// 实地查无
                if ("company".equals(entertype)) {
                    tsBizSpeListModel.setSpecause("4");
                } else {
                    tsBizSpeListModel.setSpecause("3");
                }
                // 实地查无 保存当时主体地址
                // TODO 确认地址信息字段
                if ("individual".equals(entertype)) {
                    tsBizSpeListModel.setDom(eBaseinfo.getOploc());
                } else {
                    tsBizSpeListModel.setDom(eBaseinfo.getDom());
                }
            } else if ("1".equals(reaType)) {// 未年报
                // TODO 保存未年报年度
//                tsBizSpeListModel.setReportYear());
            } else if ("2".equals(reaType)) {// 未在规定期内公示
                if ("company".equals(entertype)) {
                    tsBizSpeListModel.setSpecause("2");
                }
            }
            tsBizSpeListModel.setDecorg(code);
            tsBizSpeListModel.setDecisionContent(tsBizSpeListService.getDecTempContent(tsBizSpeListModel.getSpecause(),
                    entertype, tsBizSpeListModel.getDecorg()));
            bizSpeList.add(tsBizSpeListModel);
        }
        if (bizSpeList.size() == 0) throw new BusinessException("尚未查找到企业信息");
        if ("CLUE".equals(abnType)) { // 线索列异
            // 文件信息拷贝
            TSAttachment tsAttachment = new TSAttachment();
            tsAttachment.setBizseq(toincludeabn.getDataFromId());
            List<TSAttachment> attachmentList = tsAttachmentService.selectwritByPage(tsAttachment);
            for (TSAttachment attachment : attachmentList) {
                TSAttachment tsAttachmentModel = new TSAttachment();
                tsAttachmentModel.setAttachmentid(UUID.randomUUID().toString());
                tsAttachmentModel.setBizseq(bizSeq);
                tsAttachmentModel.setAttachtype("1");//标记线索上传的附件类型为1
                tsAttachmentModel.setLauptime(LocalDateTime.now());
                tsAttachmentModel.setFileurl(attachment.getFileurl());
                tsAttachmentModel.setTemppath(attachment.getTemppath());
                tsAttachmentModel.setFilename(attachment.getFilename());
                tsAttachmentModel.setUploaddate(attachment.getUploaddate());
                tsAttachmentModel.setFileext(attachment.getFileext());
                tsAttachmentModel.setCreatetype(attachment.getCreatetype());
//                if ("2".equals(dataFrom)) {
//                    tsAttachmentModel.setCreatetype("2"); // 双随机系统附件
//                } else {
//                    tsAttachment.setCreatetype("1");
//                }
                tsAttachmentService.save(tsAttachmentModel);
            }
//            if("2".equals(dataFrom)){// 如果是双随机的，拷贝完删除
//                for (TSAttachment attachment : attachmentList) {
//                    tsAttachmentService.removeById(attachment.getAttachmentid());
//                }
//            }
        }

        //待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        String type = "";
        if (entertype.equals("individual")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG);//个体工商户
            type = "个体户";
        } else if (entertype.equals("farmer")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD);////农合
            type = "农合";
        } else {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP);//企业异常名录
            type = "企业";
        }
        String busName = null;
        if (bizSpeList.size() > 1) {
            busName = "(" + bizSpeList.size() + "家）关于" + bizSpeList.get(0).getEntname() + "等" + type;

        } else {
            busName = bizSpeList.get(0).getEntname();
        }
        taskListModel.setBusname(busName);
        //经营异常受理保存
        taskListModel = tsBizSpeListService.saveAbnListAccept(aicUser, taskListModel, bizSpeList);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, String> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizSeq);
            result.put("workflowId", taskListModel.getWorkflowid());
            return RestResult.ok(result);
        }
        return OK;
    }

    /**
     * Excel批量列入异常名录受理保存并生成待办
     */
/*    @Transactional
    @RequestMapping(value = "/saveBatchAbnListAccept.do")
    public RestResult<?> batchAbnList(HttpServletRequest request, MultipartFile file, String entertype) {
        AICUser aicUser = getLoginUser(request);

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

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

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

        List<TSBizSpeList> bizSpeList = new ArrayList<TSBizSpeList>();
        for (Map<String, String> map : entList) {
            String regno = map.get("regno");
            if (StringUtils.isBlank(regno)) continue; //忽略异常数据

            TSEntBaseQuery tsEntBaseQueryModel = new TSEntBaseQuery();
            tsEntBaseQueryModel.setRegNO(regno);
//            tsEntBaseQueryModel.setLocalAdm(aicUser.getRegionID());//只列入 本机构监管的主体
            IPage<TSEntBaseQuery> tsEntBaseQueryModelDataGrid = tsEntBaseQueryService.abnormalListByPage(new Page<>(1, 3), tsEntBaseQueryModel);
            List<TSEntBaseQuery> records = tsEntBaseQueryModelDataGrid.getRecords();
            if (CollectionUtils.isNotEmpty(records)) { //过xResult.newInstance(AjaxResult.Status.ERROR,"上传文件中尚未找到主体信息").toString();
                TSEntBaseQuery entBaseModel = records.get(0);
                if (entBaseModel != null && StringUtils.isNotBlank(entBaseModel.getPriPID())) {
                    //做列入前的相关校验：过滤掉不能列入的
                    if ("success".equals(this.validate(entBaseModel.getPriPID(), aicUser, entertype,null))) {
                        TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
                        tsBizSpeListModel.setBizseq(bizSeq);
                        tsBizSpeListModel.setPripid(entBaseModel.getPriPID());
                        tsBizSpeListModel.setRegno(StringUtils.isUscc(entBaseModel.getUscc()) ? entBaseModel.getUscc() : entBaseModel.getRegNO());
                        tsBizSpeListModel.setEntname(entBaseModel.getEntName());
                        tsBizSpeListModel.setEnttype(entBaseModel.getEntType());
                        tsBizSpeListModel.setApprovaldate(LocalDate.now());
                        tsBizSpeListModel.setDecorg(aicUser.getRegionID());
//                        tsBizSpeListModel.setSpereasons(map.get("spereasons"));
//                        tsBizSpeListModel.setSpereasons(null);
                        bizSpeList.add(tsBizSpeListModel);
                    }
                }
            }
        }
        if (bizSpeList.size() == 0) throw new BusinessException("上传文件中尚未找到主体信息");
        //待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        if (entertype.equals("individual")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG);//个体工商户
        } else if (entertype.equals("farmer")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD);//农合
        } else {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP);//企业异常名录
        }

        StringBuffer entname = new StringBuffer("");
        for (int i = 0; i < bizSpeList.size(); i++) {
            if (i > 1) {
                entname.append("等企业");
                break;
            }
            if (i > 0) entname.append("、");
            entname.append(bizSpeList.get(i).getEntname());
        }
        taskListModel.setBusname(entname.toString());
        //列入经营异常 受理保存生成待办
        taskListModel = tsBizSpeListService.saveAbnListAccept(aicUser, taskListModel, bizSpeList);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("tasklistid", taskListModel.getTasklistid());
            resultMap.put("bizseq", bizSeq);
            return RestResult.ok(resultMap);
        }
        throw new BusinessException("内部服务出错，请联系管理员!");
    }*/

    /**
     * 查看待列入企业名单
     *
     * @param tsBizSpeListModel 实体
     * @param rows              分页滴啊小
     * @param page              当前分页
     * @return 分页结果
     * @author lroyia
     * @since 2021年1月22日 15:41:54
     */
    @PostMapping("/selectBSPExptByPageList.do")
    public RestResult<?> selectBSPExptByPageList(TSBizSpeList tsBizSpeListModel, int rows, int page) {
        return RestResult.ok(tsBizSpeListService.selectBSPExptByPageList(tsBizSpeListModel, new Page<>(page, rows)));
    }

    /**
     * 通过业务号查询列入原因及事实理由
     *
     * @param bizSeqId 业务号
     * @return
     */
    @GetMapping(value = "/searchBizSpeByBizSeqId")
    public RestResult<?> searchBizSpeByBizSeqId(String bizSeqId) {
        QueryWrapper<TSBizSpeList> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TSBizSpeList::getBizseq, bizSeqId).eq(TSBizSpeList::getIsRemove, "0");
        return RestResult.ok(tsBizSpeListService.getOne(wrapper, false));
    }

    /**
     * 经营异常拟列入主体名单导出Excel
     *
     * @return
     */
    @GetMapping("exportEntList")
    public RestResult<?> exportEntList(String bizseq, HttpServletRequest request, HttpServletResponse response) {
        AssertUtils.isNotBlank(bizseq);
        List<TSBizSpeList> list = tsBizSpeListService.list(new LambdaQueryWrapper<TSBizSpeList>().eq(TSBizSpeList::getBizseq, bizseq).eq(TSBizSpeList::getIsRemove, "0"));
        List<TSBizSpeListVO> tsBizSpeListVOS = new ArrayList<>();
        list.forEach(each -> {
            TSBizSpeListVO listVO = new TSBizSpeListVO();
            BeanUtils.copyProperties(each, listVO);
            tsBizSpeListVOS.add(listVO);
        });

        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        tsBizSpeListVOS.forEach(each -> {
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, each.getPripid()));
            //经营地址
            if ("9910".equals(each.getEnttype())) {//个体户地址暂存 oploc字段
                each.setAddress(eBaseinfo.getOploc());
            } else {
                each.setAddress(eBaseinfo.getDom());
            }
            each.setRegstate(eBaseinfo.getRegstate());//登记状态
            TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
            if (code != null) {
                each.setRegstateCn(code.getName());
            }
            each.setEstDate(eBaseinfo.getEstdate());//成立日期
            each.setLerepname(eBaseinfo.getLerep());//法定代表人
            if (eBaseinfo.getEnttypeCn() == null) {
                TREntPriseType type = entPriseTypeService.getEntPriseTypeFromCache(each.getEnttype());
                if (type != null) {
                    each.setEntTypeName(type.getDisplayvalue());
                }
            } else {
                each.setEntTypeName(eBaseinfo.getEnttypeCn());
            }
            each.setUscc(StringUtils.isNotEmpty(eBaseinfo.getUniscid()) ? eBaseinfo.getUniscid() : eBaseinfo.getRegno());
        });
        ExcelWriter writer = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //添加响应头信息
            String fileName = "异常主体名单清单.xlsx";
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");//设置类型
            response.setHeader("Pragma", "No-cache");//设置头
            response.setHeader("Cache-Control", "no-cache");//设置头
            response.setDateHeader("Expires", 0);//设置日期头
            //实例化 ExcelWriter，传入输出流，excel格式，表头true
            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);

            //使用Lists.partition 将list集合按指定长度进行切分，避免导出数据量大于excel的上限
            List<List<TSBizSpeListVO>> partition = Lists.partition(tsBizSpeListVOS, 10000);
            for (int i = 1; i <= partition.size(); i++) {
                com.alibaba.excel.metadata.Sheet sheet = new com.alibaba.excel.metadata.Sheet(i, 0, TSBizSpeListVO.class);
                sheet.setSheetName("清单" + i);
                //输出
                writer.write(partition.get(i - 1), sheet);
            }
            writer.finish();
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return OK;
    }

    /**
     * 异常名录审批流程
     * 保存列入异常名录 转接到待办列表中
     */
    @Transactional
    @PostMapping(value = "/exptnext.do")
    public RestResult<?> opentexptlist(HttpServletRequest request, TSBizSpeList tsBizSpeListModel, TSOpinion opinionModel,
                                       String tasklistid, String nextPerformerids, String nextPerformerNames, String nextNodeID, String enterType) {
        AICUser user = getLoginUser(request);
        Map<String, Object> resultMap = new HashMap<>();
        //更新 列入异常名录业务表
        if (tsBizSpeListModel != null && StringUtils.isNotBlank(tsBizSpeListModel.getBizseq())) {
            TSBizSpeList paramModel = new TSBizSpeList();
            paramModel.setBizseq(tsBizSpeListModel.getBizseq());
            paramModel.setIsRemove("0");
            TSTaskList taskListModel = taskListService.selectByTasklistID(tasklistid);
            //批量，业务主体有多个
            List<TSBizSpeList> tsBizSpeList = tsBizSpeListService.selectBSPexptlist(paramModel);
            TSTwfProcessNode processNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
            for (TSBizSpeList bizSpeListModel : tsBizSpeList) {
                //下一步为审核
                if (FlowUtil.EXPTLISTWORKFLOW_HANDLEEXPTLIST.equals(nextNodeID)) {
//                    bizSpeListModel.setSpereasons(tsBizSpeListModel.getSpereasons());
                    if (FlowUtil.EXPTLISTWORKFLOW_EXPTLISTENTER.equals(processNode.getCurrentnode())) {
                        if (StringUtils.isNotEmpty(tsBizSpeListModel.getRemark())) {
                            bizSpeListModel.setRemark(tsBizSpeListModel.getRemark());
                        }
                        bizSpeListModel.setReconsiderationOrg(tsBizSpeListModel.getReconsiderationOrg());
                        bizSpeListModel.setGovernmentOrg(tsBizSpeListModel.getGovernmentOrg());
                        bizSpeListModel.setLitiOrg(tsBizSpeListModel.getLitiOrg());
                        bizSpeListModel.setSpecause(tsBizSpeListModel.getSpecause());
                        bizSpeListModel.setDecisionContent(tsBizSpeListModel.getDecisionContent());
                        bizSpeListModel.setEndApply(tsBizSpeListModel.getEndApply());
                        bizSpeListModel.setEndReason(tsBizSpeListModel.getEndReason());
                    }
                }
            }

            //审批完回到经办人
//            if(FlowUtil.EXPTLISTWORKFLOW_ENDEXPTLIST.equals(nextNodeID) || FlowUtil.EXPTLISTWORKFLOW_OVEREXPTLIST.equals(nextNodeID)){
//                nextPerformerids = taskListModel.getSenderuserid();
//                nextPerformerNames = taskListModel.getSendername();
//            }
            if (StringUtils.isBlank(nextPerformerids)) {
                int order = WorkFlowUtil.checkNextOrder(processNode.getCurrentnode(), nextNodeID);
                // 通过order判断为回退还是前进 >0前进
                if (order > 0) {
                    String opiniontype;
                    if (!"company".equals(enterType)) {
                        opiniontype = "0";
                    } else {
                        opiniontype = "1";
                    }
                    LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TSOpinion::getWorkflowid, taskListModel.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, opiniontype)// 经办为1
                            .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) {
                    String nodeNum = FlowUtil.getChangeLink(nextNodeID);
                    if (!"company".equals(enterType)) {
                        nodeNum = String.valueOf(Integer.parseInt(nodeNum) - 1);
                    }
                    LambdaQueryWrapper<TSOpinion> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(TSOpinion::getWorkflowid, taskListModel.getWorkflowid())
                            .eq(TSOpinion::getOpiniontype, nodeNum)
                            .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();
                }
            }
            //发送
            String[] ids = StringUtils.split(nextPerformerids, Constant.COMMA);
            String[] names = StringUtils.split(nextPerformerNames, Constant.COMMA);
            try {
                tsBizSpeListService.saveAbnListAuditProcess(user, taskListModel, tsBizSpeList, opinionModel, nextNodeID, ids, names);
                if (ids.length == 1 && StringUtils.equals(user.getPrimaryKey(), ids[0])) {
                    resultMap.put("bizseq", tsBizSpeListModel.getBizseq());
                    resultMap.put("nextNodeId", nextNodeID);
                    resultMap.put("taskListId", tasklistid);
                    resultMap.put("workFlowId", taskListModel.getWorkflowid());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return RestResult.ok(resultMap);
    }


    /**
     * 异常名录审批流程
     */
    @PostMapping("/processControl")
    public RestResult<?> processControl(@RequestBody @Validated AbnProcessDto abnProcessDto, BindingResult bindingResult, HttpServletRequest request) {
        AssertUtils.isBndingValidit(bindingResult);
        AICUser user = getLoginUser(request);
        if (user == null) throw new BusinessException("登录超时，请重新登录");
        TSBizSpeList paramModel = new TSBizSpeList();
        paramModel.setBizseq(abnProcessDto.getBizseq());
        paramModel.setIsRemove("0");
        //批量，业务主体有多个
        List<TSBizSpeList> tsBizSpeList = tsBizSpeListService.selectBSPexptlist(paramModel);
        TSTaskList taskListModel = taskListService.selectByTasklistID(abnProcessDto.getTasklistid());
        AssertUtils.isTrue(taskListModel != null && CollectionUtils.isNotEmpty(tsBizSpeList), ResultCode.DATA_NONE);
        try {
            tsBizSpeListService.processControl(abnProcessDto, taskListModel, tsBizSpeList, user);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("列异业务号{}流程扭转出错" + e, abnProcessDto.getBizseq());
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "流程扭转出错");
        }
        return OK;
    }


    /**
     * 审批表
     */
    @PostMapping(value = "/approvalForm.do")
    public RestResult<?> approvalForm(String bizSeq) {
        Map<String, Object> resultMap = new HashMap<>();
        try {

            if (StringUtils.isNotBlank(bizSeq)) {
                bizSeq = bizSeq.trim();
                StringBuilder regno = new StringBuilder();
                StringBuilder ename = new StringBuilder();
                TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
                tsBizSpeListModel.setBizseq(bizSeq);
                List<TSBizSpeList> list = tsBizSpeListService.selectBSPexptlist(tsBizSpeListModel);

                if (CollectionUtils.size(list) > 3) {
                    for (TSBizSpeList tsBizSpeListModel1 : list) {
//                        if (!WebUtil.isEmpty(regno)) {
//                            regno.append(",");
//                        }
//                        regno.append(tsBizSpeListModel1.getRegno());
                        if (StringUtils.isNotBlank(ename)) {
                            ename.append(Constant.COMMA);
                        }
                        ename.append(tsBizSpeListModel1.getEntname());
                    }
                    // 超过3家企业审批表追加显示的内容
                    ename.append("等企业");
                    regno.append("详情请见附件");
                } else {
                    for (TSBizSpeList tsBizSpeListModel1 : list) {
                        if (StringUtils.isNotBlank(regno)) {
                            regno.append(",");
                        }
                        regno.append(tsBizSpeListModel1.getRegno());
                        if (StringUtils.isNotBlank(ename)) {
                            ename.append(",");
                        }
                        ename.append(tsBizSpeListModel1.getEntname());
                    }
                }

                resultMap.put("regno", regno);
                resultMap.put("ename", ename);
                resultMap.put("specause", list.get(0).getSpecause());
                resultMap.put("bizSeq", bizSeq);
                if (CollectionUtils.isNotEmpty(list) && list.get(0).getApprovaldate() != null)
                    resultMap.put("approvaldate", list.get(0).getApprovaldate());
                if (StringUtils.isNotBlank(list.get(0).getSpereasons()))
                    resultMap.put("spereasons", list.get(0).getSpereasons());
                resultMap.put("ReconsiderationOrg", list.get(0).getReconsiderationOrg());
                resultMap.put("GovernmentOrg", list.get(0).getGovernmentOrg());
                resultMap.put("LitiOrg", list.get(0).getLitiOrg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResult.ok(resultMap);
    }

    /**
     * 增加列入信息
     */
    @PostMapping("/addMoreEnt.do")
    public RestResult<?> addMoreEnt(HttpServletRequest request, ModelMap modelMap, String entertype, String blicNO, String entName, String bizSeq, String specause, String spereasons) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);

        TSEntBaseQuery tsEntBaseQueryModel = new TSEntBaseQuery();
        tsEntBaseQueryModel.setRegNO(blicNO);
        tsEntBaseQueryModel.setEntName(entName);
        tsEntBaseQueryModel.setEnterType(entertype);
//        tsEntBaseQueryModel.setLocalAdm(aicUser.getRegionID());//只添加属于本机构监管的主体
        IPage<TSEntBaseQuery> dataGrid = tsBizSpeListService.abnormalListByPage(new Page<>(1, 5), tsEntBaseQueryModel);
        if (CollectionUtils.isEmpty(dataGrid.getRecords())) {
            throw new BusinessException("无法查到该主体信息,请确认查询条件或检查是否已认领");
        } else {
            tsEntBaseQueryModel = dataGrid.getRecords().get(0);
        }

        if (tsEntBaseQueryModel != null && StringUtils.isNotBlank(tsEntBaseQueryModel.getPriPID())) {
            TSBizSpeList bizSpeListModel = new TSBizSpeList();
            bizSpeListModel.setBizseq(bizSeq);
            bizSpeListModel.setPripid(tsEntBaseQueryModel.getPriPID());
            List<TSBizSpeList> tsBizSpeListModels = tsBizSpeListService.selectBSPexptlist(bizSpeListModel);
            if (CollectionUtils.isEmpty(tsBizSpeListModels)) { //避免重复增加
                String validateResult = this.validate(tsEntBaseQueryModel.getPriPID(), aicUser, entertype, null, "true");
                if ("success".equals(validateResult) || "3".equals(validateResult)) {
                    TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
                    tsBizSpeListModel.setBizseq(bizSeq);
                    tsBizSpeListModel.setPripid(tsEntBaseQueryModel.getPriPID());
                    tsBizSpeListModel.setRegno(StringUtils.isUscc(tsEntBaseQueryModel.getUscc()) ? tsEntBaseQueryModel.getUscc() : tsEntBaseQueryModel.getRegNO());
                    tsBizSpeListModel.setEntname(tsEntBaseQueryModel.getEntName());
                    tsBizSpeListModel.setEnttype(tsEntBaseQueryModel.getEntType());
                    tsBizSpeListModel.setApprovaldate(LocalDate.now());
                    tsBizSpeListModel.setDecorg(aicUser.getRegionID());
                    tsBizSpeListModel.setSpereasons(spereasons);
                    tsBizSpeListModel.setSpecause(specause);
                    tsBizSpeListService.saveOrUpdate(tsBizSpeListModel);
                    return OK;
                } else {
                    if ("0".equals(validateResult)) validateResult = "主体尚未被认领,不能列入";
                    else if ("1".equals(validateResult)) validateResult = "非本机构监管主体,不能列入";
                    else if ("2".equals(validateResult)) validateResult = "主体正在被列入,请先完成";
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("blicNO", StringUtils.isUscc(tsEntBaseQueryModel.getUscc()) ? tsEntBaseQueryModel.getUscc() : tsEntBaseQueryModel.getRegNO());
                    return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, validateResult, resultMap);
                }
            }
        }
        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "无法查找该主体信息，请确认查询条件或检查是否已在列表中");
    }

    /**
     * 删除列入信息
     *
     * @param Id
     * @return String
     */
    @PostMapping("/delBizSpeList.do")
    public RestResult<?> delBizSpeList(String Id) {
        tsBizSpeListService.removeById(Id);
        return OK;
    }

//    /**
//     * 列入前监管主体信息验证
//     *
//     * @param pripids
//     * @param entertype
//     * @return String
//     */
//    @PostMapping("/validateBiz.do")
//    public RestResult<?> validateBiz(String pripids, String entertype, HttpServletRequest request) {
//        Map<String, String> resultMap = new HashMap<>();
//        AICUser aicUser = getLoginUser(request);
//        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
//        String[] priPIDs = pripids.split(";");
//        for (String priPID : priPIDs) {
//            String validateResult = this.validate(priPID, aicUser, entertype);
//            if (!"success".equals(validateResult)) {
//                TREntBase paramModel = new TREntBase();
//                paramModel.setPripid(priPID);
//                TREntBase entBaseModel = trEntBaseService.getTrEntBase(paramModel);
//                resultMap.put("blicNO", StringUtils.isUscc(entBaseModel.getUscc()) ? entBaseModel.getUscc() : entBaseModel.getRegno());
//                resultMap.put("entName", entBaseModel.getEntname());
//                resultMap.put("priPID", priPID);
//                resultMap.put("reason", validateResult);
//            }
//
//        }
//        return RestResult.ok(resultMap);
//    }

    /**
     * 列入前监管主体信息验证
     *
     * @param ids
     * @param entertype
     * @param validType
     * @return String
     */
    @PostMapping("/validateBiz")
    public RestResult<?> validateBiz(String ids, String validType, String entertype, String checkInBiz, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotEmpty(validType, entertype);
        String[] idArray = ids.split(";");
        List<Map<String, String>> list = new ArrayList<>();
        for (String id : idArray) {
            String pripid = null;
            if ("CLUE".equals(validType)) {// 线索列异
                Toincludeabn toincludeabn = toincludeabnService.getById(id);
                pripid = toincludeabn.getPripid();
            } else if ("ADDRESS".equals(validType)) {// 地址列异
                pripid = id;
            }
            String validateResult = this.validate(id, aicUser, entertype, validType, checkInBiz);
            if (!"success".equals(validateResult)) {
                EBaseinfo eBaseinfo = eBaseinfoService.getOneByPripid(pripid);
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("uniscid", eBaseinfo.getUniscid());
                resultMap.put("entname", eBaseinfo.getEntname());
                resultMap.put("regno", eBaseinfo.getRegno());
                resultMap.put("reason", validateResult);
                list.add(resultMap);
            }
        }
        return RestResult.ok(list);
    }

    /**
     * 批准流程进入下一步
     *
     * @param taskListModel 待办信息
     * @param entertype     主体类型
     * @return 批准处理结果
     * @author lroyia
     * @since 2021年1月22日 14:31:40
     */
    @PostMapping("/approvalnext.do")
    public RestResult<?> approvalNext(TSTaskList taskListModel, String entertype) {
        // 结果集
        Map<String, Object> resultMap = new HashMap<>();

        StringBuilder pripids = new StringBuilder();
        TSTaskList taskListModel1 = tasklistService.getById(taskListModel.getTasklistid());
        List<TSBizSpeList> list = tsBizSpeListService.list(new LambdaQueryWrapper<TSBizSpeList>().eq(TSBizSpeList::getBizseq, taskListModel1.getBizseqid()));
        if (list.size() > 0) {
            String isHaveLost = "";
            for (TSBizSpeList bizSpeListModel : list) {
                if (StringUtils.isNotBlank(pripids)) {
                    pripids.append(";");
                }
                pripids.append(bizSpeListModel.getPripid());

                //校验：列入名单中是否存在曾因【通过登记的住所或者经营场所无法联系】被列入且未移出,不能因此原因重复列入;若存在,则列入原因无此项可选
                List<TSAbnList> abnList = tsAbnListService.list(new LambdaQueryWrapper<TSAbnList>()
                        .eq(TSAbnList::getPripid, bizSpeListModel.getPripid())
                        .orderByAsc(TSAbnList::getAbntime));
                if (CollectionUtils.isNotEmpty(abnList)) {
                    for (TSAbnList abn : abnList) {
                        if (abn.getRemdate() == null) { //存在未移除 且列入原因是：无法取得联系的,此原因不被重复列入
                            if (("enterprise".equals(entertype) && "4".equals(abn.getSpecause()))
                                    || ("individual".equals(entertype) && "3".equals(abn.getSpecause()))
                                    || ("farmer".equals(entertype) && "3".equals(abn.getSpecause()))) {
                                isHaveLost = "have";
                            }
                        }
                    }
                }

            }
            TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
            tsBizSpeListModel.setSpecause(list.get(0).getSpecause());//列入原因回显
            resultMap.put("spereasons", list.get(0).getSpereasons());
            resultMap.put("tsBizSpeListModel", tsBizSpeListModel);
            resultMap.put("ReconsiderationOrg", list.get(0).getReconsiderationOrg());
            resultMap.put("GovernmentOrg", list.get(0).getGovernmentOrg());
            resultMap.put("LitiOrg", list.get(0).getLitiOrg());
            resultMap.put("isHaveLost", isHaveLost);

        }

        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("pripids", pripids);
        resultMap.put("bizSeq", taskListModel1.getBizseqid());
        resultMap.put("currentNode", currentNode.getCurrentnode());
        resultMap.put("currentLinkTypeID", opinionType);
        resultMap.put("currentNodeName", WorkFlowUtil.getNodeName(currentNode.getCurrentnode()));
        resultMap.put("entertype", entertype);

        return RestResult.ok(resultMap);
    }

    /**
     * 批量列入异常名录Excel表属性集合，顺序与批量到入的Excel文件中的列一致
     */
    public static final List<String> PRIPERSON_FIELD_LIST = initPriPersonFieldList();

    private static List<String> initPriPersonFieldList() {
        List<String> list = new ArrayList<String>();
        list.add("entname");//企业名称
        list.add("regno");  //注册号
        //list.add("specause"); //列入原因（基础字符）
//        list.add("spereasons"); //列入理由（中文）
        return Collections.unmodifiableList(list);
    }

    /**
     * 列入前监管主体信息验证
     *
     * @param id
     * @param aicUser 用户
     * @return String
     * @author Lee
     * @since 2021年10月21日
     */
    private String validate(String id, AICUser aicUser, String entertype, String validType, String checkInBiz) {

        if ("CLUE".equals(validType)) {// 线索列异
            Toincludeabn toincludeabn = toincludeabnService.getById(id);

//            //判断是否已被列异
//            LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
//            abnWrapper.eq(TSAbnList::getPripid, toincludeabn.getPripid())
//                      .eq(TSAbnList::getOperatestatus, "1");
//            List<TSAbnList> abnList = tsAbnListService.list(abnWrapper);
//            if(abnList.size() > 0){
//                for(TSAbnList abn : abnList){
//                    if("nb".equals(abn.getSpecauseType()) && "2".equals(toincludeabn.getIncludeType())){
//                        return "因未公示年报已被列入";
//                    } else if("xj".equals(abn.getSpecauseType()) && "3".equals(toincludeabn.getIncludeType())){
//                        return "因未弄虚作假已被列入";
//                    } else if("sd".equals(abn.getSpecauseType()) && "4".equals(toincludeabn.getIncludeType())){
//                        return "因实地查无已被列入";
//                    }
//                }
//                //abnList.get(0).getEntname()
//            }

            //checkInBiz 发起待办时为true，提交受理时是false
            if (!"false".equals(checkInBiz)) {//发起待办时校验
                //判断是否因未公示或弄虚作假已被列异
                LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
                abnWrapper.eq(TSAbnList::getPripid, toincludeabn.getPripid())
                        .eq(TSAbnList::getOperatestatus, "1");
                List<TSAbnList> abnList = tsAbnListService.list(abnWrapper);
                if (abnList.size() > 0) {
                    for (TSAbnList abn : abnList) {
                        if ("nb".equals(abn.getSpecauseType()) && "2".equals(toincludeabn.getIncludeType())) {
                            return "因未公示年报已被列入";
                        } else if ("xj".equals(abn.getSpecauseType()) && "3".equals(toincludeabn.getIncludeType())) {
                            return "因未弄虚作假已被列入";
                        } else if ("sd".equals(abn.getSpecauseType()) && "4".equals(toincludeabn.getIncludeType())) {
                            List<EntAddressChangeLog> records = iEntAddressChangeLogService.lambdaQuery()
                                    .eq(EntAddressChangeLog::getPripid, abn.getPripid()).list();
                            if (records.size() > 0) {
                                for (EntAddressChangeLog each : records) {
                                    if (each.getChangeDate() == null) continue;
                                    LocalDate date = each.getChangeDate().toLocalDate();
                                    if (date.isAfter(abn.getAbntime())) {
                                        return "因地址原因已列异且未移出";
                                    }
                                }
                            }
                            EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaUpdateWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, abn.getPripid()));
                            return "因在'" + eBaseinfo.getDom() + "'实地查无，已列异且未移出";
                        }
                    }
                    //abnList.get(0).getEntname()
                }
            }

            if (!"true".equals(checkInBiz)) {//提交受理时校验
                // 验证拟列异表记录是否因未公示或弄虚作假在办，即是否存在业务表中
                LambdaQueryWrapper<TSBizSpeList> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TSBizSpeList::getPripid, toincludeabn.getPripid())
                        .ne(TSBizSpeList::getToIncludeId, toincludeabn.getToIncludeId())
                        .notIn(TSBizSpeList::getStatus, "2", "3", "4", "0")
                        .eq(TSBizSpeList::getIsRemove, "0");
                TSBizSpeList speList = tsBizSpeListService.getOne(wrapper, false);
                if (speList != null) {
                    if ("2".equals(speList.getSpecause()) && "2".equals(toincludeabn.getIncludeType())) {
                        return "该主体因未公示年报正在被列入";
                    } else if ("3".equals(speList.getSpecause()) && "3".equals(toincludeabn.getIncludeType())) {
                        return "该主体因未弄虚作假正在被列入";
                    } else if ("4".equals(speList.getSpecause()) && "4".equals(toincludeabn.getIncludeType())) {
                        List<EntAddressChangeLog> records = iEntAddressChangeLogService.lambdaQuery()
                                .eq(EntAddressChangeLog::getPripid, speList.getPripid()).list();
                        if (records.size() > 0) {
                            TSTaskList tsTaskList = taskListService.getOne(new LambdaUpdateWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, speList.getBizseq()));
                            for (EntAddressChangeLog each : records) {
                                if (each.getChangeDate().isAfter(tsTaskList.getCreateTime())) {
                                    return "因地址原因已在列异流程中";
                                }
                            }
                        }
                        EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaUpdateWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, speList.getPripid()));
                        return "因在'" + eBaseinfo.getDom() + "'实地查无，已在列异流程中";
                    }
                    return "该主体正在被列入";
                }
            }


            // 校验是否开业状态
            if ("1".equals(toincludeabn.getIsbatch())) { // 检查多个
                List<Toinroster> toinrosters = toinrosterService.list(new LambdaQueryWrapper<Toinroster>()
                        .eq(Toinroster::getToIncludeId, id));
                String rs = "";
                for (Toinroster toinroster : toinrosters) {
                    rs = tsBizSpeListService.checkEBaseinfo(toincludeabn.getPripid(), entertype, toincludeabn.getIncludeType());
                    if (!"success".equals(rs)) break;
                }
                return rs;
            } else {
                String rs = tsBizSpeListService.checkEBaseinfo(toincludeabn.getPripid(), entertype, toincludeabn.getIncludeType());
                if (!"success".equals(rs)) {
                    return rs;
                }
            }
        } else if ("ADDRESS".equals(validType)) {// 地址列异
            // 校验是否开业状态
            LambdaQueryWrapper<EBaseinfo> entWrapper = new LambdaQueryWrapper<>();
            entWrapper.eq(EBaseinfo::getPripid, id);
            EBaseinfo baseinfo = eBaseinfoService.getOne(entWrapper, false);

            String userOrg = org.apache.commons.lang.StringUtils.substring(aicUser.getRegionID(), 0, 6);
            if (!userOrg.equals(baseinfo.getRegorg())) {
                return "名单中存在其他登记机关登记主体，请重新选择！";
            }

            if (baseinfo != null && !"1".equals(baseinfo.getRegstate())) {
                return "该主体非开业状态";
            }
            // 校验是否已列
            LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
            abnWrapper.eq(TSAbnList::getPripid, id)// pripid
                    .eq(TSAbnList::getOperatestatus, "1");// 列入状态
            if (entertype.equals("company")) {
                abnWrapper.eq(TSAbnList::getSpecause, "4");// 因地址列入
            } else if (entertype.equals("individual") || entertype.equals("farmer")) {
                abnWrapper.eq(TSAbnList::getSpecause, "3");
            }
            TSAbnList abnList = tsAbnListService.getOne(abnWrapper, false);
            if (abnList == null) {// 未被列异
                // 判断是在列异业务中
                if (validInBiz(id, entertype)) {
                    return "该主体正在被列入";
                }
            } else {
                return "该主体已因地址原因列异";
            }
        }
        return "success";
    }

    /**
     * 列入前监管主体信息验证
     *
     * @param priPID  主体pripid
     * @param aicUser 用户
     * @return String
     * @author lroyia
     * @since 2021年1月22日 15:06:48
     */
//    private String validate(String priPID, AICUser aicUser, String entertype) {
//        //已在监管之内
//        TSEntBase tsEntBaseModel = tsEntBaseService.findTsentbaseByID(priPID);
//        if (tsEntBaseModel == null) {
//            return "0";//"主体尚未被认领,不能列入"
//        }
//        //监管机构验证
//        TSEntBaseAddr tsentBaseAddrModel = tsEntBaseAddrService.findTsentBaseAddrBypripid(priPID);
//        if (tsentBaseAddrModel != null) {
//            if (!StringUtils.equals(StringUtils.trimToEmpty(aicUser.getRegionID()),
//                    StringUtils.trimToEmpty(tsentBaseAddrModel.getLocaladm()))) {
//                return "1";//"非本机构监管主体,不能列入"
//            }
//        }
//
//        TSBizSpeList paramModel = new TSBizSpeList();
//        paramModel.setPripid(priPID);
//        List<TSBizSpeList> resultList = tsBizSpeListService.selectBSPexptlist(paramModel);
//        if (CollectionUtils.isEmpty(resultList)) {
//            //tsBizSpeList不存在记录，验证通过
//            return "success";
//        }
//
//        //业务表不空的情况下验证异常名录表
//        List<TSAbnList> abnList = tsAbnListService.selectEntList(priPID);
//        if (CollectionUtils.isEmpty(abnList)) {
//            //TSAbnList不存在记录，说明业务存在正在受理，验证不通过
//            return "2";//"主体正在被列入,请先完成"
//        }
//
//        if (resultList.size() > abnList.size()) {
//            //说明业务存在正在受理
//            return "2";//"主体正在被列入,请先完成";
//        }
//
//        boolean isHaveLost = false;
//        for (TSAbnList abn : abnList) {
//            //存在未移除 且列入原因是：无法取得联系的,此原因不被重复列入
//            if (abn.getRemdate() == null) {
//                if (("enterprise".equals(entertype) && "4".equals(abn.getSpecause()))
//                        || ("individual".equals(entertype) && "3".equals(abn.getSpecause()))
//                        || ("farmer".equals(entertype) && "3".equals(abn.getSpecause()))) {
//                    isHaveLost = true;
//                }
//            }
//        }
//        if (isHaveLost) {
//            return "3";//"主体曾因【通过登记的住所或者经营场所无法联系】被列入,不能因此原因重复列入;若继续列入,则列入原因无此项可选";
//        }
//
//        return "success";
//    }

    /**
     * 查看待列入企业名单
     *
     * @param rows 分页滴啊小
     * @param page 当前分页
     * @return 分页结果
     * @author lroyia
     * @since 2021年1月22日 15:41:54
     */
    @PostMapping("/selectBizSpeByPageList")
    public RestResult<?> selectBizSpeByPageList(int rows, int page) {
        IPage<TSBizSpeList> tsBizSpeListIPage = tsBizSpeListService.selectBizSpeByPageList(new Page<>(page, rows));
        List<TSBizSpeList> bizSpeLists = tsBizSpeListIPage.getRecords();
        for (int i = 0; i < bizSpeLists.size(); i++) {
            bizSpeLists.get(i).setSpecause("广州市市场监督管理局列入经营异常名录决定书");
        }
        return RestResult.ok(bizSpeLists);
    }

    /**
     * 企业经营异常名录导入excel
     *
     * @param httpServletRequest
     * @param file
     * @return
     */
    @PostMapping("upload")
    public RestResult<?> upload(HttpServletRequest httpServletRequest, MultipartFile file, String entertype) {
        AssertUtils.isNotBlank(entertype);
        AssertUtils.isNotNull(file);
        String filename = file.getOriginalFilename();
        if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "文件类型错误");
        }
        Object objList = ExcelIePortUtils.readExcel(file, new BizSpetExcel(), 1, 1);
        List<BizSpetExcel> orderList = (List<BizSpetExcel>) objList;

//        List<String> pripidArray = new ArrayList<>();
//        for(BizSpetExcel bizSpetExcel : orderList){
//            pripidArray.add(bizSpetExcel.getPripids());
//        }
        //校验数据
        if (orderList.size() > 0) {
            String code = orderList.get(0).getCode();
            for (BizSpetExcel bizSpetExcel : orderList) {
                if (StringUtils.isBlank(bizSpetExcel.getPripids())
                        && StringUtils.isBlank(bizSpetExcel.getEntname())
                        && StringUtils.isBlank(bizSpetExcel.getCode())) {
                    return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "导入数值不能为空!");
                } else {
                    if (!bizSpetExcel.getCode().equals(code)) {
                        return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "列入原因不一致!");
                    }
                }
            }
        } else {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "导入数据条数不能为空!");
        }
        //导入数据
        return saveAcceptByUpload(orderList, entertype, orderList.get(0).getCode(), httpServletRequest);
    }

    @Transactional
    public RestResult<?> saveAcceptByUpload(List<BizSpetExcel> bizSpetExcels, String entertype, String code, HttpServletRequest request) {
        Map<String, String> BizSpetExcelMap = new HashMap<>();
        List<String> pripidArray = new ArrayList<>();
        for (BizSpetExcel bizSpetExcel : bizSpetExcels) {
            BizSpetExcelMap.put(bizSpetExcel.getPripids(), bizSpetExcel.getEntname());
            pripidArray.add(bizSpetExcel.getPripids());
        }
        AICUser aicUser = getLoginUser(request);
        //生成业务号
        String bizSeq = UUID.randomUUID().toString();
        List<TSBizSpeList> bizSpeList = new ArrayList<>();
//        Map<String, TCompanyDetails> companyDetailsMap = new HashMap<>();
        HashMap<String, EBaseinfo> eBaseinfosMap = new HashMap<>();
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(EBaseinfo::getPripid, pripidArray);
        List<EBaseinfo> list = eBaseinfoService.list(wrapper);
//        if(list.size()!=pripidArray.size()){
//            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR.setMessage("导入的企业主体不存在!"));
//        }
        for (EBaseinfo each : list) {
            if (!BizSpetExcelMap.get(each.getPripid()).equals(each.getEntname())) {
//                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR.setMessage("导入的主体身份代码和主体名称不一致!"));
                continue;
            }
            if (!each.getRegstate().equals("1")) {
//                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR.setMessage("存在非在营企业!"));
                continue;
            }
            eBaseinfosMap.put(each.getPripid(), each);
        }
        for (int i = 0; i < eBaseinfosMap.size(); i++) {
            EBaseinfo eachEBaseinfo = eBaseinfosMap.get(pripidArray.get(i));
            TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
            tsBizSpeListModel.setBizseq(bizSeq);
            tsBizSpeListModel.setPripid(pripidArray.get(i));
            tsBizSpeListModel.setRegno(eachEBaseinfo.getRegno());
            tsBizSpeListModel.setUniscid(eachEBaseinfo.getUniscid());
            tsBizSpeListModel.setEntname(eachEBaseinfo.getEntname());
            tsBizSpeListModel.setEnttype(eachEBaseinfo.getEnttype());
            tsBizSpeListModel.setApprovaldate(LocalDate.now());
            tsBizSpeListModel.setSpecause(code);
            if (aicUser.getOrgName().contains("广州市")) {
                tsBizSpeListModel.setDecorg(aicUser.getOrgName());
            } else {
                tsBizSpeListModel.setDecorg("广州市" + aicUser.getOrgName());
            }
            bizSpeList.add(tsBizSpeListModel);
        }

        if (bizSpeList.size() == 0) throw new BusinessException("尚未查找到企业信息");

        //待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        if (entertype.equals("individual")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG);//个体工商户
        } else if (entertype.equals("farmer")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD);////农合
        } else {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP);//企业异常名录
        }
        //封装批量操作时的主体名称回显 效果：(企业1、企业2、企业3等企业)
        StringBuilder entname = new StringBuilder("");
        for (int i = 0; i < bizSpeList.size(); i++) {
            if (i > 1) {
                entname.append(entertype.equals("individual") ? "等个体户" : entertype.equals("farmer") ? "等农社" : "等企业");
                break;
            }
            if (i > 0) entname.append("、");
            entname.append(bizSpeList.get(i).getEntname());
        }
        taskListModel.setBusname(entname.toString());
        //经营异常受理保存
        taskListModel = tsBizSpeListService.saveAbnListAccept(aicUser, taskListModel, bizSpeList);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, String> result = new HashMap<>();
            result.put("tasklistid", taskListModel.getTasklistid());
            result.put("bizseq", bizSeq);
            result.put("workflowId", taskListModel.getWorkflowid());
            return RestResult.ok(result);
        }
        return OK;
    }

    /**
     * 判断经营列入该业务是不是已经在办了
     */
    @GetMapping("/checkoutToincludeabn")
    public RestResult<String> checkoutToincludeabn(String toIncludeId) {
        Toincludeabn toincludeabn = toincludeabnService.getById(toIncludeId);
        // 验证拟列异表记录是否在办，即是否存在业务表中
        LambdaQueryWrapper<TSBizSpeList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSBizSpeList::getToIncludeId, toincludeabn.getToIncludeId())
                .eq(TSBizSpeList::getIsRemove, "0");
        TSBizSpeList speList = tsBizSpeListService.getOne(wrapper);
        if (speList != null) {
            LambdaQueryWrapper<TSTaskList> lqw = Wrappers.lambdaQuery();
            lqw.eq(TSTaskList::getBizseqid, speList.getBizseq());
            List<TSTaskList> taskLists = taskListService.list(lqw);
            return RestResult.error(ResultCode.BUSINESS_ASSOCIATED
                    , (taskLists.get(0).getSignloginname() + "已发起列异业务，请勿重复发起。"));
        }

        return RestResult.ok();
    }

    /**
     * Excel地址批量列入异常名录受理保存并生成待办
     */
    @Transactional
    @PostMapping(value = "saveBatchAbnListAccept")
    public RestResult<?> saveBatchAbnListAccept(HttpServletRequest request, String enableListId, String bizseq, String entertype) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        AssertUtils.isNotEmpty(enableListId, bizseq, entertype);

        String cacheKey = CACHE_KEY_PREFIX + enableListId;
        String cacheData = redisService.get(cacheKey);
        if (StringUtils.isBlank(cacheData)) {
            throw new BusinessException("缓存数据已过期，请重新上传文件");
        }
        HashSet<EBaseinfo> enableList = JSONObject.parseObject(cacheData,
            new com.alibaba.fastjson.TypeReference<HashSet<EBaseinfo>>() {});
        List<TSBizSpeList> bizSpeList = new ArrayList<>();
        TSTaskList taskListModel = new TSTaskList();
        String specause = null;
        String type = null;
        if (entertype.equals("individual")) {
            specause = "3";
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ADDRESSBATCH_INDIVIDUAL_TAG);//个体户地址批量列异
            type = "个体户";
        } else if (entertype.equals("farmer")) {
            specause = "3";//农合
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ADDRESSBATCH_FARMER_ADD);//农合地址批量列异
            type = "农合";
        } else {
            specause = "4";//企业异常名录
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ADDRESSBATCH_ENTEREXCP);//企业地址批量列异
            type = "企业";
        }
        String code = aicorgService.getRegionCodeByUser(aicUser);
        for (EBaseinfo eBaseinfo : enableList) {
            TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
            tsBizSpeListModel.setBizseq(bizseq);
            tsBizSpeListModel.setPripid(eBaseinfo.getPripid());
            tsBizSpeListModel.setRegno(eBaseinfo.getRegno());
            tsBizSpeListModel.setUniscid(eBaseinfo.getUniscid());
            tsBizSpeListModel.setEntname(eBaseinfo.getEntname());
            tsBizSpeListModel.setEnttype(eBaseinfo.getEnttype());
            tsBizSpeListModel.setIsRemove("0");
            tsBizSpeListModel.setType(entertype);// 区分主体类型：企业，个体户，农专
            tsBizSpeListModel.setDecorg(code);
            if ("individual".equals(entertype)) {
                tsBizSpeListModel.setDom(eBaseinfo.getOploc());
            } else {
                tsBizSpeListModel.setDom(eBaseinfo.getDom());
            }
            tsBizSpeListModel.setSpecause(specause);
            tsBizSpeListModel.setAreaCode(code);
            tsBizSpeListModel.setDecisionContent(tsBizSpeListService.getDecTempContent(tsBizSpeListModel.getSpecause(),
                    entertype, tsBizSpeListModel.getDecorg()));
            bizSpeList.add(tsBizSpeListModel);
        }
        if (bizSpeList.size() == 0) throw new BusinessException("尚未查找到企业信息");

        String busName = null;
        if (bizSpeList.size() > 1) {
            busName = "(" + bizSpeList.size() + "家）关于" + bizSpeList.get(0).getEntname() + "等" + type;

        } else {
            busName = bizSpeList.get(0).getEntname();
        }
        taskListModel.setBusname(busName);
        taskListModel.setBizseqid(bizseq);
//        列入经营异常 受理保存生成待办
        if (aicUser.getRegionID().length() < 6) {
            Gzaiccode gzaiccode = tUsersService.findOrganization(aicUser.getPrimaryKey());
            aicUser.setRegionID(gzaiccode.getScountrycode());
        }
        taskListModel = tsBizSpeListService.saveAbnListAccept(aicUser, taskListModel, bizSpeList);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("tasklistid", taskListModel.getTasklistid());
            resultMap.put("bizseq", taskListModel.getBizseqid());
            resultMap.put("workFlowId", taskListModel.getWorkflowid());
            return RestResult.ok(resultMap);
        }
        throw new BusinessException("内部服务出错，请联系管理员!");
    }

    /**
     * Excel年报批量列入异常名录受理保存并生成待办
     */
    @Transactional
    @PostMapping(value = "saveBatchAbnListAcceptByNB")
    public RestResult<?> saveBatchAbnListAcceptByNB(HttpServletRequest request, String enableListId, String bizseq, String entertype) {
        AICUser aicUser = getLoginUser(request);
        if (aicUser == null) {
            return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        }
        AssertUtils.isNotEmpty(enableListId, bizseq, entertype);

        String cacheKey = CACHE_KEY_PREFIX + enableListId;
        String cacheData = redisService.get(cacheKey);
        if (StringUtils.isBlank(cacheData)) {
            throw new BusinessException("缓存数据已过期，请重新上传文件");
        }
        HashSet<EBaseinfo> enableList = JSONObject.parseObject(cacheData,
            new com.alibaba.fastjson.TypeReference<HashSet<EBaseinfo>>() {});
        List<TSBizSpeList> bizSpeList = new ArrayList<>();
        TSTaskList taskListModel = new TSTaskList();
        //不需要固定列异原因
//        String specause = null;
        String type = null;
        if (entertype.equals("individual")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG);
            type = "个体户";
        } else if (entertype.equals("farmer")) {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD);
            type = "农合";
        } else {
            taskListModel.setBustype(BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP);
            type = "企业";
        }
        redisService.set(ConstantsUtil.BATCH_NB_REDIS_KEY + bizseq, Constant.TRUE_1_STR);
        String code = aicorgService.getRegionCodeByUser(aicUser);
        for (EBaseinfo eBaseinfo : enableList) {
            TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
            tsBizSpeListModel.setBizseq(bizseq);
            tsBizSpeListModel.setPripid(eBaseinfo.getPripid());
            tsBizSpeListModel.setRegno(eBaseinfo.getRegno());
            tsBizSpeListModel.setUniscid(eBaseinfo.getUniscid());
            tsBizSpeListModel.setEntname(eBaseinfo.getEntname());
            tsBizSpeListModel.setEnttype(eBaseinfo.getEnttype());
            tsBizSpeListModel.setIsRemove("0");
            tsBizSpeListModel.setType(entertype);// 区分主体类型：企业，个体户，农专
            tsBizSpeListModel.setDecorg(code);
            if ("individual".equals(entertype)) {
                tsBizSpeListModel.setDom(eBaseinfo.getOploc());
            } else {
                tsBizSpeListModel.setDom(eBaseinfo.getDom());
            }
            tsBizSpeListModel.setAreaCode(code);
            //不固定列异原因也不生成文书内容
//            tsBizSpeListModel.setDecisionContent(tsBizSpeListService.getDecTempContent(tsBizSpeListModel.getSpecause(),
//                    entertype, tsBizSpeListModel.getDecorg()));
            bizSpeList.add(tsBizSpeListModel);
        }
        if (bizSpeList.size() == 0) throw new BusinessException("尚未查找到企业信息");

        String busName = null;
        if (bizSpeList.size() > 1) {
            busName = "(" + bizSpeList.size() + "家）关于" + bizSpeList.get(0).getEntname() + "等" + type;

        } else {
            busName = bizSpeList.get(0).getEntname();
        }
        taskListModel.setBusname(busName);
        taskListModel.setBizseqid(bizseq);
//        列入经营异常 受理保存生成待办
        if (aicUser.getRegionID().length() < 6) {
            Gzaiccode gzaiccode = tUsersService.findOrganization(aicUser.getPrimaryKey());
            aicUser.setRegionID(gzaiccode.getScountrycode());
        }
        taskListModel = tsBizSpeListService.saveAbnListAccept(aicUser, taskListModel, bizSpeList);
        if (StringUtils.isNotBlank(taskListModel.getTasklistid())) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("tasklistid", taskListModel.getTasklistid());
            resultMap.put("bizseq", taskListModel.getBizseqid());
            resultMap.put("workFlowId", taskListModel.getWorkflowid());
            return RestResult.ok(resultMap);
        }
        throw new BusinessException("内部服务出错，请联系管理员!");
    }

    /**
     * 检查是否批量年报列异
     */
    @GetMapping(value = "checkIsBatchNB")
    public RestResult<?> checkIsBatchNB(String bizSeq) {
        boolean isBatchNB = false;
        if (redisService.exists(ConstantsUtil.BATCH_NB_REDIS_KEY + bizSeq)) {
            isBatchNB = true;
        }
        return RestResult.ok(isBatchNB);
    }

    /**
     * 地址批量列异excel文件导入解析
     *
     * @param file 文件
     * @return 查询结果
     * @author lroyia
     * @since 2021年3月19日 18:27:19
     */
    @Transactional
    @ApiOperation("excel文件查询参数解析")
    @PostMapping("fileParamExplain")
    public RestResult<?> fileParamExplain(HttpServletRequest request, @ApiParam("上传的excel文件") MultipartFile file, String type) {
        AssertUtils.isNotNull(file);
        AssertUtils.isNotBlank(type);
        //保存文件至服务器
        // 获得上传目录
        AICUser curUser = getLoginUser(request);
        if (curUser == null) {
            throw new BusinessException("登录超时，请重新登录");
        }
        String bizseq = UUID.randomUUID().toString();
        String oldFileName = file.getOriginalFilename();
        String ext = StringUtils.isNotBlank(oldFileName) && oldFileName.lastIndexOf(Constant.DOT) > -1 ? oldFileName.substring(oldFileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
        String realPath = CommonConfig.getUploadPathByDate();
        String uploadPath = realPath + File.separator + "abnormal" + File.separator + oldFileName;
        try (InputStream is = file.getInputStream()) {
            fileStorageService.writeFromStream(uploadPath, is);
        } catch (Exception e) {
            log.error("上传出错", e);
            throw new RuntimeException(e.getMessage());
        }
        TSAttachment tsAttachmentModel1 = new TSAttachment();
        tsAttachmentModel1.setBizseq(bizseq);
        tsAttachmentModel1.setFileext(ext);
        tsAttachmentModel1.setFilename(oldFileName);
        tsAttachmentModel1.setTemppath(uploadPath);
        tsAttachmentModel1.setUploaddate(LocalDate.now());
        tsAttachmentModel1.setUserid(curUser.getPrimaryKey());
        tsAttachmentModel1.setUsername(curUser.getName());
        tsAttachmentModel1.setAttachtype("0");// 0代表地址批量列异导入文件
        attachmentService.save(tsAttachmentModel1);
        // 读取excel数据
        List<EntExcel> entDtos;
        try {
            ExcelListener excelListener = ExcelIePortUtils.getExcelListener(file, new EntExcel(), 1, 1);
            Object objList = excelListener.getDatas();
            entDtos = (List<EntExcel>) objList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件数据读取出错");
        }
        HashSet<EBaseinfo> enableList = new HashSet<>();
        ArrayList<DisableListVo> disableList = new ArrayList<>();//不可导
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        Gzaiccode gzaiccode = tUsersService.findOrganization(curUser.getPrimaryKey());
        String scountrycode = gzaiccode.getScountrycode();// 登录用户登记机关码值
        LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
        boolean findRegorg = false;
        String standardRegorg = null;
        for (EntExcel entDto : entDtos) {
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
            EBaseinfo baseinfoModel = new EBaseinfo();
            if (entDto.getUniscid() != null) {
                baseinfoModel.setUniscid(entDto.getUniscid().trim());
            }
            if (entDto.getRegno() != null) {
                baseinfoModel.setRegno(entDto.getRegno().trim());
            }
            if (entDto.getEntname() != null) {
                baseinfoModel.setEntname(entDto.getEntname().trim());
            }

            wrapper.select(EBaseinfo::getPripid, EBaseinfo::getEntname, EBaseinfo::getRegno, EBaseinfo::getName,
                    EBaseinfo::getRegstate, EBaseinfo::getRegstateCn, EBaseinfo::getEnttypeCn, EBaseinfo::getEnttype,
                    EBaseinfo::getUniscid, EBaseinfo::getRegorg);
            if (StringUtils.isNotBlank(baseinfoModel.getUniscid())) {
                wrapper.eq(EBaseinfo::getUniscid, baseinfoModel.getUniscid());
            }
            if (StringUtils.isNotBlank(baseinfoModel.getRegno())) {
                wrapper.eq(EBaseinfo::getRegno, baseinfoModel.getRegno());
            }
            if (StringUtils.isNotBlank(baseinfoModel.getEntname())) {
                wrapper.eq(EBaseinfo::getEntname, baseinfoModel.getEntname());
                // 用名称查主体的时候，可能会出现同名的情况
                List<EBaseinfo> list = eBaseinfoService.list(wrapper);
                if (list.size() > 1) {// 多家同名的时候，返回不可导原因“主体名称重名，请填写准确的统一码或注册号”
                    DisableListVo disableListVo = new DisableListVo();
                    disableListVo.setEntname(baseinfoModel.getEntname());
                    disableListVo.setReason("主体名称重名，请填写准确的统一码或注册号");
                    disableList.add(disableListVo);
                    continue;
                }

            }
            // 避免wrapper没有筛选条件导致全表查询
            if (wrapper.getExpression().getNormal().size() == 0) {
                continue;
            }
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(wrapper);
            if (eBaseinfo != null) {
                String reason = "";
                if (StringUtils.isNotEmpty(eBaseinfo.getRegorg())) {
                    if (!findRegorg) {
                        standardRegorg = eBaseinfo.getRegorg().substring(0, 6);
                    }

                    TRBaseCode baseCode = codeMap.get(eBaseinfo.getRegstate());
                    if (baseCode != null) {
                        eBaseinfo.setRegstateCn(baseCode.getName());
                    }
                    //校验是否为同一个登记机关
                    if (standardRegorg.equals(eBaseinfo.getRegorg().substring(0, 6))) {
                        // 校验是否为同个主体类型（企业、农专、个体户）
                        String baseInfoType;
                        switch (eBaseinfo.getEnttype()) {
                            case "9100":
                            case "9200":
                                baseInfoType = "farmer";
                                break;
                            case "9910":
                                baseInfoType = "individual";
                                break;
                            default:
                                baseInfoType = "company";
                        }
                        if (type.equals(baseInfoType)) {
                            //校验企业状态是否为开业
                            if ("1".equals(eBaseinfo.getRegstate())) {//为开业才可导入
                                // 校验是否已列
                                abnWrapper.clear();
                                abnWrapper.eq(TSAbnList::getPripid, eBaseinfo.getPripid())// pripid
                                        .eq(TSAbnList::getOperatestatus, "1");// 列入状态
                                if (type.equals("company")) {
                                    abnWrapper.eq(TSAbnList::getSpecause, "4");// 因地址列入
                                } else if (type.equals("individual") || type.equals("farmer")) {
                                    abnWrapper.eq(TSAbnList::getSpecause, "3");
                                }
                                TSAbnList abnList = tsAbnListService.getOne(abnWrapper, false);
                                if (abnList == null) {// 未被列异
                                    // 判断是在列异业务中
                                    if (!validInBiz(eBaseinfo.getPripid(), type)) {
                                        enableList.add(eBaseinfo);
                                        findRegorg = true;// 成功添加过一次，就以成功添加的登记机关作为整个名单的判断依据
                                        continue;
                                    } else {
                                        reason = "该主体在办理地址原因列异中";
//                                        disableListVo.setReason("该主体在办理地址原因列异中");
                                    }
                                } else {
                                    reason = "该主体已因地址原因列异";
//                                    disableListVo.setReason("该主体已因地址原因列异");
                                }
                            } else {// 不为开业
                                reason = "主体状态为" + eBaseinfo.getRegstateCn();
//                                disableListVo.setReason("主体状态为" + eBaseinfo.getRegstateCn());//企业状态为不可导原因
                            }
                        } else {
                            TREntPriseType entPriseType = entPriseTypeService.getEntPriseTypeFromCache(eBaseinfo.getEnttype());
                            reason = "主体类型不符合导入名单类型";
                            if (entPriseType != null) {
                                reason = reason + ",为：" + entPriseType.getDisplayvalue();
                            }
//                            disableListVo.setReason(reason);
                        }
                    } else {
                        reason = "登记机关为" + iGzaiccodeService.getNameByCode(eBaseinfo.getRegorg());
//                        disableListVo.setReason("登记机关为" + iGzaiccodeService.getNameByCode(eBaseinfo.getRegorg()));
                    }
                } else {
                    reason = "登记机关为空";
//                    disableListVo.setReason("登记机关为空");
                }
                DisableListVo disableListVo = new DisableListVo();
                disableListVo.setReason(reason);
                disableListVo.setEntname(eBaseinfo.getEntname());
                disableListVo.setUniscid(eBaseinfo.getUniscid());
                disableListVo.setRegno(eBaseinfo.getRegno());
                disableListVo.setRegstateCn(eBaseinfo.getRegstateCn());
                disableList.add(disableListVo);
            } else {
                DisableListVo disableListVo = new DisableListVo();
                disableListVo.setEntname(baseinfoModel.getEntname());
                disableListVo.setUniscid(baseinfoModel.getUniscid());
                disableListVo.setRegno(baseinfoModel.getRegno());
                disableListVo.setReason("主体信息有误");
                disableList.add(disableListVo);
            }
        }

        HashMap<String, Object> resultMap = new HashMap<>();
        String enableListId = UUID.randomUUID().toString();
        String disableListId = UUID.randomUUID().toString();
        resultMap.put("enableListId", enableListId);
        resultMap.put("disableListId", disableListId);

        String enableCacheKey = CACHE_KEY_PREFIX + enableListId;
        String disableCacheKey = CACHE_KEY_PREFIX + disableListId;
        redisService.set(enableCacheKey, JSONObject.toJSONString(enableList), CACHE_EXPIRE_SECONDS);
        redisService.set(disableCacheKey, JSONObject.toJSONString(disableList), CACHE_EXPIRE_SECONDS);

        resultMap.put("enableSize", enableList.size());
        resultMap.put("disableSize", disableList.size());
        resultMap.put("bizseq", bizseq);

        return RestResult.ok(resultMap);
    }

    /**
     * 年报批量列异excel文件导入解析
     *
     * @param file 文件
     * @return 查询结果
     * @author lroyia
     * @since 2021年3月19日 18:27:19
     */
    @Transactional
    @ApiOperation("excel文件查询参数解析")
    @PostMapping("fileParamExplainByNB")
    public RestResult<?> fileParamExplainByNB(HttpServletRequest request, @ApiParam("上传的excel文件") MultipartFile file, String type) {
        AssertUtils.isNotNull(file);
        AssertUtils.isNotBlank(type);
        //保存文件至服务器
        // 获得上传目录
        AICUser curUser = getLoginUser(request);
        if (curUser == null) {
            throw new BusinessException("登录超时，请重新登录");
        }
        String bizseq = UUID.randomUUID().toString();
        String oldFileName = file.getOriginalFilename();
        String ext = StringUtils.isNotBlank(oldFileName) && oldFileName.lastIndexOf(Constant.DOT) > -1 ? oldFileName.substring(oldFileName.lastIndexOf(Constant.DOT)) : StringUtils.EMPTY;
        String filePath = curUser.getPrimaryKey() + File.separator + bizseq + File.separator + oldFileName;
        try (InputStream is = file.getInputStream()) {
            fileStorageService.writeFromStream(CommonConfig.getUploadPath() + File.separator + filePath, is);
        } catch (Exception e) {
            log.error("上传出错", e);
            throw new RuntimeException(e.getMessage());
        }
        TSAttachment tsAttachmentModel1 = new TSAttachment();
        tsAttachmentModel1.setBizseq(bizseq);
        tsAttachmentModel1.setFileext(ext);
        tsAttachmentModel1.setFilename(oldFileName);
        tsAttachmentModel1.setTemppath(filePath);
        tsAttachmentModel1.setUploaddate(LocalDate.now());
        tsAttachmentModel1.setUserid(curUser.getPrimaryKey());
        tsAttachmentModel1.setUsername(curUser.getName());
        tsAttachmentModel1.setAttachtype("0");// 0代表地址批量列异导入文件
        attachmentService.save(tsAttachmentModel1);
        // 读取excel数据
        List<EntExcel> entDtos;
        try {
            ExcelListener excelListener = ExcelIePortUtils.getExcelListener(file, new EntExcel(), 1, 1);
            Object objList = excelListener.getDatas();
            entDtos = (List<EntExcel>) objList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件数据读取出错");
        }
        HashSet<EBaseinfo> enableList = new HashSet<>();
        ArrayList<DisableListVo> disableList = new ArrayList<>();//不可导
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        Gzaiccode gzaiccode = tUsersService.findOrganization(curUser.getPrimaryKey());
        String scountrycode = gzaiccode.getScountrycode();// 登录用户登记机关码值
        LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
        boolean findRegorg = false;
        String standardRegorg = null;
        for (EntExcel entDto : entDtos) {
            LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
            EBaseinfo baseinfoModel = new EBaseinfo();
            if (entDto.getUniscid() != null) {
                baseinfoModel.setUniscid(entDto.getUniscid().trim());
            }
            if (entDto.getRegno() != null) {
                baseinfoModel.setRegno(entDto.getRegno().trim());
            }
            if (entDto.getEntname() != null) {
                baseinfoModel.setEntname(entDto.getEntname().trim());
            }

            wrapper.select(EBaseinfo::getPripid, EBaseinfo::getEntname, EBaseinfo::getRegno, EBaseinfo::getName,
                    EBaseinfo::getRegstate, EBaseinfo::getRegstateCn, EBaseinfo::getEnttypeCn, EBaseinfo::getEnttype,
                    EBaseinfo::getUniscid, EBaseinfo::getRegorg);
            if (StringUtils.isNotBlank(baseinfoModel.getUniscid())) {
                wrapper.eq(EBaseinfo::getUniscid, baseinfoModel.getUniscid());
            }
            if (StringUtils.isNotBlank(baseinfoModel.getRegno())) {
                wrapper.eq(EBaseinfo::getRegno, baseinfoModel.getRegno());
            }
            if (StringUtils.isNotBlank(baseinfoModel.getEntname())) {
                wrapper.eq(EBaseinfo::getEntname, baseinfoModel.getEntname());
                // 用名称查主体的时候，可能会出现同名的情况
                List<EBaseinfo> list = eBaseinfoService.list(wrapper);
                if (list.size() > 1) {// 多家同名的时候，返回不可导原因“主体名称重名，请填写准确的统一码或注册号”
                    DisableListVo disableListVo = new DisableListVo();
                    disableListVo.setEntname(baseinfoModel.getEntname());
                    disableListVo.setReason("主体名称重名，请填写准确的统一码或注册号");
                    disableList.add(disableListVo);
                    continue;
                }

            }
            // 避免wrapper没有筛选条件导致全表查询
            if (wrapper.getExpression().getNormal().size() == 0) {
                continue;
            }
            List<EBaseinfo> eBaseinfoList = eBaseinfoService.list(wrapper);
            if (CollectionUtils.isNotEmpty(eBaseinfoList)) {
                for (EBaseinfo eBaseinfo : eBaseinfoList) {
                    String reason = "";
                    if (StringUtils.isNotEmpty(eBaseinfo.getRegorg())) {
                        if (!findRegorg) {
                            standardRegorg = eBaseinfo.getRegorg().substring(0, 6);
                        }

                        TRBaseCode baseCode = codeMap.get(eBaseinfo.getRegstate());
                        if (baseCode != null) {
                            eBaseinfo.setRegstateCn(baseCode.getName());
                        }
                        //校验是否为同一个登记机关
                        if (standardRegorg.equals(eBaseinfo.getRegorg().substring(0, 6))) {
                            // 校验是否为同个主体类型（企业、农专、个体户）
                            String baseInfoType;
                            switch (eBaseinfo.getEnttype()) {
                                case "9100":
                                case "9200":
                                    baseInfoType = "farmer";
                                    break;
                                case "9910":
                                    baseInfoType = "individual";
                                    break;
                                default:
                                    baseInfoType = "company";
                            }
                            if (type.equals(baseInfoType)) {
                                //校验企业状态是否为开业 为开业才可导入
                                if (!"1".equals(eBaseinfo.getRegstate()) && !"7".equals(eBaseinfo.getRegstate())) {
                                    reason = "主体状态为" + eBaseinfo.getRegstateCn();
                                } else {
                                    enableList.add(eBaseinfo);
                                    findRegorg = true;// 成功添加过一次，就以成功添加的登记机关作为整个名单的判断依据
                                    continue;
                                }
                            } else {
                                TREntPriseType entPriseType = entPriseTypeService.getEntPriseTypeFromCache(eBaseinfo.getEnttype());
                                reason = "主体类型不符合导入名单类型";
                                if (entPriseType != null) {
                                    reason = reason + ",为：" + entPriseType.getDisplayvalue();
                                }
                            }
                        } else {
                            reason = "登记机关为" + iGzaiccodeService.getNameByCode(eBaseinfo.getRegorg());
                        }
                    } else {
                        reason = "登记机关为空";
                    }
                    DisableListVo disableListVo = new DisableListVo();
                    disableListVo.setReason(reason);
                    disableListVo.setEntname(eBaseinfo.getEntname());
                    disableListVo.setUniscid(eBaseinfo.getUniscid());
                    disableListVo.setRegno(eBaseinfo.getRegno());
                    disableListVo.setRegstateCn(eBaseinfo.getRegstateCn());
                    disableList.add(disableListVo);
                }
            } else {
                DisableListVo disableListVo = new DisableListVo();
                disableListVo.setEntname(baseinfoModel.getEntname());
                disableListVo.setUniscid(baseinfoModel.getUniscid());
                disableListVo.setRegno(baseinfoModel.getRegno());
                disableListVo.setReason("主体信息有误");
                disableList.add(disableListVo);
            }

        }

        HashMap<String, Object> resultMap = new HashMap<>();
        String enableListId = UUID.randomUUID().toString();
        String disableListId = UUID.randomUUID().toString();
        resultMap.put("enableListId", enableListId);
        resultMap.put("disableListId", disableListId);

        String enableCacheKey = CACHE_KEY_PREFIX + enableListId;
        String disableCacheKey = CACHE_KEY_PREFIX + disableListId;
        redisService.set(enableCacheKey, JSONObject.toJSONString(enableList), CACHE_EXPIRE_SECONDS);
        redisService.set(disableCacheKey, JSONObject.toJSONString(disableList), CACHE_EXPIRE_SECONDS);

        resultMap.put("enableSize", enableList.size());
        resultMap.put("disableSize", disableList.size());
        resultMap.put("bizseq", bizseq);

        return RestResult.ok(resultMap);
    }

    /**
     * 验证企业是否已在地址列异在办业务中
     *
     * @param pripid 主体id
     * @return true: 在办中；false：未办
     */
    public boolean validInBiz(String pripid, String type) {
        LambdaQueryWrapper<TSBizSpeList> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSBizSpeList::getPripid, pripid).eq(TSBizSpeList::getIsRemove, "0").notIn(TSBizSpeList::getStatus, "2", "3", "4");
        if (type.equals("company")) {
            wrapper.eq(TSBizSpeList::getSpecause, "4");// 因地址列入
        } else if (type.equals("individual") || type.equals("farmer")) {
            wrapper.eq(TSBizSpeList::getSpecause, "3");
        }
        List<TSBizSpeList> list = tsBizSpeListService.list(wrapper);
        return CollectionUtils.isNotEmpty(list);
    }

    /**
     * 地址批量列异错误清单导出
     *
     * @param request
     * @param response
     * @param disableListId
     * @return
     */
    @GetMapping("failEntAddressExport")
    public RestResult<?> failEntAddressExport(HttpServletRequest request, HttpServletResponse response, String disableListId) {
        AssertUtils.isNotEmpty(disableListId);
        String cacheKey = CACHE_KEY_PREFIX + disableListId;
        String cacheData = redisService.get(cacheKey);
        if (StringUtils.isBlank(cacheData)) {
            throw new BusinessException("缓存数据已过期，请重新上传文件");
        }
        List<DisableListVo> list = JSONObject.parseObject(cacheData,
            new com.alibaba.fastjson.TypeReference<List<DisableListVo>>() {});
        String fileName = "地址批量列异错误清单.xlsx";
        tsAttachmentService.exportExcel(request, response, fileName, list);
        return OK;
    }

    /**
     * 列异线索回退
     *
     * @param tasklistid   待办id
     * @param bizseq       业务号
     * @param toIncludeId  拟列异主键id
     * @param returnReason 退回原因
     * @param request
     * @return
     */
    @Transactional
    @PostMapping("returnClue")
    public RestResult<?> returnClue(String tasklistid, String bizseq, String toIncludeId, String returnReason, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotEmpty(tasklistid, bizseq, returnReason, toIncludeId);
        // 找到业务记录，更改状态
        TSBizSpeList speList = new TSBizSpeList();
        speList.setBizseq(bizseq);
        // 只回退未来剔除的企业
        speList.setIsRemove("0");
        List<TSBizSpeList> tsBizSpeLists = tsBizSpeListService.selectBSPexptlist(speList);
        if (CollectionUtils.isEmpty(tsBizSpeLists)) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "业务表为空");
        }
        // 有可能是批量状态
        for (TSBizSpeList bizSpeList : tsBizSpeLists) {
            bizSpeList.setStatus("0");// 设置为线索回退状态
            bizSpeList.setLauptime(LocalDateTime.now());
            tsBizSpeListService.updateById(bizSpeList);
        }
        Toincludeabn toincludeabn = toincludeabnService.getById(toIncludeId);
        if (toincludeabn == null) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "列异线索不存在，无法回退");
        }
        if (StringUtils.isEmpty(toincludeabn.getRegEntryUserId()) || StringUtils.isEmpty(toincludeabn.getRegEntryUserName())) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
        }
        TSTaskList taskList = taskListService.getById(tasklistid);
        // 回退原因保存到意见表
        TSOpinion tsOpinion = new TSOpinion();
        tsOpinion.setWorkflowid(taskList.getWorkflowid());
        tsOpinion.setHandlerid(user.getPrimaryKey());
        tsOpinion.setHandler(user.getName());
        tsOpinion.setOpiniontype("9");
        tsOpinion.setOpinioncontent(returnReason);
        tsOpinion.setIsagree("2");
        tsOpinion.setLauptime(LocalDateTime.now());
        if (tsOpinion.getHandledate() == null) {
            tsOpinion.setHandledate(LocalDateTime.now());
        }

        String[] ids = new String[]{toincludeabn.getRegEntryUserId()};
        String[] names = new String[]{toincludeabn.getRegEntryUserName()};
        try {
            taskListService.updateWorkFlow(user, tsOpinion, taskList, "clueReturn", ids, names);
            taskList.setBusstatus(BaseDataConstant.BUSINESS_STATUS_RETURN_APPLY);
            taskListService.updateById(taskList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("业务号" + bizseq + "列异线索回退失败" + e.getMessage());
            throw new BusinessException("回退失败");
        }

        String dataFrom = toincludeabn.getDataFrom();// 线索来源 （1、年报2、双随机3、日常检查4、应诉检查）
        String dataFromId = toincludeabn.getDataFromId();
        String includeType = toincludeabn.getIncludeType();
        if (StringUtils.isNotEmpty(dataFromId)) {
            if ("2".equals(dataFrom)) {
                // 返回新的dataFromId
                String rs = itsUsualInspectService.backCheck(dataFromId, returnReason, "双随机", "1", includeType, bizseq, toincludeabn.getPripid());
                toincludeabn.setDataFromId(rs);
                toincludeabn.setUpdateTime(LocalDateTime.now());
                toincludeabn.setState("5"); // 线索回退状态
                toincludeabnService.updateById(toincludeabn);
            } else {
                //是否为批量
                if ("1".equals(toincludeabn.getIsbatch())) {
                    String pripids = "";
                    for (int i = 0; i < tsBizSpeLists.size(); i++) {
                        if (i == tsBizSpeLists.size() - 1) {
                            pripids = pripids + tsBizSpeLists.get(i).getPripid();
                        } else {
                            pripids = pripids + tsBizSpeLists.get(i).getPripid() + ";";
                        }
                    }
                    String rs = itsUsualInspectService.backCheck(dataFromId, returnReason, "市场所监管", "2", null, bizseq, pripids);
                    toincludeabn.setDataFromId(rs);
                    toincludeabn.setUpdateTime(LocalDateTime.now());
                    toincludeabn.setState("5"); // 线索回退状态
                    toincludeabnService.updateById(toincludeabn);
                } else {
                    // 同一个检查任务其他未发起的线索一起退回
                    List<Toincludeabn> toincludeabns = toincludeabnService.list(new LambdaQueryWrapper<Toincludeabn>()
                            .eq(Toincludeabn::getDataFromId, dataFromId).eq(Toincludeabn::getState, "0").eq(Toincludeabn::getDataState, "0"));
                    toincludeabns.add(toincludeabn);
                    // 区分投诉处理和日常检查
                    String check = "";
                    if (dataFrom.equals("3")) {
                        check = itsUsualInspectService.backCheck(dataFromId, returnReason, "市场所监管",
                                "1", null, bizseq, toincludeabns.get(0).getPripid());
                    } else {
                        Boolean rs = itsSueInspectService.backCheck(dataFromId, returnReason);
                        if (!rs) throw new BusinessException("回退失败");
                    }
                    for (Toincludeabn toincludeabnModel : toincludeabns) {
                        if (StringUtils.isNotBlank(check)) {
                            toincludeabn.setDataFromId(check);
                        }
                        toincludeabnModel.setState("5");
                        toincludeabnModel.setUpdateTime(LocalDateTime.now());
                        toincludeabnService.updateById(toincludeabnModel);
                    }
                }
            }
        }
        return OK;
    }

    /**
     * 线索作废
     *
     * @param toIncludeId  拟列异id 线索
     * @param deleteReason 作废原因
     * @param request
     * @return
     */
    @PostMapping("deleteClue")
    public RestResult<?> deleteClue(String toIncludeId, String dataFromId, String deleteReason, HttpServletRequest request) {
        AICUser user = getLoginUser(request);
        if (user == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        AssertUtils.isNotEmpty(deleteReason, toIncludeId);
        try {
            tsBizSpeListService.deleteClue(toIncludeId, deleteReason, user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
        return OK;
    }

    /**
     * 线索更新 重新提交或作废
     *
     * @param type       类型 “delete” 废弃 “update” 重新提交
     * @param dataFromId 线索主键
     * @return
     */
    @PostMapping("clueUpdate")
    @ApiOperation(value = "线索更新 重新提交或作废")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型 “delete” 废弃 “update” 重新提交", required = true),
            @ApiImplicitParam(name = "dataFromId", value = "线索主键", required = true)
    })
    public RestResult<?> clueUpdate(String type, String dataFromId) {
        AssertUtils.isNotEmpty(type, dataFromId);
        tsBizSpeListService.updateClue(type, dataFromId);
        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");
        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 = () -> {
                TSBizSpeList tsBizSpeListModel = new TSBizSpeList();
                tsBizSpeListModel.setBizseq(taskListUnionDto.getBizseqid());
                TSOpinion opinionModel = new TSOpinion();
                opinionModel.setWorkflowid(taskListUnionDto.getWorkflowid());
                String enterType = null;

                //批量审核
                if ("review".equals(batchType)) {
                    //判断是什么主体类型业务
                    if (BaseDataConstant.EXPTLIST_TYPE_ADDRESSBATCH_ENTEREXCP.equals(taskListUnionDto.getBustype()) || BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP.equals(taskListUnionDto.getBustype())) {
                        //企业
                        enterType = "company";
                        opinionModel.setOpiniontype("2");
                    } else if (BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG.equals(taskListUnionDto.getBustype()) || BaseDataConstant.EXPTLIST_TYPE_ADDRESSBATCH_INDIVIDUAL_TAG.equals(taskListUnionDto.getBustype())) {
                        //个体
                        enterType = "individual";
                        opinionModel.setOpiniontype("1");
                    } else if (BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD.equals(taskListUnionDto.getBustype()) || BaseDataConstant.EXPTLIST_TYPE_ADDRESSBATCH_FARMER_ADD.equals(taskListUnionDto.getBustype())) {
                        //农专
                        enterType = "farmer";
                        opinionModel.setOpiniontype("1");
                    }
                } else if ("examine".equals(batchType)) {
                    //判断是什么主体类型业务
                    if (BaseDataConstant.EXPTLIST_TYPE_ADDRESSBATCH_ENTEREXCP.equals(taskListUnionDto.getBustype()) || BaseDataConstant.EXPTLIST_TYPE_ENTEREXCP.equals(taskListUnionDto.getBustype())) {
                        //企业
                        enterType = "company";
                        opinionModel.setOpiniontype("3");
                    } else if (BaseDataConstant.EXPTLIST_TYPE_INDIVIDUAL_TAG.equals(taskListUnionDto.getBustype()) || BaseDataConstant.EXPTLIST_TYPE_ADDRESSBATCH_INDIVIDUAL_TAG.equals(taskListUnionDto.getBustype())) {
                        //个体
                        enterType = "individual";
                        opinionModel.setOpiniontype("2");
                    } else if (BaseDataConstant.EXPTLIST_TYPE_FARMER_ADD.equals(taskListUnionDto.getBustype()) || BaseDataConstant.EXPTLIST_TYPE_ADDRESSBATCH_FARMER_ADD.equals(taskListUnionDto.getBustype())) {
                        //农专
                        enterType = "farmer";
                        opinionModel.setOpiniontype("2");
                    }
                }

                opinionModel.setHandler(user.getName());
                opinionModel.setHandlerid(user.getPrimaryKey());
                opinionModel.setOpinioncontent(opinion);
                opentexptlist(request, tsBizSpeListModel, opinionModel, taskListUnionDto.getTasklistid(), finalNextPerformerids, finalNextPerformerNames, nextNodeID, enterType);
                countDownLatch.countDown();//减1
            };
            executorService.submit(runnable);
        }
        try {
            countDownLatch.await(5, TimeUnit.MINUTES);//5分钟超时
        } catch (Exception e) {
            log.error("批量审核/审批失败", e);
        }
        return OK;
    }

    /**
     * 根据列异原因获取决定书模板内容
     *
     * @param specause  列异原因
     * @param entertype 主体类型
     * @param request   请求
     * @return 决定书模板内容
     */
    @GetMapping("getDecContent")
    public RestResult<?> getDecContent(String specause, String entertype, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        AssertUtils.isNotEmpty(specause, entertype);
        if (aicUser == null) return RestResult.error(ResultCode.USER_NOT_LOGGED_IN);
        String code = aicorgService.getRegionCodeByUser(aicUser);
        String decTempContent = tsBizSpeListService.getDecTempContent(specause, entertype, code);
        return RestResult.ok(decTempContent);
    }

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

    @PostMapping("getOldBizSpeListPage")
    public RestResult<?> getOldBizSpeListPage(@RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        return tsBizSpeListService.getOldBizSpeListPage(pageRequestDto);
    }

    @RequestMapping(value = "exportExcelOldBizSpeList")
    public void exportExcelOldBizSpeList(String SAPPROVECODE, HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = null;
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String("列异名单.xls".getBytes(), "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");
            outputStream = response.getOutputStream();
            tsBizSpeListService.exportExcelOldBizSpeList(outputStream, SAPPROVECODE);
        } catch (IOException e) {
            outputStream.close();
            e.printStackTrace();
        } finally {
            outputStream.close();
        }
    }

    @RequestMapping("downLoad")
    public void downLoad(String attachmentid, HttpServletResponse response) throws IOException {
        TSAttachment tsAttachmentModel = attachmentService.queryHistoryFileById(attachmentid);
        if (tsAttachmentModel == null) {
            throw new BusinessException("文件无法找到" + attachmentid);
        }
        Ftp ftp = new Ftp("172.16.74.77", 21, "jxsftp", "aiccs@vsftp_2024_PASSWORD");
        ftp.setMode(FtpMode.Passive);
        String path = tsAttachmentModel.getTemppath();
        final String fileName = FileUtil.getName(path);
        final String dir = StrUtil.removeSuffix(path, fileName);
        response.setHeader("Content-Disposition", "attachment;  filename=\"" +
                new String(tsAttachmentModel.getFilename().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"");
        ftp.download(dir, fileName, response.getOutputStream());
    }
}
