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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.vo.TSBizSpeListVO;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.TSAttachmentMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.auditing.entity.TSOpinion;
import com.chinaweal.aiccs.aiccs.auditing.mapper.TSOpinionMapper;
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.entbase.entity.TREntPriseType;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntPriseTypeService;
import com.chinaweal.aiccs.aiccs.inspect.service.TSWorkNoService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.*;
import com.chinaweal.aiccs.aiccs.seriousillegal.mapper.TSBizSerIllegallMapper;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSForIllOperatingBnService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSForIllOperatingListService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import com.chinaweal.aiccs.aiccs.system.service.TRBaseCodeService;
import com.chinaweal.aiccs.aiceps.annual.service.NoAnnualService;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.util.*;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.entity.TUsers;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aiccs.outside.api.SOAServiceApi;
import com.chinaweal.aiccs.outside.service.SMSServiceImpl;
import com.chinaweal.aiccs.outside.vo.ChangRuanResult;
import com.chinaweal.aiccs.outside.vo.Investor;
import com.chinaweal.aiccs.outside.vo.Personnel;
import com.chinaweal.aiccs.redis.RedisService;
import com.chinaweal.aicorg.model.AICUser;
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 com.dtflys.forest.http.ForestResponse;
import com.esms.common.entity.GsmsResponse;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.restlet.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 列入严重违法企业名单业务表 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-01-26
 */
@Service
@Slf4j
public class TSBizSerIllegalServiceImpl extends BaseServiceImpl<TSBizSerIllegallMapper, TSBizSerIllegal> implements TSBizSerIllegalService {

    @Autowired
    private TSTaskListService taskListService;

    @Autowired
    private TSAbnListService abnListService;

    @Autowired
    private TSSerIllegalListService serIllegalListService;

    @Autowired
    private TSWorkNoService workNoService;

    @Autowired
    private TSWritService tsWritService;
    @Autowired
    private AicorgService aicorgService;
    @Resource
    private SOAServiceApi soaServiceApi;
    @Autowired
    private TSForIllOperatingBnService tsForIllOperatingBnService;
    @Autowired
    private TRBaseCodeService baseCodeService;
    @Resource
    @Lazy
    private EBaseinfoService eBaseinfoService;
    @Resource
    private TUsersService tUsersService;
    @Resource
    @Lazy
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    private WorkFlowService workFlowService;

    @Autowired
    private TSTwfProcessNodeService tsTwfProcessNodeService;
    @Autowired
    private TSForIllOperatingListService tsForIllOperatingListService;
    @Resource
    private TSOpinionMapper tsOpinionMapper;
    @Resource
    private TSAttachmentMapper tsAttachmentMapper;
    @Resource
    private TREntPriseTypeService entPriseTypeService;
    @Resource
    private SMSServiceImpl smsService;
    @Resource
    private AbnSerSmsLogService abnSerSmsLogService;


    @Override
    public List<TSBizSerIllegal> selectBizSerIllegalModels(TSBizSerIllegal tsBizSerIllegalModel) {
        return baseMapper.selectBizSerIllegalModels(tsBizSerIllegalModel);
    }

    @Override
    public TSTaskList saveSerIllegalAccept(AICUser aicUser, TSTaskList taskListModel, List<TSBizSerIllegal> bizSerList) {
        if (StringUtils.isBlank(taskListModel.getTasklistid())) {

            for (TSBizSerIllegal bizSerIllegalModel : bizSerList) {
                bizSerIllegalModel.setIntoSponsorIllegal(aicUser.getName()); // 流程启动人(主办人)
                bizSerIllegalModel.setStatus("9"); // 流程启动把状态设置为 "受理中"
                bizSerIllegalModel.setLauptime(LocalDateTime.now());
                saveOrUpdate(bizSerIllegalModel);
            }
            String definedname = FlowUtil.SERILLEGALWORKFLOW;//严重违法失信名单流程模板
            //新待办
            taskListModel = HandleWorkFlowUtil.createTaskList(taskListModel, aicUser);
            //开始工作流
            taskListService.startWorkFlow(taskListModel, aicUser, definedname);
        }
        return taskListModel;
    }

    @Override
    public IPage<TSBizSerIllegal> selectSerIllegalByPageList(int rows, int page, TSBizSerIllegal tsBizSerIllegalModel) {
        return baseMapper.selectSerIllegalByPageList(tsBizSerIllegalModel, new Page<>(page, rows));
    }

