package com.chinaweal.aiccs.aiccs.fraudreg.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.controller.EBaseinfoController;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSWrit;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.EntExcel;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.service.TSOpinionService;
import com.chinaweal.aiccs.aiccs.business.entity.TSTaskList;
import com.chinaweal.aiccs.aiccs.business.entity.TSTwfProcessNode;
import com.chinaweal.aiccs.aiccs.business.service.TSTaskListService;
import com.chinaweal.aiccs.aiccs.business.service.TSTwfProcessNodeService;
import com.chinaweal.aiccs.aiccs.business.service.WorkFlowService;
import com.chinaweal.aiccs.aiccs.fraudreg.dto.RevokeFraudBatchDto;
import com.chinaweal.aiccs.aiccs.fraudreg.entity.FraudBatchBaseinfo;
import com.chinaweal.aiccs.aiccs.fraudreg.entity.RevokeFraudBatch;
import com.chinaweal.aiccs.aiccs.fraudreg.mapper.RevokeFraudBatchMapper;
import com.chinaweal.aiccs.aiccs.fraudreg.service.FraudBatchBaseinfoService;
import com.chinaweal.aiccs.aiccs.fraudreg.service.RevokeFraudBatchService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.market.entity.EntAddressChangeLog;
import com.chinaweal.aiccs.aiccs.market.service.IEntAddressChangeLogService;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelIePortUtils;
import com.chinaweal.aiccs.aiccs.punishment.util.ExcelListener;
import com.chinaweal.aiccs.aiccs.revoke.Vo.DisableListVo;
import com.chinaweal.aiccs.aiccs.temp.service.TemporarySaveService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.FlowUtil;
import com.chinaweal.aiccs.common.util.HandleWorkFlowUtil;
import com.chinaweal.aiccs.common.util.WorkNoUtil;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.solr.entity.EBaseInfoSolrBean;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
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.sso.util.SSOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sh
 * @since 2023-03-14
 */
@Service
@Slf4j
public class RevokeFraudBatchServiceImpl extends BaseServiceImpl<RevokeFraudBatchMapper, RevokeFraudBatch> implements RevokeFraudBatchService {

    @Autowired
    private EBaseinfoService eBaseinfoService;
    @Autowired
    private FraudBatchBaseinfoService fraudBatchBaseinfoService;
    @Autowired
    private TSTaskListService taskListService;
    @Autowired
    private TSAbnListService tsAbnListService;
    @Autowired
    private TSOpinionService tsOpinionService;
    @Autowired
    private WorkFlowService workFlowService;
    @Resource
    private OrgUM orgUM;
    @Autowired
    private AicorgService aicorgService;
    @Autowired
    private TSWorkNoService workNoService;
    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private CreatePdfService createPdfService;
    @Autowired
    TSTwfProcessNodeService tsTwfProcessNodeService;
    @Autowired
    private IEntAddressChangeLogService iEntAddressChangeLogService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Lazy
    @Autowired
    private EBaseinfoController eBaseinfoController;
    @Autowired
    private TemporarySaveService temporarySaveService;