    @Transactional
    @Override
    public TSTaskList saveSerIllegalAuditProcess(AICUser user, TSTaskList taskListModel, List<TSBizSerIllegal> tsBizSerIllegalModels,
                                                 TSOpinion opinionModel, String nextNodeID, String[] nextPerformerids, String[] nextPerformerNames, String type, String forillOperaOrSerillega) {
        String decOrgCode = aicorgService.getRegionCodeByUser(user);
        try {
            for (TSBizSerIllegal bizSerIllegalModel : tsBizSerIllegalModels) {

                if (FlowUtil.SERILLEGALWORKFLOW_HANDLESERILLEGAL.equals(nextNodeID)) { //审批时操作
                    bizSerIllegalModel.setStatus("1"); // 审批流程中把状态设置成 "审批中"
                    bizSerIllegalModel.setLauptime(LocalDateTime.now());
                    saveOrUpdate(bizSerIllegalModel);
                }

                //添加严重违法失信
                if (FlowUtil.SERILLEGALWORKFLOW_ENDSERILLEGAL.equals(nextNodeID)) { //完结时
                    if (bizSerIllegalModel.getEndApply() != null && bizSerIllegalModel.getEndApply().equals("2")) { //不作列严操作
                        bizSerIllegalModel.setApprovaldate(LocalDate.now());//核准日期
                        bizSerIllegalModel.setStatus("4"); // 9 受理中、1 审批中、2 已通过、3 不通过、4 通过结束流程
                        bizSerIllegalModel.setLauptime(LocalDateTime.now());
                        updateById(bizSerIllegalModel);
                        continue;
                    }
                    if (BaseDataConstant.SERILLEGAL_TYPE_INCLUDEDILLEGAL.equals(taskListModel.getBustype())) {//拟列入
                        TSForIllOperatingBn forIllOperatingBnModel = new TSForIllOperatingBn();
                        forIllOperatingBnModel.setIlloperatingid(bizSerIllegalModel.getIllegallistid());
                        forIllOperatingBnModel.setBizseq(bizSerIllegalModel.getBizseq());
                        if ("timeout".equals(type) && StringUtils.isNotBlank(bizSerIllegalModel.getAbnlistid())) {//异常名录期限届满列入
                            forIllOperatingBnModel.setAbnlistid(bizSerIllegalModel.getAbnlistid());

                            //异常名录中 标记为已列入严重违法失信
                            TSAbnList abnListModel = abnListService.getById(bizSerIllegalModel.getAbnlistid());
                            if (abnListModel != null && StringUtils.isNotBlank(abnListModel.getAbnlistid())) {
                                abnListModel.setRemexcpres("6"); // 列入经营异常名录届满3年仍未履行公示义务的，列入严重违法企业名单，自动移出
                                abnListModel.setRemSponsor(bizSerIllegalModel.getIntoSponsorIllegal()); // 列入严重违法失信的启动人就是移出经营异常名录的主办人
                                abnListModel.setRemdate(LocalDate.now());
                                abnListModel.setOperatestatus("4"); //标记严重违法失信
                                abnListService.updateById(abnListModel);
                            }
                        }
                        forIllOperatingBnModel.setPripid(bizSerIllegalModel.getPripid());
                        forIllOperatingBnModel.setEntname(bizSerIllegalModel.getEntname());
                        forIllOperatingBnModel.setRegno(bizSerIllegalModel.getRegno());
                        forIllOperatingBnModel.setUniscid(bizSerIllegalModel.getUniscid());
                        forIllOperatingBnModel.setSerillrea(bizSerIllegalModel.getSerillrea());
                        forIllOperatingBnModel.setAbntime(LocalDateTime.now());
                        forIllOperatingBnModel.setAreaCode(decOrgCode);
                        forIllOperatingBnModel.setDecorg(bizSerIllegalModel.getDecorg());
                        forIllOperatingBnModel.setLostcreditexplain(bizSerIllegalModel.getLostcreditexplain());
                        forIllOperatingBnModel.setReconsiderationOrg(bizSerIllegalModel.getReconsiderationOrg());
                        forIllOperatingBnModel.setGovernmentOrg(bizSerIllegalModel.getGovernmentOrg());
                        forIllOperatingBnModel.setLitiOrg(bizSerIllegalModel.getLitiOrg());
                        forIllOperatingBnModel.setIntoSponsorIllegal(bizSerIllegalModel.getIntoSponsorIllegal());
                        forIllOperatingBnModel.setOperationStatus("0");
                        forIllOperatingBnModel.setLauptime(LocalDateTime.now());
                        forIllOperatingBnModel.setBatchAndCase(bizSerIllegalModel.getBatchAndCase());


                        bizSerIllegalModel.setApprovaldate(LocalDate.now()); //核准时间
                        bizSerIllegalModel.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
                        bizSerIllegalModel.setLauptime(LocalDateTime.now());
                        updateById(bizSerIllegalModel);

                        // 改变拟列入清单的状态值
                        TSForIllOperatingList tsForIllOperatingList = tsForIllOperatingListService.getById(bizSerIllegalModel.getSerialId());
                        tsForIllOperatingList.setOperationStatus("2");
                        tsForIllOperatingList.setLauptime(LocalDateTime.now());
                        tsForIllOperatingListService.updateById(tsForIllOperatingList);

                        //生成文书号
                        TSWrit tsWritModel = new TSWrit();
                        String tswritId = UUID.randomUUID().toString();
                        tsWritModel.setWritsid(tswritId);
                        tsWritModel.setAreaCode(bizSerIllegalModel.getDecorg());
                        String workNoType = WorkNoUtil.WORKNOTYPE_20;//拟列入严重违法失信名单 决定书文号
                        String writsno = workNoService.forIllOperatingBnNo(tsWritModel.getAreaCode());
                        tsWritModel.setBizseq(bizSerIllegalModel.getBizseq());
                        tsWritModel.setWritsno(writsno);
                        tsWritModel.setWritstype(workNoType);
                        tsWritModel.setPripid(bizSerIllegalModel.getPripid());
                        tsWritModel.setWritsname(WorkNoUtil.getWorkNoTypeName(workNoType));
                        tsWritModel.setContent(toIncludeDecText(bizSerIllegalModel));
                        tsWritModel.setCreatetime(LocalDateTime.now());
                        tsWritService.save(tsWritModel);
                        forIllOperatingBnModel.setIntowritid(tswritId);//严重违法表里保存列入文书id
                        tsForIllOperatingBnService.save(forIllOperatingBnModel);

                    } else {//严重违法列入
                        TSSerIllegalList tsSerIllegalListModel = new TSSerIllegalList();
                        tsSerIllegalListModel.setIllegallistid(bizSerIllegalModel.getIllegallistid());
                        tsSerIllegalListModel.setBizseq(bizSerIllegalModel.getBizseq());
                        if ("timeout".equals(type) && StringUtils.isNotBlank(bizSerIllegalModel.getAbnlistid())) {//异常名录期限届满列入
                            tsSerIllegalListModel.setAbnlistid(bizSerIllegalModel.getAbnlistid());

                            //异常名录中 标记为已列入严重违法失信
                            TSAbnList abnListModel = abnListService.getById(bizSerIllegalModel.getAbnlistid());
                            if (abnListModel != null && StringUtils.isNotBlank(abnListModel.getAbnlistid())) {
                                abnListModel.setRemexcpres("6"); // 列入经营异常名录届满3年仍未履行公示义务的，列入严重违法企业名单，自动移出
                                abnListModel.setRemSponsor(bizSerIllegalModel.getIntoSponsorIllegal()); // 列入严重违法失信的启动人就是移出经营异常名录的主办人
                                abnListModel.setRemdate(LocalDate.now());
                                abnListModel.setOperatestatus("4"); //标记严重违法失信
                                abnListService.updateById(abnListModel);
                            }
                        }
                        tsSerIllegalListModel.setPripid(bizSerIllegalModel.getPripid());
                        tsSerIllegalListModel.setEntname(bizSerIllegalModel.getEntname());
                        tsSerIllegalListModel.setRegno(bizSerIllegalModel.getRegno());
                        tsSerIllegalListModel.setUniscid(bizSerIllegalModel.getUniscid());
                        tsSerIllegalListModel.setSerillrea(bizSerIllegalModel.getSerillrea());
                        if (bizSerIllegalModel.getAbntime() != null) {
                            //判断经办人是否选择了列入日期,行政处罚有这个需求
                            tsSerIllegalListModel.setAbntime(bizSerIllegalModel.getAbntime());
                        } else {
                            tsSerIllegalListModel.setAbntime(LocalDate.now());
                            bizSerIllegalModel.setAbntime(LocalDate.now());
                        }
                        Gzaiccode gzaiccode = tUsersService.findOrganization(SSOUtil.getUser().getPrimaryKey());
                        tsSerIllegalListModel.setAreaCode(decOrgCode);
                        tsSerIllegalListModel.setDecorg(gzaiccode.getScountrycode());
                        tsSerIllegalListModel.setDecorgCn(gzaiccode.getSregorgname());// 列入决定机关中文
                        Map<String, TRBaseCode> serCodeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
                        TRBaseCode serillreaCode = serCodeMap.get(bizSerIllegalModel.getSerillrea());
                        if (serillreaCode != null) {
                            tsSerIllegalListModel.setLostcreditexplain(serillreaCode.getName());// 列入原因对应中文
                        }
//                        tsSerIllegalListModel.setLostcreditexplain(bizSerIllegalModel.getLostcreditexplain());
                        tsSerIllegalListModel.setReconsiderationOrg(bizSerIllegalModel.getReconsiderationOrg());
                        tsSerIllegalListModel.setGovernmentOrg(bizSerIllegalModel.getGovernmentOrg());
                        tsSerIllegalListModel.setLitiOrg(bizSerIllegalModel.getLitiOrg());
                        tsSerIllegalListModel.setIntoSponsorIllegal(bizSerIllegalModel.getIntoSponsorIllegal()); // 列入严重违法失信主办人
                        tsSerIllegalListModel.setIntoSponsorIllegalId(user.getPrimaryKey());
                        tsSerIllegalListModel.setBatchAndCase(bizSerIllegalModel.getBatchAndCase());
                        tsSerIllegalListModel.setOperationStatus("0");


                        bizSerIllegalModel.setApprovaldate(LocalDate.now()); //核准时间
                        bizSerIllegalModel.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
                        bizSerIllegalModel.setLauptime(LocalDateTime.now());
                        updateById(bizSerIllegalModel);

                        //生成文书号
                        TSWrit tsWritModel = new TSWrit();
                        String tswritId = UUID.randomUUID().toString();
                        tsWritModel.setWritsid(tswritId);
                        String workNoType = WorkNoUtil.WORKNOTYPE_21;//列入严重违法失信名单 决定书文号
                        if (!"1".equals(bizSerIllegalModel.getSourceType())) {
                            //行政处罚或法院的文书已经办人录入为准
                            tsWritModel.setWritsno(bizSerIllegalModel.getWritsno());
                        } else {
                            String writsno = workNoService.getOperatingWrirsno(workNoType, user.getRegionID());
                            tsWritModel.setWritsno(writsno);
                        }
                        String writsName = gzaiccode.getSregorgname() + WorkNoUtil.getWorkNoTypeName(workNoType);
                        tsWritModel.setContent(bizSerIllegalModel.getEntname() + "（统一社会信用代码/注册号："
                                + (bizSerIllegalModel.getUniscid() != null ? bizSerIllegalModel.getUniscid() : bizSerIllegalModel.getRegno())
                                + "）：" + bizSerIllegalModel.getLostcreditexplain());
                        tsWritModel.setWritsname(writsName);
                        tsWritModel.setBizseq(bizSerIllegalModel.getBizseq());
                        tsWritModel.setWritstype(workNoType);
                        tsWritModel.setPripid(bizSerIllegalModel.getPripid());
                        tsWritModel.setCreatetime(LocalDateTime.now());
                        tsWritModel.setLauptime(LocalDateTime.now());
                        tsWritService.save(tsWritModel);
                        tsSerIllegalListModel.setIntowritid(tswritId);//严重违法表里保存列入文书id
                        serIllegalListService.save(tsSerIllegalListModel);
                    }

                }
                if (FlowUtil.SERILLEGALWORKFLOW_OVERSERILLEGAL.equals(nextNodeID)) {

                    if (bizSerIllegalModel.getEndApply() != null && bizSerIllegalModel.getEndApply().equals("2")) { //不作列严操作
                        bizSerIllegalModel.setApprovaldate(LocalDate.now());//核准日期
                        bizSerIllegalModel.setStatus("5"); // 9 受理中、1 审批中、2 已通过、3 不通过、4 通过结束流程 5 直接否决结束流程
                        bizSerIllegalModel.setLauptime(LocalDateTime.now());
                        updateById(bizSerIllegalModel);
                    } else {
                        bizSerIllegalModel.setApprovaldate(LocalDate.now()); //核准时间
                        bizSerIllegalModel.setStatus("3"); // 9 受理中、1 审批中、2 已通过、3 不通过
                        bizSerIllegalModel.setLauptime(LocalDateTime.now());
                        updateById(bizSerIllegalModel);
                    }
                    // 改回录入状态
                    TSForIllOperatingList tsForIllOperatingList = tsForIllOperatingListService.getById(bizSerIllegalModel.getSerialId());
                    tsForIllOperatingList.setOperationStatus("0");
                    tsForIllOperatingListService.updateById(tsForIllOperatingList);
                }
            }
            taskListService.updateWorkFlow(user, opinionModel, taskListModel, nextNodeID, nextPerformerids, nextPerformerNames);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("异常名录期限届满列入严重违法失信名单审核出错");
        }
        return taskListModel;
    }

    @Override
    public List<TSBizSerIllegalReas> getSerillreas(String type) {
        if ("timeout".equals(type)) {
            return baseMapper.getSerillreasOne();//异常名录期限届满原因  列入及法律条款
        } else {
            return baseMapper.getSerillreasOthers();//其他原因 列入
        }
    }

    @Override
    public List<TSBizSerIllegalReas> findSerIllegalReas() {
        return baseMapper.findSerIllegalReas();
    }

    @Override
    public TSBizSerIllegalReas findSerIllegalReaByCode(String reaCode) {
        return baseMapper.findSerIllegalReaByCode(reaCode);
    }

    @Override
    public RestResult isLegalCorrect(String uscc, String name, String cerType, String certNo, String type) {
        Map<String, String> params = new LinkedHashMap<>();
        // 是否是统一码
        boolean isUscId = uscc.length() == 18 && (uscc.trim().startsWith("9"));
        params.put(isUscId ? "uniscid" : "regno", uscc);
        // 根据type来源指定查询接口 key= 1-严重违法修复 2-企业农专经营异常修复 3-个体异常消除修复;
        LambdaQueryWrapper<EBaseinfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(isUscId, EBaseinfo::getUniscid, uscc);
        lqw.eq(!isUscId, EBaseinfo::getRegno, uscc);
        lqw.eq(EBaseinfo::getRegstate, '1');//查询在营企业
        EBaseinfo eBaseinfo = eBaseinfoService.getOne(lqw);
        if (eBaseinfo == null) {
            // 是否为迁出
            LambdaQueryWrapper<EBaseinfo> lqw2 = Wrappers.lambdaQuery();
            lqw2.eq(isUscId, EBaseinfo::getUniscid, uscc);
            lqw2.eq(!isUscId, EBaseinfo::getRegno, uscc);
            lqw2.eq(EBaseinfo::getRegstate, '6');
            EBaseinfo checkInfo = eBaseinfoService.getOne(lqw2);
            if (checkInfo != null) {
                return RestResult.error(ResultCode.PARAM_IS_INVALID, "广州市该企业查无，如是已迁出企业，请联系列入机关咨询办理。");
            } else {
                return RestResult.error(ResultCode.PARAM_IS_INVALID, "查无该企业，请确认统一码是否正确！");
            }
        }
        // 因个转企调整，调用登记查询直接按企业类型进行判断 yuanjw  20250730
        String iType;
        if ("9910".equals(eBaseinfo.getEnttype()))
            iType = "individuality";
        else iType = "ent";
        // 挣扎判断一下是否真要都查接口
       /* if ("1".equals(type) && isUscId) {
            String uscIdSecPlace = uscc.substring(1, 2);
            iType = "2".equals(uscIdSecPlace) ? "individuality" : "ent";
        } else if ("2".equals(type)) {
            iType = "ent";
        } else if ("1".equals(type) || "3".equals(type)) {
            iType = "individuality";
        } else {
            log.error("找不到登陆类型！");
            return RestResult.error(ResultCode.PARAM_IS_INVALID,"身份验证失败！");
        }*/
        // 走本地验证，不走接口验证
        boolean localFlag = false;
        List<String> entTypes = new ArrayList<>(Arrays.asList("6400", "6410", "6420", "6430", "6490", "4530", "4531", "4532", "4533", "4540"));
        for (String entType : entTypes) {
            if (eBaseinfo.getEnttype() != null && eBaseinfo.getEnttype().equals(entType)) {
                localFlag = true;
                break;
            }
        }
        if (localFlag) {
            // 判断法人信息是否相等
            if (eBaseinfo.getLerep() != null && eBaseinfo.getLerep().trim().equals(name) && eBaseinfo.getCerno() != null && eBaseinfo.getCerno().trim().equals(certNo)) {
                Personnel personnel = new Personnel();
                personnel.setCerno(eBaseinfo.getCerno());
                personnel.setName(eBaseinfo.getLerep());
                personnel.setPripid(eBaseinfo.getPripid());
                personnel.setSex("");
                personnel.setTel(eBaseinfo.getTel());
                personnel.setHouseadd(eBaseinfo.getDom());
                return RestResult.ok(personnel);
            }
            log.error("身份认证：e_baseinfo表没有找到相关法人数据。{}", uscc);
            log.error("身份认证：法人名称({}),e_baseinfo中为：{};法人证件号({}),e_baseinfo中为：{}", name, eBaseinfo.getLerep(), certNo, eBaseinfo.getCerno());
            return RestResult.error(ResultCode.PARAM_IS_INVALID, "身份验证失败！");
        }

        ForestResponse<ChangRuanResult<List<Personnel>>> response = null;
        switch (iType) {
            case "ent":
                //企业
                response = soaServiceApi.queryPriPerson(params);
                break;
            case "individuality":
                //个体
                response = soaServiceApi.queryEpbOperator(params);
                break;
            default:
                log.error("iType值获取异常");
                return RestResult.error(ResultCode.PARAM_IS_INVALID, "身份验证失败！");
        }

        assert response != null;
        ChangRuanResult<List<Personnel>> result = response.getResult();

        List<Personnel> personnels = result.getData();

        Optional<Personnel> optional = "ent".equals(iType) ?
                personnels.stream().filter(item -> "1".equals(item.getLerepsign()) && eBaseinfo.getPripid().equals(item.getPripid())).findFirst()
                : personnels.stream().filter(item -> name.equals(item.getName().trim())).findFirst();
        if (optional.isPresent()) {
            Personnel personnel = optional.get();

            //判断法人名称是否相等
            if (personnel.getName().trim().equals(name) && personnel.getCerno().trim().equals(certNo)) {
                return RestResult.ok(personnel);
            } else {
                log.error("身份认证：法人名称({})不匹配,接口获取结果为：{}", name, personnel.getName());
                return RestResult.error(ResultCode.PARAM_IS_INVALID, "您填写的法定代表人/经营者身份证件号码与您办理登记时录入的身份证件号码不一致，请重新填写。如认证仍无法成功，建议到登记注册部门核对法人代表信息！");
            }
        }
        log.error("身份认证：主要人员信息没有找到相关法人数据。{}", uscc);
        return RestResult.error(ResultCode.PARAM_IS_INVALID, "身份验证失败！");
    }