    @Override
    public Map<String, String> startTaskRevokeFraudBatch(String pripids) {
        Map<String, String> resultMap = new HashMap<>();
        RevokeFraudBatch revokeFraudBatch = new RevokeFraudBatch();
        String bizseq = IdUtil.simpleUUID();
        AICUser aicUser = SSOUtil.getUser();
        String xzqh = aicUser.getRegionID().substring(0,6);

        revokeFraudBatch.setBizseq(bizseq);
        revokeFraudBatch.setCreateTime(LocalDateTime.now());
        revokeFraudBatch.setXzqh(xzqh);
        revokeFraudBatch.setUserid(aicUser.getPrimaryKey());
        // 插入到业务关联主体表
        String[] pripidArry = pripids.split(";");
        for (int i = 0; i<pripidArry.length; i++) {
            String pripid = pripidArry[i];
            EBaseinfo eBaseinfo = eBaseinfoService.getById(pripid);
            FraudBatchBaseinfo fraudBatchBaseinfo = new FraudBatchBaseinfo();
            fraudBatchBaseinfo.setId(IdUtil.simpleUUID());
            fraudBatchBaseinfo.setBizseq(bizseq);
            fraudBatchBaseinfo.setPripid(eBaseinfo.getPripid());
            fraudBatchBaseinfo.setUniscid(eBaseinfo.getUniscid());
            fraudBatchBaseinfo.setRegno(eBaseinfo.getRegno());
            fraudBatchBaseinfo.setEntname(eBaseinfo.getEntname());
            fraudBatchBaseinfo.setLerep(eBaseinfo.getLerep());
            fraudBatchBaseinfo.setDom(eBaseinfo.getDom());
            fraudBatchBaseinfo.setRegorg(eBaseinfo.getRegorg());
            fraudBatchBaseinfo.setRegorgCn(eBaseinfo.getRegorgCn());
            fraudBatchBaseinfo.setIsremove("0");
            Boolean isnb = checknb(pripid);
            fraudBatchBaseinfo.setIsnb(isnb ? "0" : "1");
            fraudBatchBaseinfoService.save(fraudBatchBaseinfo);
        }
        // 启动工作流
        TSTaskList tsTaskList = new TSTaskList();
        tsTaskList.setBizseqid(bizseq);
        tsTaskList.setBustype(BaseDataConstant.CANCEL_REVOKE_BATCH);
        // TODO: 2023/3/15  业务名称待定
        tsTaskList.setBusname("");
        //新待办 设置待办信息
        tsTaskList = HandleWorkFlowUtil.createTaskList(tsTaskList, aicUser);
        //开始工作流
        taskListService.startWorkFlow(tsTaskList, aicUser, FlowUtil.CANCELREVOKEBATCHWORKFLOW);
        revokeFraudBatch.setWorkflowid(tsTaskList.getWorkflowid());
        save(revokeFraudBatch);
        // 返回结果
        resultMap.put("tasklistid", tsTaskList.getTasklistid());
        resultMap.put("bizseq", bizseq);
        resultMap.put("workflowId", tsTaskList.getWorkflowid());
        return resultMap;
    }

    @Override
    public Map<String, Object> getRevokeFraudBatch(String bizseq, String workflowId) {
        Map<String, Object> resultMap = new HashMap<>();
        RevokeFraudBatch revokeFraudBatch = getOne(new LambdaQueryWrapper<RevokeFraudBatch>().eq(RevokeFraudBatch::getBizseq, bizseq));
        List<FraudBatchBaseinfo> fraudBatchBaseinfos = fraudBatchBaseinfoService.list(
                new LambdaQueryWrapper<FraudBatchBaseinfo>().eq(FraudBatchBaseinfo::getBizseq, bizseq)
        );
        List<TSOpinion> tsOpinions = tsOpinionService.getOpinionsWithOrg(workflowId);
        resultMap.put("revokeFraudBatch", revokeFraudBatch);
        resultMap.put("fraudBatchBaseinfos", fraudBatchBaseinfos);
        resultMap.put("tsOpinions", tsOpinions);
        return resultMap;
    }

    @Override
    public void saveContent(RevokeFraudBatch revokeFraudBatch) {
        RevokeFraudBatch revokeFraudBatchModel = getOne(new LambdaQueryWrapper<RevokeFraudBatch>()
                .eq(RevokeFraudBatch::getBizseq, revokeFraudBatch.getBizseq()));
        RevokeFraudBatch revokeFraudBatchParam = new RevokeFraudBatch();
        revokeFraudBatchParam.setId(revokeFraudBatchModel.getId());
        if ("tz".equals(revokeFraudBatch.getContentType())) {
            revokeFraudBatchParam.setCxsltzcontent(revokeFraudBatch.getCxsltzcontent());
        } else if ("cx".equals(revokeFraudBatch.getContentType())) {
            revokeFraudBatchParam.setCxsldjcontent(revokeFraudBatch.getCxsldjcontent());
        }
        revokeFraudBatchParam.setUpdateTime(LocalDateTime.now());
        updateById(revokeFraudBatchParam);
    }