    @Override
    public TSTaskList startIncludeIllegal(TSBizSerIllegal params) {
        AICUser user = SSOUtil.getUser();
        EBaseinfo eBaseinfo = eBaseinfoService.getById(params.getPripid());
        // 不再用gzaiccode表
//        Gzaiccode gzaiccode = tUsersService.findOrganization(user.getPrimaryKey());
        // 这里截取前六位到区级别
        String decOrgCode = aicorgService.getRegionCodeByUser(user);
        TSBizSerIllegal tsBizSerIllegal = new TSBizSerIllegal();
        String bizSeq = UUID.randomUUID().toString();
        tsBizSerIllegal.setBizseq(bizSeq);
        tsBizSerIllegal.setSourceType(params.getSourceType());
        tsBizSerIllegal.setPripid(eBaseinfo.getPripid());
        tsBizSerIllegal.setRegno(eBaseinfo.getRegno());
        tsBizSerIllegal.setUniscid(eBaseinfo.getUniscid());
        tsBizSerIllegal.setEntname(eBaseinfo.getEntname());
        tsBizSerIllegal.setDecorg(decOrgCode);
        tsBizSerIllegal.setBatchAndCase("1");
        //列入严重违法 经办保存
        tsBizSerIllegal.setIntoSponsorIllegal(user.getName()); // 流程启动人(主办人)
        tsBizSerIllegal.setStatus("9"); // 流程启动把状态设置为 "受理中"
        tsBizSerIllegal.setLauptime(LocalDateTime.now());

        //数据来源来自拟列入表
        if (StringUtils.isNotBlank(params.getIlloperatingid())) {
            TSForIllOperatingBn tsForIllOperatingBn = tsForIllOperatingBnService.getById(params.getIlloperatingid());
            tsForIllOperatingBn.setOperationStatus("4");//正在进行列入操作，防止重复办理
            tsForIllOperatingBn.setLauptime(LocalDateTime.now());
            tsForIllOperatingBnService.updateById(tsForIllOperatingBn);
            //为业务表设置经营异常名录ID
            tsBizSerIllegal.setAbnlistid(tsForIllOperatingBn.getAbnlistid());
            tsBizSerIllegal.setIlloperatingid(tsForIllOperatingBn.getIlloperatingid());
        }
        save(tsBizSerIllegal);

        //创建启动待办
        TSTaskList taskListModel = new TSTaskList();
        taskListModel.setBizseqid(bizSeq);
        taskListModel.setBustype(BaseDataConstant.SERILLEGAL_TYPE_ENTERSERILLEGAL);//列入严重违法失信
        taskListModel.setBusname(eBaseinfo.getEntname());
        taskListModel.setAreaCode(decOrgCode);
        String definedname = FlowUtil.SERIOUS_ILLEGAL_WORKFLOW;//严重违法失信名单流程模板
        //新待办
        HandleWorkFlowUtil.createTaskList(taskListModel, user);
        //开始工作流
        String tasklistid = taskListService.startWorkFlow(taskListModel, user, definedname);

        return taskListService.getById(tasklistid);
    }