    @Override
    public void processControlFraudBatch(RevokeFraudBatchDto revokeFraudBatchDto) {
        TSTaskList taskListModel = taskListService.selectByTasklistID(revokeFraudBatchDto.getTasklistid());
        TSTwfProcessNode twfProcessNode = workFlowService.findCurrentNode(taskListModel.getWorkflowid());
        // 删除暂存
        temporarySaveService.delByBizseq(revokeFraudBatchDto.getBizseq());
        AICUser loginUser = SSOUtil.getUser();
        String link = String.format("%s_%s", twfProcessNode.getCurrentnode(), revokeFraudBatchDto.getNextNodeID());
        switch (link) {
            case "startTZAccept_handleCancelTZ": // 听证送审核
                toHandleCaseTZ(revokeFraudBatchDto);
                break;
            case "startTZAccept_overPlCxFinish": // 听证经办结束流程
                break;
            case "handleCancelTZ_startTZAccept": // 听证审核回退到经办
            case "approvalCancelTZ_handleCancelTZ": // 听证退回审核
            case "handleCancelDJ_startDJAccept": // 撤销审核回退到经办
            case "approvalCancelDJ_handleCancelDJ": // 撤销退回审核
                backLastStep(revokeFraudBatchDto, taskListModel, twfProcessNode.getCurrentnode(), revokeFraudBatchDto.getNextNodeID());
                break;
            case "handleCancelTZ_approvalCancelTZ": // 听证送审批
                break;
            case "approvalCancelTZ_startDJAccept": // 听证审批送撤销经办
                break;
            case "startDJAccept_handleCancelDJ": // 撤销送审核
                toHandleCaseCX(revokeFraudBatchDto);
                break;
            case "startDJAccept_overPlCxFinish": // 撤销经办结束流程
                break;
            case "handleCancelDJ_approvalCancelDJ": // 撤销送审批
                break;
            case "approvalCancelDJ_endApprovalCancel": // 正常结束
                toEnd(revokeFraudBatchDto);
                break;
            default:
                throw new RuntimeException("流程扭转出错");
        }
        // 流程推进
        taskListService.updateWorkFlow(loginUser, revokeFraudBatchDto.getOpinion(), taskListModel,
                revokeFraudBatchDto.getNextNodeID(), revokeFraudBatchDto.getNextPerformerIds(), revokeFraudBatchDto.getNextPerformerNames());
    }

    @Override
    public void toHandleCaseTZ(RevokeFraudBatchDto revokeFraudBatchDto) {
        RevokeFraudBatch revokeFraudBatch = revokeFraudBatchDto.getRevokeFraudBatch();
        RevokeFraudBatch revokeFraudBatchModel = getOne(new LambdaQueryWrapper<RevokeFraudBatch>()
                .eq(RevokeFraudBatch::getBizseq, revokeFraudBatchDto.getBizseq()));

        RevokeFraudBatch revokeFraudBatchParam = new RevokeFraudBatch();

        revokeFraudBatchParam.setId(revokeFraudBatchModel.getId());
        revokeFraudBatchParam.setComplaintreason(revokeFraudBatch.getComplaintreason());
        revokeFraudBatchParam.setHandlereason(revokeFraudBatch.getHandlereason());
        revokeFraudBatchParam.setHandlereasonCn(revokeFraudBatch.getHandlereasonCn());
        revokeFraudBatchParam.setHandleresult(revokeFraudBatch.getHandleresult());
        revokeFraudBatchParam.setTzremarks(revokeFraudBatch.getTzremarks());
        revokeFraudBatchParam.setUpdateTime(LocalDateTime.now());

        updateById(revokeFraudBatchParam);
    }

    @Override
    public void toHandleCaseCX(RevokeFraudBatchDto revokeFraudBatchDto) {
        RevokeFraudBatch revokeFraudBatch = revokeFraudBatchDto.getRevokeFraudBatch();
        RevokeFraudBatch revokeFraudBatchModel = getOne(new LambdaQueryWrapper<RevokeFraudBatch>()
                .eq(RevokeFraudBatch::getBizseq, revokeFraudBatchDto.getBizseq()));
        RevokeFraudBatch revokeFraudBatchParam = new RevokeFraudBatch();

        revokeFraudBatchParam.setId(revokeFraudBatchModel.getId());
        revokeFraudBatchParam.setDjremarks(revokeFraudBatch.getDjremarks());
        updateById(revokeFraudBatchParam);
    }

    @Override
    public void toEnd(RevokeFraudBatchDto revokeFraudBatchDto) {

    }

    @Override
    public void backLastStep(RevokeFraudBatchDto revokeFraudBatchDto, TSTaskList taskList, String currentNode, String nextNode) {
        String userId = workFlowService.findLastTwfprocessnodeByProcessidAndNodename(taskList.getWorkflowid(), currentNode, nextNode);
        AICUser handler = orgUM.findUserByPrimaryKey(userId);
        revokeFraudBatchDto.setNextPerformerIds(new String[]{handler.getPrimaryKey()});
        revokeFraudBatchDto.setNextPerformerNames(new String[]{handler.getName()});
    }