    @Override
    public boolean nextProcessInclude(String currentLink, String nextNodeId, String nextHandleId, TSBizSerIllegal tsBizSerIllegal) {
        AICUser user = SSOUtil.getUser();
        switch (nextNodeId) {
            case FlowUtil.SERIOUS_ILLEGAL_ACCEPT://被退回到经办的
                //暂不用做什么操作
                break;
            case FlowUtil.SERIOUS_ILLEGAL_NULLIFY://办结作废（办结）
                nullifyInclude(tsBizSerIllegal);
                break;
            case FlowUtil.SERIOUS_ILLEGAL_REVIEW://审核
                reviewInclude(tsBizSerIllegal, nextNodeId);
                break;
            case FlowUtil.SERIOUS_ILLEGAL_EXAMINE://审批
                examineInclude(tsBizSerIllegal);
                break;
            case FlowUtil.SERIOUS_ILLEGAL_EXAMINE_SUCCESS://审批通过（办结）
                examineSuccessInclude(tsBizSerIllegal);
                break;
            case FlowUtil.SERIOUS_ILLEGAL_EXAMINE_FAIL://审批不通过（办结）
                examineFailInclude(tsBizSerIllegal);
                break;
            case FlowUtil.SERIOUS_ILLEGAL_BUREAU_EXAMINE_SUCCESS://行政处罚类型，区局审批通过还需要走市局的三级审批
                bureauExamineSuccessInclude(tsBizSerIllegal);
                break;
            case FlowUtil.SERIOUS_ILLEGAL_CITY_EXAMINE_SUCCESS://市局的审批通过待归档
                //先记录保存业务表
                reviewInclude(tsBizSerIllegal, nextNodeId);
                examineSuccessInclude(tsBizSerIllegal);
                break;
            case FlowUtil.SERIOUS_ILLEGAL_ENDARCHIVES://经办人归档
                //暂不用处理，只驱动流程结束
                break;
            default:
                throw new BusinessException(ResultCode.BUSINESS_LOGIC_ERROR, "下一个流程节点" + nextNodeId + "无效");
        }

        TSTaskList tsTaskList = taskListService.selectTaskListByBizseqid(tsBizSerIllegal.getBizseq()).get(0);
        //为意见表设置
        TSOpinion opinionModel = new TSOpinion();
        String currentLinkNum = FlowUtil.getChangeLink(currentLink);
        if (StringUtils.isBlank(currentLinkNum)) {
            throw new BusinessException(ResultCode.BUSINESS_LOGIC_ERROR, "当前流程节点" + nextNodeId + "无效");
        }
        opinionModel.setOpiniontype(currentLinkNum);
        opinionModel.setOpinioncontent(tsBizSerIllegal.getOpinion());
        TUsers tUsers = new TUsers();
        if (StringUtils.isNotBlank(nextHandleId)) {
            tUsers = tUsersService.selectTusersById(nextHandleId);
        }
        // 区局发起的行政处罚列严，到了市局审批流程时，有审核权限的都能看到待办（经办->审核）（审批->审核）
        String[] ids = {nextHandleId};
        String[] names = {tUsers.getRealname()};
        if ("001".equals(user.getOrgID())) {
            if ("2".equals(tsBizSerIllegal.getSourceType()) && FlowUtil.SERIOUS_ILLEGAL_REVIEW.equals(nextNodeId)) {
                // 市局的行政处罚列严-有审核权限都能看到待办
                List<AICUser> userList = tUsersService.findUserByPermissionAndOrgIds("illegalInclusionReview", user.getOrgID(), false, user);
                if (CollectionUtils.isEmpty(userList)) throw new BusinessException("找不到审核人，提交失败");
                String[] idArray = new String[userList.size()];
                String[] nameArray = new String[userList.size()];
                for (int i = 0; i < userList.size(); i++) {
                    idArray[i] = userList.get(i).getPrimaryKey();
                    nameArray[i] = userList.get(i).getName();
                }
                ids = idArray;
                names = nameArray;
            }
            // 市局的行政处罚列严 审核人操作时，由于到审核节点时是发给组的待办，状态改为了待签收 先签收待办
            if (FlowUtil.SERIOUS_ILLEGAL_REVIEW.equals(currentLink)) {
                workFlowService.claimGroup(tsTaskList.getWorkflowid(), user.getPrimaryKey());
            }
        }
        //流转
        taskListService.updateWorkFlow(user, opinionModel, tsTaskList, nextNodeId, ids, names);
        return true;
    }


    @Override
    public void examineSuccessInclude(TSBizSerIllegal tsBizSerIllegal) {
        //需要生成文书数据、更新业务表数据、插入正式表数据
        AICUser user = SSOUtil.getUser();
        TSBizSerIllegal dbTSBizSerIllegal = getById(tsBizSerIllegal.getIllegallistid());
        //机关以经办人为准
        // 不再用gzaiccode表
//        Gzaiccode gzaiccode = iGzaiccodeService.getOne(Wrappers.lambdaQuery(Gzaiccode.class).eq(Gzaiccode::getScountrycode, dbTSBizSerIllegal.getDecorg()));
        OrgUnits orgUnits = aicorgService.queryByOrgNumber(dbTSBizSerIllegal.getDecorg());
        //1.生成列入正式表数据
        TSSerIllegalList tsSerIllegalList = new TSSerIllegalList();
        tsSerIllegalList.setIllegallistid(dbTSBizSerIllegal.getIllegallistid());
        tsSerIllegalList.setBizseq(dbTSBizSerIllegal.getBizseq());
        tsSerIllegalList.setAbnlistid(dbTSBizSerIllegal.getAbnlistid());
        tsSerIllegalList.setPripid(dbTSBizSerIllegal.getPripid());
        tsSerIllegalList.setEntname(dbTSBizSerIllegal.getEntname());
        tsSerIllegalList.setRegno(dbTSBizSerIllegal.getRegno());
        tsSerIllegalList.setUniscid(dbTSBizSerIllegal.getUniscid());
        tsSerIllegalList.setSerillrea(dbTSBizSerIllegal.getSerillrea());
        tsSerIllegalList.setReconsiderationOrg(dbTSBizSerIllegal.getReconsiderationOrg());
        tsSerIllegalList.setGovernmentOrg(dbTSBizSerIllegal.getGovernmentOrg());
        tsSerIllegalList.setLitiOrg(dbTSBizSerIllegal.getLitiOrg());
        tsSerIllegalList.setIntoSponsorIllegal(dbTSBizSerIllegal.getIntoSponsorIllegal()); // 列入严重违法失信主办人
        tsSerIllegalList.setIntoSponsorIllegalId(user.getPrimaryKey());
        tsSerIllegalList.setBatchAndCase(dbTSBizSerIllegal.getBatchAndCase());
        tsSerIllegalList.setOperationStatus("0");
        String areaCode = tsBizSerIllegal.getDecorg();
        tsSerIllegalList.setAreaCode(StringUtils.isEmpty(areaCode)?"150000":areaCode.substring(0,6));
        tsSerIllegalList.setIsshow("1");
        tsSerIllegalList.setDecorg(orgUnits.getOrgNumber());
        tsSerIllegalList.setDecorgCn(orgUnits.getOrgUnitName());// 列入决定机关中文
        tsSerIllegalList.setLauptime(LocalDateTime.now());

        tsSerIllegalList.setIshea(dbTSBizSerIllegal.getIshea());
        tsSerIllegalList.setHeaop(dbTSBizSerIllegal.getHeaop());
        tsSerIllegalList.setIsrev("0");
        tsSerIllegalList.setJuddocno(dbTSBizSerIllegal.getJuddocno());
        tsSerIllegalList.setJuddoctitle(dbTSBizSerIllegal.getJuddoctitle());

        if (dbTSBizSerIllegal.getAbntime() != null) {
            //判断是否选择线下纸质的录入,行政处罚有这个需求
            tsSerIllegalList.setAbntime(dbTSBizSerIllegal.getAbntime());
        } else {
            tsSerIllegalList.setAbntime(LocalDate.now());
            dbTSBizSerIllegal.setAbntime(LocalDate.now());
        }

        // 列入原因对应中文
        Map<String, TRBaseCode> serCodeMap = baseCodeService.getBaseCodeMapFormCache("CD73");
        TRBaseCode serillreaCode = serCodeMap.get(dbTSBizSerIllegal.getSerillrea());
        if (serillreaCode != null) {
            tsSerIllegalList.setLostcreditexplain(serillreaCode.getName());
        }

        //2.更新业务表数据
        dbTSBizSerIllegal.setApprovaldate(LocalDate.now()); //核准时间
        dbTSBizSerIllegal.setStatus("2"); // 9 受理中、1 审批中、2 已通过、3 不通过
        dbTSBizSerIllegal.setLauptime(LocalDateTime.now());
        updateById(dbTSBizSerIllegal);

        //3.判断是否经营异常名录的线索列入，是的话则把该线索自动移出
        if (StringUtils.isNotBlank(dbTSBizSerIllegal.getAbnlistid())) {
            //异常名录中 标记为已列入严重违法失信
            TSAbnList abnListModel = abnListService.getById(dbTSBizSerIllegal.getAbnlistid());
            if (abnListModel != null) {
                abnListModel.setRemexcpres("6"); // 列入经营异常名录届满3年仍未履行公示义务的，列入严重违法企业名单，自动移出
                abnListModel.setRemSponsor(dbTSBizSerIllegal.getIntoSponsorIllegal()); // 列入严重违法失信的启动人就是移出经营异常名录的主办人
                abnListModel.setRemdate(LocalDate.now());
                abnListModel.setOperatestatus("4"); //标记严重违法失信
                abnListModel.setRemDecorg(orgUnits.getOrgNumber()); //移出机关
                abnListModel.setReDecorg(orgUnits.getOrgUnitName()); //移出机关中文
                abnListModel.setLauptime(LocalDateTime.now());
                abnListService.updateById(abnListModel);
            }
        }
        //4.生成文书号
        TSWrit tsWritModel = new TSWrit();
        String tswritId = UUID.randomUUID().toString();
        tsWritModel.setWritsid(tswritId);
        String workNoType = WorkNoUtil.WORKNOTYPE_21;//列入严重违法失信名单 决定书文号
        if (dbTSBizSerIllegal.getDecorg().equals("440101") && !"1".equals(dbTSBizSerIllegal.getSourceType())) {
            //市局的直接办理的业务，行政处罚或法院的文书已经办人录入为准
            tsWritModel.setWritsno(dbTSBizSerIllegal.getWritsno());
        } else {
            String writsno = workNoService.generateSeriousIncludeDocNo(dbTSBizSerIllegal.getDecorg());
            tsWritModel.setWritsno(writsno);
        }
        String writsName = orgUnits.getOrgUnitName() + WorkNoUtil.getWorkNoTypeName(workNoType);
        tsWritModel.setContent(dbTSBizSerIllegal.getEntname() +
                "（统一社会信用代码/注册号："
                + (dbTSBizSerIllegal.getUniscid() != null ? dbTSBizSerIllegal.getUniscid() : dbTSBizSerIllegal.getRegno()) + "）："
                + dbTSBizSerIllegal.getLostcreditexplain()
                + includeDocumentLastText(tsSerIllegalList));

        tsWritModel.setWritsname(writsName);
        tsWritModel.setBizseq(dbTSBizSerIllegal.getBizseq());
        tsWritModel.setWritstype(workNoType);
        tsWritModel.setPripid(dbTSBizSerIllegal.getPripid());
        tsWritModel.setCreatetime(LocalDateTime.now());
        tsWritModel.setLauptime(LocalDateTime.now());
        tsWritModel.setAreaCode(orgUnits.getOrgNumber());
        tsWritService.save(tsWritModel);
        tsSerIllegalList.setIntowritid(tswritId);//严重违法表里保存列入文书id
        //保存正式表
        serIllegalListService.save(tsSerIllegalList);

        //获取法人手机号码
//        List<Map<String,String>> epriPersonList = eBaseinfoService.queryEpriPersonList(dbTSBizSerIllegal.getPripid());
//        if (epriPersonList.size() > 0) {
//            Map<String,String> epriPerson = epriPersonList.get(0);
//            if ( !"".equals(epriPerson.get("phone")) && epriPerson.get("phone") != null ) {
//                String phone = epriPerson.get("phone");
//                Set<String> set = new HashSet<>();
//                set.add(phone);
//                Calendar calendar = Calendar.getInstance();
//                int year = calendar.get(Calendar.YEAR);
//                int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，所以加1
//                int day = calendar.get(Calendar.DAY_OF_MONTH);
//                String text = "【信用监管系统】 您的企业：" + dbTSBizSerIllegal.getEntname() + "于" + year + "年" + month + "月" + day + "日被列入严重违法，如有异议请联系当地市场监督管理局询问。" ;
//                try {
//                    AbnSerSmsLog abnSerSmsLog = new AbnSerSmsLog();
//                    abnSerSmsLog.setAbnSerSmsid(UUID.randomUUID().toString());
//                    abnSerSmsLog.setAbnserid(dbTSBizSerIllegal.getIllegallistid());
//                    abnSerSmsLog.setUsername(user.getPrimaryKey());
//                    abnSerSmsLog.setBizseq(dbTSBizSerIllegal.getBizseq());
//                    abnSerSmsLog.setContent(text);
//                    abnSerSmsLog.setPhones(phone);
//                    abnSerSmsLogService.save(abnSerSmsLog);
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//        }
    }