    @Override
    public RestResult<?> createDocument(String bizseq, String contentType) {
        RevokeFraudBatch revokeFraudBatchModel = getOne(new LambdaQueryWrapper<RevokeFraudBatch>()
                .eq(RevokeFraudBatch::getBizseq, bizseq));
        if ("tz".equals(contentType) && StringUtils.isBlank(revokeFraudBatchModel.getCxsltzcontent())) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"请先保存文书模板");
        }
        if ("cx".equals(contentType) && StringUtils.isBlank(revokeFraudBatchModel.getCxsldjcontent())) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"请先保存文书模板");
        }
        AICUser aicUser = SSOUtil.getUser();
        LambdaQueryWrapper<FraudBatchBaseinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FraudBatchBaseinfo::getBizseq, bizseq).eq(FraudBatchBaseinfo::getIsremove, "0");
        List<FraudBatchBaseinfo> fraudBatchBaseinfos = fraudBatchBaseinfoService.list(wrapper);
        String orgCode = aicorgService.getRegionCodeByUser(aicUser);
        LocalDateTime nowDateTime = LocalDateTime.now();
        LocalDate now = LocalDate.now();

        String workNoType = "";
        String path = "";
        String content = "";
        String nameend = "";
        if ("tz".equals(contentType)) {
            workNoType = WorkNoUtil.WORKNOTYPE_43;
            path = "static" + File.separator +  "template" + File.separator + "revokeFraudBatchTZ.docx";
            content = revokeFraudBatchModel.getCxsltzcontent();
            nameend = "-听证告知书.pdf";
        } else if ("cx".equals(contentType)) {
            workNoType = WorkNoUtil.WORKNOTYPE_44;
            path = "static" + File.separator +  "template" + File.separator + "revokeFraudBatchCX.docx";
            content = revokeFraudBatchModel.getCxsldjcontent();
            nameend = "-撤销决定书.pdf";
        }
        for (FraudBatchBaseinfo fraudBatchBaseinfo : fraudBatchBaseinfos) {
            // 已经存在则不生成
            LambdaQueryWrapper<TSWrit> writWrapper = new LambdaQueryWrapper<>();
            writWrapper.eq(TSWrit::getBizseq, bizseq).eq(TSWrit::getPripid, fraudBatchBaseinfo.getPripid()).eq(TSWrit::getWritstype, workNoType);
            List<TSWrit> writs = tsWritService.list(writWrapper);
            if(writs.size() > 0) continue;
            // 生成文书表数据
            TSWrit tsWritModel = new TSWrit();
            String tswritId = UUID.randomUUID().toString();
            tsWritModel.setWritsid(tswritId);
            tsWritModel.setBizseq(bizseq);
            tsWritModel.setAreaCode(orgCode);
            String writsNo = workNoService.getWritsNoCurrency(workNoType, orgCode);
            tsWritModel.setWritsno(writsNo);
            tsWritModel.setWritstype(workNoType);
            tsWritModel.setPripid(fraudBatchBaseinfo.getPripid());
            tsWritModel.setWritsname(fraudBatchBaseinfo.getEntname() + nameend);
            tsWritModel.setCreatetime(nowDateTime);
            tsWritModel.setContent(content);
            tsWritService.save(tsWritModel);

            // 生成决定书附件
            HashMap<String, Object> map = new HashMap<>();
            String cityName = Constant.NM_REGION_CODE.get(tsWritModel.getAreaCode().substring(0,4)+"00");
            String areaName = Constant.NM_LOC_REGION_CODE.get(tsWritModel.getAreaCode());
            areaName = cityName + areaName;
            map.put("areaName",areaName);
            map.put("writsno",tsWritModel.getWritsno());
            map.put("htmlContent",tsWritModel.getContent());
            String approveDate = DateUtils.localDateFormat(now, "yyyy年MM月dd日");
            map.put("approveDate",approveDate);
            map.put("entName",fraudBatchBaseinfo.getEntname());
            map.put("entCerName","");
            map.put("uniscid",fraudBatchBaseinfo.getUniscid());
            map.put("dom",fraudBatchBaseinfo.getDom());
            map.put("lerep",fraudBatchBaseinfo.getLerep());
            String pdfPath = createPdfService.createPdfWithHtmlTemplate(bizseq, path, map);

            // 更新文件路径
            tsWritModel.setPath(pdfPath);
            tsWritService.updateById(tsWritModel);
        }
        return RestResult.ok();
    }

    /**
     * 检查是否年报
     * @param pripid
     * @return
     */
    public Boolean checknb(String pripid) {
        LocalDate abntime = LocalDate.now();
        int year = abntime.getYear();
        LocalDate boundary =  LocalDate.of(year, 7, 1);
        int check = 0;
        Boolean isnb = false;
        if (abntime.isBefore(boundary)) { // 查两年前是否年报
            check = tsAbnListService.checknb(pripid, String.valueOf(year-2));
        } else {
            // 查去年是否年报
            check = tsAbnListService.checknb(pripid, String.valueOf(year-1));
        }
        if (check>0)isnb = true;
        return isnb;
    }

    @Override
    public RestResult<?> queryRevokeFraudBatchInfo(String bizseq) {
        RevokeFraudBatch revokeFraudBatch = getOne(new LambdaQueryWrapper<RevokeFraudBatch>().eq(RevokeFraudBatch::getBizseq, bizseq));
        TSTwfProcessNode tsTwfProcessNode = tsTwfProcessNodeService.getOne(
                new LambdaQueryWrapper<TSTwfProcessNode>()
                        .eq(TSTwfProcessNode::getProcessid, revokeFraudBatch.getWorkflowid()).eq(TSTwfProcessNode::getStatus,0));
        Map map = new HashMap();
        map.put("revokeFraudBatch", revokeFraudBatch);
        map.put("currentnode", tsTwfProcessNode.getCurrentnode());
        return RestResult.ok(map);
    }

    @Override
    public RestResult<?> importExcel(HttpServletRequest request, MultipartFile file) {
        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("文件数据读取出错");
        }
        if (entDtos.size() > 509) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR,"导入数量不能大于500条");
        }
        AICUser aicUser = SSOUtil.getUser();
        HashSet<FraudBatchBaseinfo> enableList = new HashSet<>();
        ArrayList<DisableListVo> disableList = new ArrayList<>();//不可导

        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,EBaseinfo::getDom);
            if(com.chinaweal.aiccs.common.util.StringUtils.isNotBlank(baseinfoModel.getUniscid())){
                wrapper.eq(EBaseinfo::getUniscid, baseinfoModel.getUniscid());
            }
            if(com.chinaweal.aiccs.common.util.StringUtils.isNotBlank(baseinfoModel.getRegno())){
                wrapper.eq(EBaseinfo::getRegno, baseinfoModel.getRegno());
            }
            if(com.chinaweal.aiccs.common.util.StringUtils.isNotBlank(baseinfoModel.getEntname())) {
                wrapper.eq(EBaseinfo::getEntname, baseinfoModel.getEntname());
                // 用名称查主体的时候，可能会出现同名的情况
                // 避免wrapper没有筛选条件导致全表查询
                if (wrapper.getExpression().getNormal().size() == 0) {
                    continue;
                }
                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 (!aicUser.getRegionID().equals(eBaseinfo.getRegorg())) {
                    reason = "主体登记机关与账号人员所属机关不一致的主体";
                } else if ("4".equals(eBaseinfo.getEntStatus())) {
                    reason = "主体状态为注销";
                } else if ("5".equals(eBaseinfo.getEntStatus())) {
                    reason = "主体状态为撤销";
                } else if ("6".equals(eBaseinfo.getEntStatus())) {
                    reason = "主体状态为迁出";
                } else {
                    LambdaQueryWrapper<EntAddressChangeLog> addressWrapper = new LambdaQueryWrapper<>();
                    addressWrapper.eq(EntAddressChangeLog :: getPripid, eBaseinfo.getPripid());
                    List<EntAddressChangeLog> entAddressChangeLogs = iEntAddressChangeLogService.list(addressWrapper);
                    if (entAddressChangeLogs.size() > 0) {
                        reason = "存在地址变更记录";
                    } else {
                        LambdaQueryWrapper<FraudBatchBaseinfo> frbWrapper = new LambdaQueryWrapper<>();
                        frbWrapper.eq(FraudBatchBaseinfo :: getPripid, eBaseinfo.getPripid()).eq(FraudBatchBaseinfo :: getIsremove, "0");
                        List<FraudBatchBaseinfo> fraudBatchBaseinfos = fraudBatchBaseinfoService.list(frbWrapper);
                        if (fraudBatchBaseinfos.size() > 0) {
                            reason = "已在撤销设立登记业务流程中";
                        } else {
                            // todo 判断是否锁定，暂无接口
                            // 校验通过
                            FraudBatchBaseinfo fraudBatchBaseinfo = new FraudBatchBaseinfo();
                            fraudBatchBaseinfo.setPripid(eBaseinfo.getPripid());
                            fraudBatchBaseinfo.setUniscid(eBaseinfo.getUniscid());
                            fraudBatchBaseinfo.setRegno(eBaseinfo.getRegno());
                            fraudBatchBaseinfo.setEntname(eBaseinfo.getEntname());
                            fraudBatchBaseinfo.setRegorg(eBaseinfo.getRegorg());
                            fraudBatchBaseinfo.setDom(eBaseinfo.getDom());
                            if(com.chinaweal.aiccs.common.util.StringUtils.isEmpty(eBaseinfo.getRegorgCn())){
                                fraudBatchBaseinfo.setRegorgCn(iGzaiccodeService.getNameByCode(eBaseinfo.getRegorg()));
                            }
                            Boolean isnb = checknb(eBaseinfo.getPripid());
                            fraudBatchBaseinfo.setIsnb(isnb ? "是" : "否");
                            LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
                            abnWrapper.eq(TSAbnList::getPripid, eBaseinfo.getPripid()).eq(TSAbnList::getSpecause, "4");
                            List<TSAbnList> abnLists = tsAbnListService.list(abnWrapper);
                            fraudBatchBaseinfo.setIsabn(abnLists.size() > 0 ? "是" : "否");
                            enableList.add(fraudBatchBaseinfo);
                            continue;
                        }
                    }
                }
                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<>();
        resultMap.put("enableList",enableList);
        resultMap.put("disableList",disableList);

        resultMap.put("enableSize", enableList.size());
        resultMap.put("disableSize", disableList.size());
        return RestResult.ok(resultMap);
    }

    @Override
    public RestResult<?> queryEntlockAbnInfo(String pripid) {
        Map<String, Object> result = new HashMap();
        // 查询地址列入记录
        LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
        abnWrapper.eq(TSAbnList::getPripid, pripid).eq(TSAbnList::getSpecause, "4");
        List<TSAbnList> abnLists = tsAbnListService.list(abnWrapper);
        // todo 查询锁定记录
        result.put("abnList", abnLists);
        return RestResult.ok(result);
    }

    @Override
    public RestResult<?> getBasePage(PageRequestDto pageRequestDto, HttpServletRequest request) {
        RestResult<?> rs = eBaseinfoController.getBasePage(pageRequestDto, request);
        IPage<EBaseInfoSolrBean> resultPage = (IPage<EBaseInfoSolrBean>) rs.getData();
        List<FraudBatchBaseinfo> fraudBatchBaseinfos = new ArrayList<>();

        Page<FraudBatchBaseinfo> page = new Page<>();
        if(CollectionUtils.isNotEmpty(resultPage.getRecords())){
            for (EBaseInfoSolrBean record : resultPage.getRecords()) {
                FraudBatchBaseinfo fraudBatchBaseinfo = new FraudBatchBaseinfo();
                // 校验通过
                fraudBatchBaseinfo.setPripid(record.getPripid());
                fraudBatchBaseinfo.setUniscid(record.getUniscid());
                fraudBatchBaseinfo.setRegno(record.getRegno());
                fraudBatchBaseinfo.setEntname(record.getEntname());
                fraudBatchBaseinfo.setRegorg(record.getRegorg());
                fraudBatchBaseinfo.setDom(record.getDom());
                fraudBatchBaseinfo.setRegorgCn(record.getRegorgCn());
                Boolean isnb = checknb(record.getPripid());
                fraudBatchBaseinfo.setIsnb(isnb ? "是" : "否");
                LambdaQueryWrapper<TSAbnList> abnWrapper = new LambdaQueryWrapper<>();
                abnWrapper.eq(TSAbnList::getPripid, record.getPripid()).eq(TSAbnList::getSpecause, "4");
                List<TSAbnList> abnLists = tsAbnListService.list(abnWrapper);
                fraudBatchBaseinfo.setIsabn(abnLists.size() > 0 ? "是" : "否");
                fraudBatchBaseinfos.add(fraudBatchBaseinfo);
            }
            page.setTotal(resultPage.getTotal());
            page.setRecords(fraudBatchBaseinfos);
        }
        return RestResult.ok(page);
    }
}