    @Override
    public void examineFailInclude(TSBizSerIllegal tsBizSerIllegal) {
        TSBizSerIllegal dbTSBizSerIllegal = getById(tsBizSerIllegal.getIllegallistid());
        //结束业务表的状态
        dbTSBizSerIllegal.setStatus("3");
        updateById(dbTSBizSerIllegal);
        //恢复列入线索状态
        if (StringUtils.isNotBlank(tsBizSerIllegal.getIlloperatingid())) {
            TSForIllOperatingBn tSForIllOperatingBn = new TSForIllOperatingBn();
            tSForIllOperatingBn.setIlloperatingid(tsBizSerIllegal.getIlloperatingid());
            tSForIllOperatingBn.setOperationStatus("0");
            tSForIllOperatingBn.setLauptime(LocalDateTime.now());
            tsForIllOperatingBnService.updateById(tSForIllOperatingBn);
        }
    }

    @Override
    public void examineInclude(TSBizSerIllegal tsBizSerIllegal) {
        updateById(tsBizSerIllegal);
    }

    @Override
    public void reviewInclude(TSBizSerIllegal tsBizSerIllegal, String node) {

        // 前往审核
        if (FlowUtil.SERIOUS_ILLEGAL_REVIEW.equals(node)) {
            // 有可能是系统发起的待办
            TSBizSerIllegal tsBizSerIllegalModel = getById(tsBizSerIllegal.getIllegallistid());
            if (StringUtils.isBlank(tsBizSerIllegalModel.getIntoSponsorIllegal())) {

                TSTaskList tsTaskList = taskListService.getOne(new LambdaQueryWrapper<TSTaskList>().eq(TSTaskList::getBizseqid, tsBizSerIllegal.getBizseq()));
                // 避免重复在经办页面点击办理
                TSTwfProcessNode tsTwfProcessNode = tsTwfProcessNodeService.queryByPROCESSID(tsTaskList.getWorkflowid());
                if (!FlowUtil.SERIOUS_ILLEGAL_ACCEPT.equals(tsTwfProcessNode.getCurrentnode())) {
                    throw new RuntimeException("该业务已经被受理");
                }

                AICUser user = SSOUtil.getUser();
                TSForIllOperatingBn tsForIllOperatingBn = tsForIllOperatingBnService.getOne(
                        new LambdaQueryWrapper<TSForIllOperatingBn>().eq(TSForIllOperatingBn::getIlloperatingid, tsBizSerIllegalModel.getIlloperatingid()));
                tsForIllOperatingBn.setOperationStatus("4");//正在进行列入操作，防止重复办理
                tsForIllOperatingBnService.updateById(tsForIllOperatingBn);
                // 签收
                workFlowService.claimGroup(tsTaskList.getWorkflowid(), user.getPrimaryKey());
                tsBizSerIllegal.setIntoSponsorIllegal(user.getName());
            }
        }
        updateById(tsBizSerIllegal);
    }

    @Override
    public void nullifyInclude(TSBizSerIllegal tsBizSerIllegal) {
        //结束业务表的状态
        tsBizSerIllegal.setStatus("5");
        updateById(tsBizSerIllegal);
        //恢复列入线索状态
        TSBizSerIllegal dbTSBizSerIllegal = getById(tsBizSerIllegal.getIllegallistid());
        if (StringUtils.isNotBlank(dbTSBizSerIllegal.getIlloperatingid())) {
            TSForIllOperatingBn tSForIllOperatingBn = new TSForIllOperatingBn();
            tSForIllOperatingBn.setIlloperatingid(dbTSBizSerIllegal.getIlloperatingid());
            tSForIllOperatingBn.setOperationStatus("0");
            tSForIllOperatingBn.setLauptime(LocalDateTime.now());
            tsForIllOperatingBnService.updateById(tSForIllOperatingBn);
        }
    }

    @Override
    public void bureauExamineSuccessInclude(TSBizSerIllegal tsBizSerIllegal) {
        updateById(tsBizSerIllegal);
    }

    @Override
    public RestResult<?> querySerllegaHistoryInfo(String sapprovecode) {
        Map<String, Object> resultMap = new HashMap<>();
        TSBizSerIllegal tsBizSerIllegal = baseMapper.queryByTBYZWFAPPROVE(sapprovecode);
        // 区分批量
        if (tsBizSerIllegal == null) {
            tsBizSerIllegal = baseMapper.queryByTBYZWFBATCHAPPROVE(sapprovecode);
            resultMap.put("isBatch", true);
            resultMap.put("eBaseinfo", null);
        } else {
            EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>()
                    .eq(EBaseinfo::getUniscid, tsBizSerIllegal.getUniscid())
                    .eq(EBaseinfo::getRegno, tsBizSerIllegal.getRegno()));
            eBaseinfo = supplementinfo(eBaseinfo);
            resultMap.put("eBaseinfo", eBaseinfo);
            resultMap.put("isBatch", false);
        }
        resultMap.put("tsBizSerIllegal", tsBizSerIllegal);
        List<TSOpinion> tsOpinions = tsOpinionMapper.queryOldSerillegaOpninion(sapprovecode);
        resultMap.put("tsOpinions", tsOpinions);
        List<TSAttachment> tsAttachments = tsAttachmentMapper.queryFileByHistory(sapprovecode);
        resultMap.put("tsAttachments", tsAttachments);
        return RestResult.ok(resultMap);
    }

    @Override
    public RestResult<?> querySerllegaHistoryEnt(PageRequestDto pageRequestDto) {
        Map<String, Object> paramMap = pageRequestDto.getCustomParamMap();
        String SAPPROVECODE = paramMap.get("bizseq").toString();
        IPage<EBaseinfo> page = baseMapper.queryEntByTBYZWFBATCHLIST(new Page<>(pageRequestDto.getCurPage(),
                pageRequestDto.getPageSize()), SAPPROVECODE);
        // 封装企业基本信息
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(res -> {
                res = supplementinfo(res);
            });
        }
        return RestResult.ok(page);
    }

    /**
     * 拟列严重文书内容生成
     *
     * @param bizSerIllegal 列严业务信息
     * @return 生成的文书内容
     */
    private String toIncludeDecText(TSBizSerIllegal bizSerIllegal) {
        if (bizSerIllegal == null) throw new BusinessException("业务逻辑错误");
        String abnlistid = bizSerIllegal.getAbnlistid();
        if (StringUtils.isEmpty(abnlistid)) throw new BusinessException("找不到列异信息");
        TSAbnList abnList = abnListService.getById(abnlistid);
        if (abnList == null) throw new BusinessException("找不到列异信息");
        String abnDate = DateUtils.localDateFormat(abnList.getAbntime(), "yyyy年MM月dd日");
        LocalDate endDate = abnList.getAbntime().plusYears(3);
        String abnRea = abnList.getSpereasons();
        String entName = bizSerIllegal.getEntname();
        String uscc = StringUtils.isEmpty(bizSerIllegal.getUniscid()) ? bizSerIllegal.getUniscid() : bizSerIllegal.getRegno();
        String text = entName + "（统一社会信用代码/注册号：" + uscc + "）:\n经查，你企业于" + abnDate + "因" + abnRea
//        String text =  "经查，你企业于"+ abnDate+ "因"+ abnRea
                + "被列入经营异常名录，将于" + endDate +
                "届满3年。依据《严重违法失信企业名单管理暂行办法》第八条第一款规定，请在届满日前履行相关义务，" +
                "并向工商局部门申请移除经营异常名录。逾期未履行相关义务的，将依据《企业信息公示暂行条例》第十七条第二款" +
                "第（一）项的规定，将你企业列入严重违法失信企业名单，并通过国家企业信用信息公示系统及广州市红盾信息网向社会公示。";
        return text;
    }

    /**
     * 列入决定文书最后内容
     *
     * @return
     */
    private String includeDocumentLastText(TSSerIllegalList tsSerIllegalList) {
        LocalDate term = tsSerIllegalList.getAbntime().plusYears(3);
        LambdaQueryWrapper<Gzaiccode> lqw = Wrappers.lambdaQuery();
        //查地市的
        lqw.eq(Gzaiccode::getScountrycode, tsSerIllegalList.getDecorg().substring(0, 4) + "00");
        Gzaiccode gzaiccode = iGzaiccodeService.getOne(lqw);
        String government = gzaiccode.getScountryextcode() + "人民政府";
        String court = gzaiccode.getScountryextcode() + "人民法院";
        String text = "，现决定将你（单位）列入严重违法失信名单，通过国家企业信用信息公示系统向社会公示，并实施相应管理措施。列入期限自即日起至"
                + term.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")) +
                "。期满一年后，你（单位）可依据《市场监督管理严重违法失信名单管理办法》第十六条、第十七条规定向我局申请提前移出严重违法失信名单，停止公示相关信息并解除相应管理措施。" +
                "\n你（单位）如不服本决定，可以自收到本决定书之日起六十日内向" + government +
                "申请行政复议；也可以在六个月内向" + court + "提起行政诉讼。";
        return text;
    }

    private EBaseinfo supplementinfo(EBaseinfo eBaseinfo) {
        if (eBaseinfo != null) {
            // 经营状态
            Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
            TRBaseCode code = codeMap.get(eBaseinfo.getRegstate());
            if (code != null) {
                eBaseinfo.setRegstateCn(code.getName());
            }
            // 登记机关
            if (eBaseinfo.getRegorg() != null) {
                String regorgName = baseCodeService.getRegorgName(eBaseinfo.getRegorg());
                if (regorgName != null) {
                    eBaseinfo.setRegorgCn(regorgName);
                }
            }
            //商事主体类型
            TREntPriseType trEntPriseType = entPriseTypeService.getEntPriseTypeFromCache(eBaseinfo.getEnttype());
            if (trEntPriseType != null) {
                eBaseinfo.setEnttypeCn(trEntPriseType.getDisplayvalue());
            }
            // 监管机关
            if (eBaseinfo.getRegulatory() != null) {
                String regulatoryName = baseCodeService.getRegorgName(eBaseinfo.getRegulatory());
                if (regulatoryName != null) {
                    eBaseinfo.setRegulatoryName(regulatoryName);
                }
            }
            if (eBaseinfo.getSuporg() != null) {
                String suporgName = baseCodeService.getSuporg(eBaseinfo.getSuporg());
                if (suporgName != null) {
                    eBaseinfo.setSuporgCn(suporgName);
                }
            }
        }
        return eBaseinfo;
    }
}
