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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
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.*;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.EBaseinfoExcel;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.FcnStr;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.ContactVo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.QzzxEntDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.RegulatoryVO;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.XyxfCqDto;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.EBaseinfoMapper;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.GzaiccodeMapper;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.RegulatoryMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.*;
import com.chinaweal.aiccs.aiccs.claim.entity.SolrExGongan128Xdzkdy;
import com.chinaweal.aiccs.aiccs.claim.mapper.ExGongan128XdzkdyfwMapper;
import com.chinaweal.aiccs.aiccs.claim.service.impl.SolrExGongan128XdzkdyServiceImpl;
import com.chinaweal.aiccs.aiccs.dict.entity.CascadeTreeNode;
import com.chinaweal.aiccs.aiccs.entbase.service.TREntPriseTypeService;
import com.chinaweal.aiccs.aiccs.market.entity.AreaSlice;
import com.chinaweal.aiccs.aiccs.market.service.AreaSliceService;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegal;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalDiss;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSBizSerIllegalRem;
import com.chinaweal.aiccs.aiccs.seriousillegal.entity.TSSerIllegalList;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalDissService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalRemService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSBizSerIllegalService;
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.common.constant.Constant;
import com.chinaweal.aiccs.common.constant.IndustryConstant;
import com.chinaweal.aiccs.common.enums.EntStatusEnum;
import com.chinaweal.aiccs.common.util.DateUtils;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.crgs.entity.EPriPersonCrgs;
import com.chinaweal.aiccs.crgs.entity.E_CONTACTCrgs;
import com.chinaweal.aiccs.crgs.moveinDetails.entity.EAlterRecoder;
import com.chinaweal.aiccs.crgs.service.EContactCrgsService;
import com.chinaweal.aiccs.crgs.service.EPriPersonCrgsService;
import com.chinaweal.aiccs.org.entity.OrgAreas;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.OrgAreasService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.solr.entity.EBaseInfoSolrBean;
import com.chinaweal.solr.template.SolrSearchTemplate;
import com.chinaweal.youfool.framework.springboot.base.query.BaseQuery;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Lee
 * @since 2021-03-15
 */
@Service
@Slf4j
public class EBaseinfoServiceImpl extends BaseServiceImpl<EBaseinfoMapper, EBaseinfo> implements EBaseinfoService {

    @Autowired
    private TSSerIllegalListService serIllegalListService;
    @Autowired
    private TSBizSerIllegalDissService bizSerIllegalDissService;
    @Autowired
    private TSBizSerIllegalRemService bizSerIllegalRemService;
    @Autowired
    private TSBizSerIllegalService bizSerIllegalService;
    @Autowired
    private TSAbnListService abnListService;
    @Autowired
    private TSBizSpeListService bizSpeListService;
    @Autowired
    private TSBizDissentService bizDissentService;
    @Autowired
    private TSBizRemListService bizRemListService;

    @Resource
    private RegulatoryMapper regulatoryMapper;
    @Resource
    private TRBaseCodeService baseCodeService;

    @Autowired
    private SolrSearchTemplate solrSearchTemplate;
    @Resource
    private TREntPriseTypeService entPriseTypeService;

    @Resource
    private GzaiccodeMapper iGzaiccodeMapper;

    @Resource
    private OrgUM orgUM;
    @Autowired
    private TrentassetsService trentassetsService;
    @Autowired
    private AreaSliceService areaSliceService;
    @Autowired
    private EPriPersonService ePriPersonService;
    @Autowired
    private EContactService eContactService;
    @Autowired
    private ContactLogService contactLogService;
    @Autowired
    private EPriPersonCrgsService ePriPersonCrgsService;
    @Autowired
    private EContactCrgsService eContactCrgsService;
    @Autowired
    private ExGongan128XdzkdyfwMapper xdzkdyfwMapper;
    @Autowired
    private OrgAreasService orgAreasService;
    @Autowired
    private SolrExGongan128XdzkdyServiceImpl solrExGongan128XdzkdyService;
    @Autowired
    private AicorgService aicorgService;
    @Resource
    private IXrSuperviseDeptLogService iXrSuperviseDeptLogService;

    @Override
    public String getLevelFromCrgs(String pripid) {
        return baseMapper.getLevelFromCrgs(pripid);
    }

    @Override
    public EBaseinfo getEBaseInfoStatus(EBaseinfo eBaseinfo) {
        /*
         * 1、如果是主体是企业，检查列入严重违法失信企业名录状态
         *  1.1、检查名录表，根据移出时间初步判断状态
         *  1.2、如果移出时间为空，则判断是否存在异议或移出审批中状态
         *  1.3、如果存在移出时间，则判断是否有正在列入的记录
         * 2、如果存在严重违法失信企业名录状态则返回状态，不判断异常名录
         * 3、检查列入异常名录状态
         *  3.1、检查名录表，根据移出时间初步判断状态
         *  3.2、如果移出时间为空，则判断是否存在异议或移出审批中状态
         *  3.3、如果存在移出时间，则判断是否有正在列入的记录
         * 4、返回最终状态
         */
        EntStatusEnum status = EntStatusEnum.NORMAL;
        String pripid = eBaseinfo.getPripid();
        // 判断主体是否为企业
        if (StringUtils.notIn(eBaseinfo.getEnttype(), Constant.NOT_COMPANY_TYPE)) {
            TSSerIllegalList illegal = serIllegalListService.getFirstIllegalListRecord(new LambdaQueryWrapper<TSSerIllegalList>().eq(TSSerIllegalList::getPripid, pripid).orderByDesc(TSSerIllegalList::getAbntime));
            if (illegal != null) {
                // 移出日期为空，则已列入但未移出，此时需检查异议业务表和移出业务表，判断是否审批中
                if (illegal.getRemdate() == null) {
                    status = EntStatusEnum.ILLEGAL_LIST;
                    // 检查异议业务表，判断是否异议审批中
                    int dissent = bizSerIllegalDissService.count(new LambdaQueryWrapper<TSBizSerIllegalDiss>().eq(TSBizSerIllegalDiss::getPriPID, pripid).isNull(TSBizSerIllegalDiss::getApprovalDate));
                    if (dissent > 0) {
                        status = EntStatusEnum.ILLEGAL_DISSENT;
                    } else {
                        // 检查移出业务表，判断是否移出中
                        int rem = bizSerIllegalRemService.count(new LambdaQueryWrapper<TSBizSerIllegalRem>()
                                .eq(TSBizSerIllegalRem::getPriPID, pripid)
                                .notIn(TSBizSerIllegalRem::getStatus, "2", "3"));// 不在已通过和不通过状态的记录
                        if (rem > 0) {
                            status = EntStatusEnum.ILLEGAL_REM_EXAMINE;
                        }
                    }
                }
            }

            // 如果不存在审核已列入，移出，异议等记录，则判断是否有列入中的业务记录
            if (status.equals(EntStatusEnum.NORMAL)) {
                int examine = bizSerIllegalService.count(new LambdaQueryWrapper<TSBizSerIllegal>()
                        .eq(TSBizSerIllegal::getPripid, pripid)
                        .notIn(TSBizSerIllegal::getStatus, "2", "3"));
                if (examine > 0) {
                    status = EntStatusEnum.ILLEGAL_LIST_EXAMINE;
                }
            }

            // 如果主体不处于正常状态，则返回结果
            if (!status.equals(EntStatusEnum.NORMAL)) {
                eBaseinfo.setEntStatus(status.getCode());
                eBaseinfo.setEntStatusStr(status.getName());
                return eBaseinfo;
            }
        }

        // 判断异常名录
        TSAbnList abnList = abnListService.getFirstAbnormalList(new LambdaQueryWrapper<TSAbnList>().eq(TSAbnList::getPripid, pripid).orderByDesc(TSAbnList::getAbntime));
        if (abnList != null) {
            switch (abnList.getOperatestatus()) {
                //异常状态（0移出1列入2撤销3修改4标记严重失信）
                // 0，2，4均可视为已经不在异常名录
                case "1":
                    status = EntStatusEnum.ABNORMAL_LIST;
                    break;
                case "3": // 修改（可能为异议中或移出中），此时检查异议业务表和移出业务表
                    status = EntStatusEnum.ABNORMAL_LIST;
                    int dissent = bizDissentService.count(new LambdaQueryWrapper<TSBizDissent>().eq(TSBizDissent::getPripid, pripid).isNull(TSBizDissent::getApprovaldate));
                    if (dissent > 0) {
                        status = EntStatusEnum.ABNORMAL_DISSENT;
                    } else {
                        int rem = bizRemListService.count(new LambdaQueryWrapper<TSBizRemList>()
                                .eq(TSBizRemList::getPripid, pripid)
                                .notIn(TSBizRemList::getStatus, "2", "3"));
                        if (rem > 0) {
                            status = EntStatusEnum.ABNORMAL_REM_EXAMINE;
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        // 如果不存在审核已列入，移出，异议等记录，则判断是否有列入中的业务记录
        if (status.equals(EntStatusEnum.NORMAL)) {
            int examine = bizSpeListService.count(new LambdaQueryWrapper<TSBizSpeList>()
                    .eq(TSBizSpeList::getPripid, pripid)
                    .notIn(TSBizSpeList::getStatus, "2", "3", "4"));
            if (examine > 0) {
                status = EntStatusEnum.ABNORMAL_LIST;
            }
        }

        // 设置状态信息
        eBaseinfo.setEntStatus(status.getCode());
        eBaseinfo.setEntStatusStr(status.getName());

        return eBaseinfo;
    }

    @Override
    public IPage<ComplexEntInfoDto> getComplexEntInfoPage(IPage<ComplexEntInfoDto> page, Map<String, Object> params) {
        return baseMapper.selectComplexEntInfoPage(page, params);
    }

    @Override
    public IPage<ToIncludeAbnDto> toIncludeAbnListPage(IPage<ToIncludeAbnDto> page, Map<String, Object> customParamMap) {
        return baseMapper.selectToIncludeAbnPage(page, customParamMap);
    }

    @Override
    public Page comprehensiveQuery(IPage page, Map<String, Object> customParamMap) {
        Object searchDate = customParamMap.get("establishDate");
        if (searchDate instanceof List) {
            List<String> list = (List<String>) searchDate;
            customParamMap.put("eststartDate", list.get(0));
            customParamMap.put("estendDate", list.get(1));
        }
        Object apprDate = customParamMap.get("apprDate");
        if (apprDate instanceof List) {
            List<String> list = (List<String>) apprDate;
            customParamMap.put("apprDatestart", list.get(0));
            customParamMap.put("apprDateend", list.get(1));
        }
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                customParamMap.put("uniscid", searchUscc);
            } else {
                customParamMap.put("regno", searchUscc);
            }
        }
        //mysql数据库不再使用
//        IPage<EBaseinfo> rs = baseMapper.comprehensiveQuery(page, customParamMap);

        //查solr
        SimpleQuery query = new SimpleQuery("*:*");
        query.setDefaultOperator(Query.Operator.AND);
        // 社会信用代码查询 - 改为精确匹配确保一致性
        if (StringUtils.isNotBlank(searchUscc)) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.UNISCID).is(searchUscc)
                    .or(Criteria.where(EBaseInfoSolrBean.REG_NO).is(searchUscc))));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("noClaim")))) {
            if ("0".equals(customParamMap.get("noClaim"))) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.SUPORG).isNull()));
            } else if ("1".equals(customParamMap.get("noClaim"))) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.SUPORG).isNotNull()));
            }

        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("entName")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_NAME).is(customParamMap.get("entName").toString())));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("name")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.LE_REP).is(customParamMap.get("name").toString())));
        }
        //片区查询属地监管机关
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regulatory")))) {
            List<String> regulatory = (List<String>) customParamMap.get("regulatory");
            if (regulatory.size() > 0) {
                String suporg = regulatory.get(regulatory.size() - 1);
                List<String> idsByParentId = areaSliceService.getIdsByParentId(suporg);     //获取所有子片区id
                idsByParentId.add(suporg);      //加上父id
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.SAREACODE_TEMP).in(idsByParentId)));
            }
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regorg")))) {
            List<String> regorg = (List<String>) customParamMap.get("regorg");
            if (regorg.size() > 0) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REG_ORG).startsWith(regorg.get(regorg.size() - 1))));
            }
        }
        String addressSearchType = StringUtils.tranObject(customParamMap.get("addressSearchType"));
        if (StringUtils.isNotBlank(addressSearchType) && "eq".equals(addressSearchType)) {
            if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("dom")))) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.DOM).is(customParamMap.get("dom").toString())));
            }
        } else {
            if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("dom")))) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.DOM).contains(customParamMap.get("dom").toString())));
            }
        }
        // 多个登记机关
        if (CollectionUtils.isNotEmpty((List<String>) customParamMap.get("regorgs"))) {
            List<String> regorgs = (List<String>) customParamMap.get("regorgs");
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REG_ORG).in(regorgs)));
        }
        // 多个属地监管机关
        if (CollectionUtils.isNotEmpty((List<String>) customParamMap.get("suporgs"))) {
            List<String> suporgs = (List<String>) customParamMap.get("suporgs");
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.SUPORG).in(suporgs)));
        }
        // 多个受理机关
        if (CollectionUtils.isNotEmpty((List<String>) customParamMap.get("acceptRegorgs"))) {
            List<String> acceptRegorgs = (List<String>) customParamMap.get("acceptRegorgs");
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ACCEPT_REG_ORG).in(acceptRegorgs)));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("enttype")))) {
            String enttype = customParamMap.get("enttype").toString();
            switch (enttype) {
                case "individual":
                    query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_TYPE).is("9910")));
                    break;
                case "farmer":
                    query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_TYPE).in("9100", "9200")));
                    break;
                case "company":
                    query.addFilterQuery(new SimpleQuery(Criteria.where("-" + EBaseInfoSolrBean.ENT_TYPE).in("9100", "9200", "9910")));
                    break;
                default:
            }
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regstate")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REG_STATE).is(customParamMap.get("regstate").toString())));
        }

        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("opscope")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.OP_SCOPE).is(customParamMap.get("opscope").toString())));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("establishDate")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.EST_DATE).between(customParamMap.get("eststartDate").toString(), customParamMap.get("estendDate").toString())));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("apprDate")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.APPR_DATE).between(DateUtil.parse(customParamMap.get("apprDatestart").toString()), DateUtil.parse(customParamMap.get("apprDateend").toString()))));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("isabn")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ISABN).is(customParamMap.get("isabn").toString())));
        }
        // 主体状态市局标准
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("entStatus")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_STATUS).is(customParamMap.get("entStatus").toString())));
        }
        // 选定年份是否年报
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("isnb"))) && StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("nbyear")))) {
            String nbyear = customParamMap.get("nbyear").toString();
            String isnb = customParamMap.get("isnb").toString();
            if ("y".equals(isnb)) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REPORT_YEAR).greaterThanEqual(nbyear)));
            } else if ("n".equals(isnb)) {
                query.addFilterQuery(new SimpleQuery(Criteria.where("-" + EBaseInfoSolrBean.REPORT_YEAR).is(nbyear)));
            }
        }
        Object reportYear = customParamMap.get("reportYear");
        if (reportYear instanceof List) {
            List<String> yearList = (List<String>) reportYear;
            query.addFilterQuery(new SimpleQuery(Criteria.where("-" + EBaseInfoSolrBean.REPORT_YEAR).in(yearList)));
        }
        Object sole = customParamMap.get("sole");
        if (sole instanceof String[]) {
            String[] soleList = (String[]) sole;
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_TYPE).in(soleList)));
        }
        Object company = customParamMap.get("company");
        if (company instanceof String[]) {
            String[] companyList = (String[]) company;
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_TYPE).in(companyList)));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("risklevel")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.LEVEL).is(customParamMap.get("risklevel").toString())));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("industryphy")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.INDUSTRY_PHY).is(customParamMap.get("industryphy").toString())));
        }

        query.setOffset(page.offset());
        query.setRows((int) page.getSize());
        org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage = solrSearchTemplate.getPageByQuery(query, EBaseInfoSolrBean.class);
        Page rs = new Page<>();
        rs.setRecords(rsPage.getContent());
        rs.setTotal(rsPage.getTotalElements());
        rs.setSize(rsPage.getSize());
        rs.setPages(rsPage.getNumber() + 1);
        return rs;
    }

    @Override
    public org.springframework.data.domain.Page<EBaseInfoSolrBean> comprehensiveQuery(Map<String, Object> customParamMap, int offset, int rows) {
        Object searchDate = customParamMap.get("establishDate");
        if (searchDate instanceof List) {
            List<String> list = (List<String>) searchDate;
            customParamMap.put("eststartDate", list.get(0));
            customParamMap.put("estendDate", list.get(1));
        }
        Object apprDate = customParamMap.get("apprDate");
        if (apprDate instanceof List) {
            List<String> list = (List<String>) apprDate;
            customParamMap.put("apprDatestart", list.get(0));
            customParamMap.put("apprDateend", list.get(1));
        }
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        //查solr
        SimpleQuery query = new SimpleQuery("*:*");
        query.setDefaultOperator(Query.Operator.AND);
        // 社会信用代码查询 - 改为精确匹配确保一致性
        if (StringUtils.isNotBlank(searchUscc)) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.UNISCID).is(searchUscc)
                    .or(Criteria.where(EBaseInfoSolrBean.REG_NO).is(searchUscc))));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("entName")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_NAME).is(customParamMap.get("entName").toString())));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("name")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.LE_REP).is(customParamMap.get("name").toString())));
        }
        //片区查询属地监管机关
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regulatory")))) {
            List<String> regulatory = (List<String>) customParamMap.get("regulatory");
            if (regulatory.size() > 0) {
                String suporg = regulatory.get(regulatory.size() - 1);
                List<String> idsByParentId = areaSliceService.getIdsByParentId(suporg);     //获取所有子片区id
                idsByParentId.add(suporg);      //加上父id
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.SAREACODE_TEMP).in(idsByParentId)));
            }
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regorg")))) {
            List<String> regorg = (List<String>) customParamMap.get("regorg");
            if (regorg.size() > 0) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REG_ORG).startsWith(regorg.get(regorg.size() - 1))));
            }
        }
//        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regorg")))) {
//            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REG_ORG).startsWith(customParamMap.get("regorg").toString())));
//        }
        String addressSearchType = StringUtils.tranObject(customParamMap.get("addressSearchType"));
        if (StringUtils.isNotBlank(addressSearchType) && "eq".equals(addressSearchType)) {
            if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("dom")))) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.DOM).is(customParamMap.get("dom").toString())));
            }
        } else {
            if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("dom")))) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.DOM).contains(customParamMap.get("dom").toString())));
            }
        }
        // 多个登记机关
        if (CollectionUtils.isNotEmpty((List<String>) customParamMap.get("regorgs"))) {
            List<String> regorgs = (List<String>) customParamMap.get("regorgs");
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REG_ORG).in(regorgs)));
        }
        // 多个属地监管机关
        if (CollectionUtils.isNotEmpty((List<String>) customParamMap.get("suporgs"))) {
            List<String> suporgs = (List<String>) customParamMap.get("suporgs");
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.SUPORG).in(suporgs)));
        }
        // 多个受理机关
        if (CollectionUtils.isNotEmpty((List<String>) customParamMap.get("acceptRegorgs"))) {
            List<String> acceptRegorgs = (List<String>) customParamMap.get("acceptRegorgs");
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ACCEPT_REG_ORG).in(acceptRegorgs)));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("enttype")))) {
            String enttype = customParamMap.get("enttype").toString();
            switch (enttype) {
                case "individual":
                    query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_TYPE).is("9910")));
                    break;
                case "farmer":
                    query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_TYPE).in("9100", "9200")));
                    break;
                case "company":
                    query.addFilterQuery(new SimpleQuery(Criteria.where("-" + EBaseInfoSolrBean.ENT_TYPE).in("9100", "9200", "9910")));
                    break;
                default:
            }
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("regstate")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REG_STATE).is(customParamMap.get("regstate").toString())));
        }

        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("opscope")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.OP_SCOPE).is(customParamMap.get("opscope").toString())));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("establishDate")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.EST_DATE).between(customParamMap.get("eststartDate").toString(), customParamMap.get("estendDate").toString())));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("apprDate")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.APPR_DATE).between(DateUtil.parse(customParamMap.get("apprDatestart").toString()), DateUtil.parse(customParamMap.get("apprDateend").toString()))));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("isabn")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ISABN).is(customParamMap.get("isabn").toString())));
        }
        // 主体状态市局标准
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("entStatus")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_STATUS).is(customParamMap.get("entStatus").toString())));
        }
        // 选定年份是否年报
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("isnb"))) && StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("nbyear")))) {
            String nbyear = customParamMap.get("nbyear").toString();
            String isnb = customParamMap.get("isnb").toString();
            if ("y".equals(isnb)) {
                query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REPORT_YEAR).greaterThanEqual(nbyear)));
            } else if ("n".equals(isnb)) {
                query.addFilterQuery(new SimpleQuery(Criteria.where("-" + EBaseInfoSolrBean.REPORT_YEAR).is(nbyear)));
            }
        }
        Object reportYear = customParamMap.get("reportYear");
        if (reportYear instanceof List) {
            List<String> yearList = (List<String>) reportYear;
            query.addFilterQuery(new SimpleQuery(Criteria.where("-" + EBaseInfoSolrBean.REPORT_YEAR).in(yearList)));
        }
        Object sole = customParamMap.get("sole");
        if (sole instanceof String[]) {
            String[] soleList = (String[]) sole;
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_TYPE).in(soleList)));
        }
        Object company = customParamMap.get("company");
        if (company instanceof String[]) {
            String[] companyList = (String[]) company;
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_TYPE).in(companyList)));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("risklevel")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.LEVEL).is(customParamMap.get("risklevel").toString())));
        }
        if (StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("industryphy")))) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.INDUSTRY_PHY).is(customParamMap.get("industryphy").toString())));
        }
        org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage;
        if (offset != -1 && rows != -1) {
//            query.addProjectionOnField(EBaseInfoSolrBean.PRIPID);
            query.setRows(rows);
            query.setOffset((long) offset);
            rsPage = solrSearchTemplate.getPageByQuery(query, EBaseInfoSolrBean.class);
        } else {
            rsPage = solrSearchTemplate.getPageByQuery(query, EBaseInfoSolrBean.class);
        }
        return rsPage;
    }

    @Override
    public Page solrQueryPripidByEntName(IPage page, EBaseinfo eBaseinfo) {

        //查solr
//        SolrQuery solrQuery = new SolrQuery();
//        solrQuery.setQuery("entName:"+ entName);
        SimpleQuery query = new SimpleQuery("*:*", Pageable.unpaged());
        query.setDefaultOperator(Query.Operator.AND);
        query.addProjectionOnFields("pripid");
        query.setOffset(page.offset());
        query.setRows((int) page.getSize());
        if (StringUtils.isNotBlank(eBaseinfo.getEntname())) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.ENT_NAME).is(eBaseinfo.getEntname())));
        }
        if (StringUtils.isNotBlank(eBaseinfo.getUniscid())) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.UNISCID).is(eBaseinfo.getUniscid())));
        }
        if (StringUtils.isNotBlank(eBaseinfo.getRegno())) {
            query.addFilterQuery(new SimpleQuery(Criteria.where(EBaseInfoSolrBean.REG_NO).is(eBaseinfo.getRegno())));
        }
        org.springframework.data.domain.Page<EBaseInfoSolrBean> rsPage = solrSearchTemplate.getPageByQuery(query, EBaseInfoSolrBean.class);
        Page rs = new Page<>();
        rs.setRecords(rsPage.getContent());
        rs.setTotal(rsPage.getTotalElements());
        rs.setSize(rsPage.getSize());
        rs.setPages(rsPage.getNumber() + 1);
        return rs;
    }

    // 精确查询或分词字段的模糊查询
    public Criteria setSolrParamWithIs(Criteria criteria, String key, String value) {
        if (criteria != null) {
            criteria = criteria.and(key).is(value);
        } else {
            criteria = new Criteria(key).is(value);
        }
        return criteria;
    }

    // 非分词字段的模糊查询
    public Criteria setSolrParamWithContains(Criteria criteria, String key, String value) {
        if (criteria != null) {
            criteria = criteria.and(key).contains(value);
        } else {
            criteria = new Criteria(key).contains(value);
        }
        return criteria;
    }

    // 区间
    public Criteria setSolrParamWithBetween(Criteria criteria, String key, String start, String end) {
        if (criteria != null) {
            criteria = criteria.and(key).between(start, end);
        } else {
            criteria = new Criteria(key).between(start, end);
        }
        return criteria;
    }

    // 对标mysql的in函数
    public Criteria setSolrParamWithIn(Criteria criteria, String key, Object... values) {
        if (criteria != null) {
            criteria = criteria.and(key).in(values);
        } else {
            criteria = new Criteria(key).in(values);
        }
        return criteria;
    }

    @Override
    public List<ComprehensiveStatistics> queryCphStatistics(Map<String, Object> customParamMap) {
        customParamMap = checkSearchDate(customParamMap);
        List<ComprehensiveStatistics> rs = baseMapper.queryCphStatistics(customParamMap);
        return rs;
    }

    @Override
    public List<ComprehensiveStat> queryCphStatSplit(Map<String, Object> customParamMap) {
        customParamMap = checkSearchDate(customParamMap);
        List<ComprehensiveStat> rs = baseMapper.queryCphStatSplit(customParamMap);

        // 一笔业务包含多个主体的要统计主体数量,
        for (ComprehensiveStat each : rs) {
            if ("abnormal".equals(customParamMap.get("bustype"))) {
                each.setAbnlrnum(baseMapper.countabnlrnum(each.getOrgn(), customParamMap));
            } else if ("illegal".equals(customParamMap.get("bustype"))) {
                each.setLeglrnum(baseMapper.countleglrnum(each.getOrgn(), customParamMap));
            }
        }

        List<RegulatoryVO> regulatoryVOS = regulatoryMapper.queryParentRegulatory();
        List<String> orgnList = new ArrayList<>();
        for (ComprehensiveStat comprehensiveStat : rs) {
            orgnList.add(comprehensiveStat.getOrgn());
        }
        for (RegulatoryVO regulatoryVO : regulatoryVOS) {
            if (StringUtils.isNotBlank(regulatoryVO.getOrgNUmber()) && !orgnList.contains(regulatoryVO.getOrgNUmber())) {
                ComprehensiveStat cphStat = new ComprehensiveStat();
                cphStat.setOrgn(regulatoryVO.getOrgNUmber());
                cphStat.setOrgunitname(regulatoryVO.getOrgUnitName());
                rs.add(cphStat);
            }
        }
        return rs;
    }

    @Override
    public List<ComprehensiveStat> queryCphStat(Map<String, Object> customParamMap) {
        customParamMap = checkSearchDate(customParamMap);
        List<ComprehensiveStat> rs = baseMapper.queryCphStat(customParamMap);
        String regionId = (String) customParamMap.get("regionId");

        // 一笔业务包含多个主体的要统计主体数量,xiangwu
/*
        for (ComprehensiveStat each : rs) {
            each.setAbnlrnum(baseMapper.countabnlrnum(each.getOrgn(), customParamMap));
            each.setLeglrnum(baseMapper.countleglrnum(each.getOrgn(), customParamMap));
            each.setLocknum(baseMapper.countlocknum(each.getOrgn(), customParamMap));
            each.setUnlocknum(baseMapper.countunlocknum(each.getOrgn(), customParamMap));
            each.setPldxnum(baseMapper.countpldxnum(each.getOrgn(), customParamMap));
        }
*/

        List<RegulatoryVO> regulatoryVOS = regulatoryMapper.queryParentRegulatory();
        List<String> orgnList = new ArrayList<>();
        for (ComprehensiveStat comprehensiveStat : rs) {
            orgnList.add(comprehensiveStat.getOrgn());
        }
        for (RegulatoryVO regulatoryVO : regulatoryVOS) {
            String orgNumber = regulatoryVO.getOrgNUmber();
            if (StringUtils.isBlank(regionId) || "150000".equals(regionId)) {
                if (StringUtils.isNotBlank(orgNumber) && !(orgNumber.length() == 6 && orgNumber.endsWith("00"))) {
                    continue;
                }
            } else if (regionId.length() == 6 && regionId.endsWith("00")) {
                if (StringUtils.isNotBlank(orgNumber) && !(orgNumber.length() == 6 && orgNumber.startsWith(regionId.substring(0,4)))) {
                    continue;
                }
            } else if (regionId.length() == 6) {
                if (StringUtils.isNotBlank(orgNumber) && !orgNumber.startsWith(regionId.substring(0,6))) {
                    continue;
                }
            } else {
                if (StringUtils.isNotBlank(orgNumber) && !orgNumber.startsWith(regionId)) {
                    continue;
                }
            }
            if (StringUtils.isNotBlank(orgNumber) && !orgnList.contains(orgNumber)) {
                ComprehensiveStat cphStat = new ComprehensiveStat();
                cphStat.setOrgn(regulatoryVO.getOrgNUmber());
                cphStat.setOrgunitname(regulatoryVO.getOrgUnitName());
                rs.add(cphStat);
            }
        }
        return rs;
    }

    @Override
    public EBaseinfo getOneByPripid(String pripid) {
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EBaseinfo::getPripid, pripid);
        return getOne(wrapper);
    }

    @Override
    public IPage<EBaseinfo> selectNbAndDom(Page<EBaseinfo> Page, Map<String, Object> customParamMap) {
        return baseMapper.selectNbAndDom(Page, customParamMap);
    }

    public Map<String, Object> checkSearchDate(Map<String, Object> customParamMap) {
        Object searchDate = customParamMap.get("searchDate");
        if (searchDate instanceof List) {
            List<String> list = (List<String>) searchDate;
            customParamMap.put("startDate", list.get(0));
            customParamMap.put("endDate", list.get(1));
        }
        return customParamMap;
    }

    @Override
    public IPage<AbnEntDto> getSDCWandTwoYearsAbnlist(IPage<AbnEntDto> page, Map<String, Object> customParamMap) {
        return baseMapper.selectSDCWandTwoYearsAbnlist(page, customParamMap);
    }

    @Override
    public IPage<NoAnnualReportEntDto> getNoReportTwoYearsPage(IPage<NoAnnualReportEntDto> page, Map<String, Object> customParamMap) {
        return baseMapper.selectNoReportTwoYearsPage(page, customParamMap);
    }

    @Override
    public EBaseinfo getEntBaseInfoByCode(String code) {
        Optional<EBaseinfo> opt = this.lambdaQuery().eq(StringUtils.isUscc(code) ? EBaseinfo::getUniscid : EBaseinfo::getRegno, code).oneOpt();
        if (!opt.isPresent()) throw new BusinessException(ResultCode.DATA_NONE);

        EBaseinfo eBaseinfo = opt.get();
        // 中文渲染
        // 经营状态
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        TRBaseCode trBaseCode = codeMap.get(eBaseinfo.getRegstate());
        if (trBaseCode != null) {
            eBaseinfo.setRegstateCn(trBaseCode.getName());
        }
        // 登记机关
        if (eBaseinfo.getRegorg() != null) {
            String regorgName = baseCodeService.getRegorgName(eBaseinfo.getRegorg());
            if (regorgName != null) {
                eBaseinfo.setRegorgCn(regorgName);
            }

        }
        return eBaseinfo;
    }

    @Override
    public IPage<Map<String, String>> selectBlackForEnt(IPage<Map<String, String>> page, String uscc, String entName) {
        return baseMapper.selectBlackForEnt(page, uscc, entName);
    }

    @Override
    public IPage<Map<String, String>> selectBlackForPerson(IPage<Map<String, String>> page, String cerNo, String name) {
        return baseMapper.selectBlackForPerson(page, cerNo, name);
    }

    @Override
    public List<Map<String, String>> statistics(String startDate, String endDate) {

        log.debug("时间条件: {}, {}", startDate, endDate);

        // 同比时间条件
        LocalDate yearOnYearStartDate = LocalDate.parse(startDate).minusYears(1);
        LocalDate yearOnYearEndDate = LocalDate.parse(endDate).minusYears(1);

        log.debug("同比时间条件: {}, {}", yearOnYearStartDate, yearOnYearEndDate);

        long days = LocalDate.parse(endDate).toEpochDay() - LocalDate.parse(startDate).toEpochDay();
        LocalDate chainRatioStartDate = LocalDate.parse(startDate).minusDays(days);
        LocalDate chainRatioEndDate = LocalDate.parse(startDate).minusDays(1);
        log.debug("环比时间条件: {}, {}", chainRatioStartDate, chainRatioEndDate);

        return baseMapper.statistics(startDate, endDate, yearOnYearStartDate.toString(), yearOnYearEndDate.toString(), chainRatioStartDate.toString(), chainRatioEndDate.toString());
    }

    @Override
    public IPage<EBaseinfo> getNoReportPage(IPage<EBaseinfo> page, Map<String, Object> customParamMap) {
        return baseMapper.selectNoReportPage(page, customParamMap);
    }

    @Override
    public IPage<EBaseinfo> getSDCWandTwoYearsPage(IPage<EBaseinfo> page, Map<String, Object> customParamMap) {
        return baseMapper.selectSDCWandTwoYearsPage(page, customParamMap);
    }

    @Override
    public IPage<EBaseinfo> getWnbAndSdcwPage(IPage<EBaseinfo> page, Map<String, Object> customParamMap) {
        return baseMapper.selectWnbAndSdcwPage(page, customParamMap);
    }

    @Override
    public IPage<Map<String, String>> getEntBlackForPerson(Page<Map<String, String>> page, String cerNo) {
        return baseMapper.getEntBlackForPerson(page, cerNo);
    }

    @Override
    public IPage<EBaseinfo> selectAddressAbnPage(IPage<EBaseinfo> page, Map<String, Object> customParamMap) {
        return baseMapper.getAddressAbnPage(page, customParamMap);
    }

    @Override
    public List<EBaseinfo> getPageOrderById(String beginId, int pageSize) {
        return baseMapper.selectIdPage(beginId, pageSize);
    }

    @Override
    public List<EBaseinfo> selectUpdatedList(String... regState) {
        // TODO 查询语句优化
        String date = DateUtils.localDateFormat(LocalDate.now(), DateUtils.DATE_DEFAULT_FORMAT);
        LambdaQueryWrapper<EBaseinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(regState.length == 1, EBaseinfo::getRegstate, regState)
                .in(regState.length > 1, EBaseinfo::getRegstate, Arrays.asList(regState))
                .notIn(EBaseinfo::getEnttype, "9100", "9200")
                .gt(StringUtils.isNotBlank(date), EBaseinfo::getSExtDatatime, date + " 00:00:00")
                .lt(StringUtils.isNotBlank(date), EBaseinfo::getSExtDatatime, date + " 05:00:00");
        return list(wrapper);
    }

    @Override
    public void clearRegulatory(String pripid) {
        AssertUtils.isNotBlank(pripid);
        baseMapper.clearRegulatory(pripid);
    }

    @Override
    public void updateRegulatory(String pripid, String orgNumber, String sliceId, String sliceName) {
        baseMapper.updateRegulatory(pripid, orgNumber, sliceId, sliceName);
    }

    @Override
    public void updateEntAreaSliceInfo(String pripid, AreaSlice areaSlice) {
        baseMapper.updateEntAreaSliceInfo(pripid, areaSlice);
    }

    @Override
    public IPage<EBaseinfo> pageByRemDate(IPage<String> page, Map<String, Object> customParamMap) {
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                customParamMap.put("uniscid", searchUscc);
            } else {
                customParamMap.put("regno", searchUscc);
            }
        }
        IPage<String> abnPripids = abnListService.selectByRemDate(page, customParamMap);
        List<String> pripids = abnPripids.getRecords();
        IPage<EBaseinfo> rs = new Page<>();
        if (pripids.size() > 0) {
            LambdaQueryWrapper wrapper = new LambdaQueryWrapper<EBaseinfo>().in(EBaseinfo::getPripid, pripids);
            rs = this.page(new Page<>(0, pripids.size()), wrapper);
        }
        rs.setTotal(abnPripids.getTotal());
        return rs;
    }

    @Override
    public List<String> pageByRemDate(Map<String, Object> customParamMap) {
        String searchUscc = StringUtils.tranObject(customParamMap.get("searchUscc"));
        if (StringUtils.isNotBlank(searchUscc)) {
            if (StringUtils.isUscc(searchUscc)) {
                customParamMap.put("uniscid", searchUscc);
            } else {
                customParamMap.put("regno", searchUscc);
            }
        }
        List<String> abnPripids = abnListService.selectByRemDate(customParamMap);
        return abnPripids;
    }

    @Override
    public HSSFWorkbook exportInfo(List<String> pripids, List<String> filedParams) {
        List<EBaseinfoExcel> infos = baseMapper.queryBypripids(pripids);
        //处理集合

        HSSFWorkbook workbook = new HSSFWorkbook();
        // 样式设置
        HSSFCellStyle style = getDefaultStyle(workbook);
        HSSFSheet sheet = workbook.createSheet("主体名单");
        // 设置表头
        HSSFRow headerRow = sheet.createRow(0);
        for (int i = 0; i < filedParams.size(); i++) {
            HSSFCell cell = headerRow.createCell(i);
            setCellValue(cell, filedParams.get(i), style);
            sheet.setColumnWidth(i, 32 * 256);
        }
        int offset = 1;
        // 动态插入列
        for (int i = 0; i < infos.size(); i++) {
            HSSFRow row = sheet.createRow(i + offset);
            row.setHeightInPoints(28f);
            for (int a = 0; a < filedParams.size(); a++) {
                String filedStr = filedParams.get(a);
                String value = getFiledValue(filedStr, infos.get(i));
                setCellValue(row.createCell(a), value, style);
            }
        }
        return workbook;
    }

    @Override
    public List<List<Object>> exportInfo2(List<String> pripids, List<String> filedParams, Boolean isHead) {
        List<EBaseinfoExcel> infos = baseMapper.queryBypripids(pripids);
        // 中文渲染
        Map<String, TRBaseCode> industryphyMap = baseCodeService.getBaseCodeMapFormCache("CA05");
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        Map<String, String> orgMap = baseCodeService.queryOrgName();
        Map<String, String> entMap = baseCodeService.queryEntType();
        for (EBaseinfoExcel eBaseinfoExcel : infos) {
            // 填充年报相关信息
            String pripid = eBaseinfoExcel.getPripid();
            TREntBaseInfo trEntBaseInfo = baseMapper.queryTREntByPripid(pripid);
            if (trEntBaseInfo != null) {
                eBaseinfoExcel.setReportYear(trEntBaseInfo.getReportyear());
                String entid = trEntBaseInfo.getEntid();
                LambdaQueryWrapper<Trentassets> tasWrapper = new LambdaQueryWrapper<>();
                tasWrapper.eq(Trentassets::getEntID, entid).ne(Trentassets::getDstate, "2");
                Trentassets trentassets = trentassetsService.getOne(tasWrapper);
                if (trentassets != null) {
                    eBaseinfoExcel.setAssetsTotalAmount(StringUtils.tranObject(trentassets.getAssetsTotalAmount()));
                    eBaseinfoExcel.setSalesAmount(StringUtils.tranObject(trentassets.getSalesAmount()));
                    eBaseinfoExcel.setProfitsAmount(StringUtils.tranObject(trentassets.getProfitsAmount()));
                    eBaseinfoExcel.setNetProfitAmount(StringUtils.tranObject(trentassets.getNetProfitAmount()));
                }
            }
            Cipentliaisons cipentliaisons = baseMapper.queryCipByPripid(pripid);
            if (cipentliaisons != null) {
                eBaseinfoExcel.setLiaName(cipentliaisons.getLiaName());
                eBaseinfoExcel.setMobileTel(cipentliaisons.getMobileTel());
            }
            // 行业门类
            TRBaseCode industryphycode = industryphyMap.get(eBaseinfoExcel.getIndustryphy());
            if (industryphycode != null) {
                eBaseinfoExcel.setIndustryphy(industryphycode.getName());
            }
            // 经营状态
            TRBaseCode code = codeMap.get(eBaseinfoExcel.getRegstate());
            if (code != null) {
                eBaseinfoExcel.setRegstateCn(code.getName());
            }
            // 登记机关
            if (eBaseinfoExcel.getRegorg() != null) {
                eBaseinfoExcel.setRegorgCn(orgMap.get(eBaseinfoExcel.getRegorg()));
            }
            //商事主体类型
            eBaseinfoExcel.setEnttypeCn(entMap.get(eBaseinfoExcel.getEnttype()));
            // 监管机关
            if (eBaseinfoExcel.getRegulatory() != null) {
                eBaseinfoExcel.setRegorgCn(orgMap.get(eBaseinfoExcel.getRegulatory()));
            }
            //属地监管所
            if (eBaseinfoExcel.getSuporg() != null) {
                List<CascadeTreeNode> org = iGzaiccodeMapper.getNameByOrg(eBaseinfoExcel.getSuporg());
                if (org.size() > 0) {
                    eBaseinfoExcel.setSuporgCn(org.get(0).getLabel());
                }
            }
            // 主营项目类别
            if (StringUtils.isNotBlank(eBaseinfoExcel.getIndustryco()) && eBaseinfoExcel.getIndustryco().length() > 1) {
                eBaseinfoExcel.setOpscotypeCn(IndustryConstant.getIndustryCN(eBaseinfoExcel.getIndustryco().substring(0, 2)));
            }
        }

        List<List<Object>> dataList = new ArrayList<>();
        // 表头数据
        if (isHead) {
            List<Object> head = new ArrayList<>();
            for (String filedParam : filedParams) {
                head.add(filedParam);
            }
            dataList.add(head);
        }
        // 动态插入列
        List<Object> row;
        for (int i = 0; i < infos.size(); i++) {
            row = new ArrayList<>();
            for (int a = 0; a < filedParams.size(); a++) {
                String filedStr = filedParams.get(a);
                String value = getFiledValue(filedStr, infos.get(i));
                row.add(value);
            }
            dataList.add(row);
        }
        return dataList;
    }

    @Override
    public List<List<Object>> exportInfo2New(List<EBaseInfoSolrBean> data, List<String> filedParams, Boolean isHead) {
        // 转换为导出对象
        List<EBaseinfoExcel> eBaseInfoExcelList = BeanUtil.copyToList(data, EBaseinfoExcel.class);

        // 中文渲染
        Map<String, TRBaseCode> industryphyMap = baseCodeService.getBaseCodeMapFormCache("CA05");
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        Map<String, String> orgMap = baseCodeService.queryOrgName();
        Map<String, String> entMap = baseCodeService.queryEntType();

        // 导出条件 -- start
        boolean isContainsReport = filedParams.contains("资产总营业") || filedParams.contains("营业收入") || filedParams.contains("利润总额") || filedParams.contains("净利润");
        boolean isContainsLiaisons = filedParams.contains("联络人") || filedParams.contains("联络人电话");
        boolean isContainsIllegal = filedParams.contains("是否列严");
        boolean isContainsAddAbn = filedParams.contains("是否地址列异");
        // 导出条件 -- end

        for (EBaseinfoExcel eBaseinfoExcel : eBaseInfoExcelList) {

            String pripid = eBaseinfoExcel.getPripid();

            // 填充年报相关信息
            if (isContainsReport) {
                TREntBaseInfo trEntBaseInfo = baseMapper.queryTREntByPripid(pripid);
                if (trEntBaseInfo != null) {
                    String entId = trEntBaseInfo.getEntid();
                    LambdaQueryWrapper<Trentassets> tasWrapper = new LambdaQueryWrapper<>();
                    tasWrapper.eq(Trentassets::getEntID, entId).ne(Trentassets::getDstate, "2").last("limit 1");
                    Trentassets trentassets = trentassetsService.getOne(tasWrapper);
                    if (trentassets != null) {
                        eBaseinfoExcel.setAssetsTotalAmount(StringUtils.tranObject(trentassets.getAssetsTotalAmount()));
                        eBaseinfoExcel.setSalesAmount(StringUtils.tranObject(trentassets.getSalesAmount()));
                        eBaseinfoExcel.setProfitsAmount(StringUtils.tranObject(trentassets.getProfitsAmount()));
                        eBaseinfoExcel.setNetProfitAmount(StringUtils.tranObject(trentassets.getNetProfitAmount()));
                    }
                }
            }

            // 填充联络员信息
            if (isContainsLiaisons) {
                Cipentliaisons cipentliaisons = baseMapper.queryCipByPripid(pripid);
                if (cipentliaisons != null) {
                    eBaseinfoExcel.setLiaName(cipentliaisons.getLiaName());
                    eBaseinfoExcel.setMobileTel(cipentliaisons.getMobileTel());
                }
            }

            // 是否列严
            if (isContainsIllegal) {
                boolean isIllegal = serIllegalListService.lambdaQuery().select(TSSerIllegalList::getIllegallistid)
                        .eq(TSSerIllegalList::getPripid, pripid)
                        .isNull(TSSerIllegalList::getYcbizseq)
                        .last("limit 1").oneOpt().isPresent();
                eBaseinfoExcel.setIsIllegalCn(isIllegal ? "是" : "否");
            }

            // 是否地址列异
            if (isContainsAddAbn) {
                boolean isAddAbn = abnListService.lambdaQuery().select(TSAbnList::getAbnlistid)
                        .eq(TSAbnList::getPripid, pripid)
                        .eq(TSAbnList::getSpecause, "4")
                        .eq(TSAbnList::getOperatestatus, "1")
                        .last("limit 1").oneOpt().isPresent();
                eBaseinfoExcel.setIsAddAbn(isAddAbn ? "是" : "否");
            }

            // 经营状态
            TRBaseCode code = codeMap.get(eBaseinfoExcel.getRegstate());
            if (code != null) {
                eBaseinfoExcel.setRegstateCn(code.getName());
            }
            // 登记机关
            if (StringUtils.isNotBlank(eBaseinfoExcel.getRegorg())) {
                eBaseinfoExcel.setRegorgCn(orgMap.get(eBaseinfoExcel.getRegorg()));
            }
            // 主营项目类别
            if (StringUtils.isNotBlank(eBaseinfoExcel.getIndustryco()) && eBaseinfoExcel.getIndustryco().length() > 1) {
                eBaseinfoExcel.setOpscotypeCn(IndustryConstant.getIndustryCN(eBaseinfoExcel.getIndustryco().substring(0, 2)));
            }
            //商事主体类型
            eBaseinfoExcel.setEnttypeCn(entMap.get(eBaseinfoExcel.getEnttype()));

            // 是否年报
            String lastYear = String.valueOf(LocalDate.now().getYear() - 1); // 获取上一年年份 通过LocalDate
            eBaseinfoExcel.setIsReportCn(lastYear.equals(eBaseinfoExcel.getReportYear()) ? "是" : "否");

            // 是否列异
            String isAbn = eBaseinfoExcel.getIsabn();
            eBaseinfoExcel.setIsabn_cn(StringUtils.isNotBlank(isAbn) && isAbn.equals("1") ? "是" : "否");
        }

        List<List<Object>> dataList = new ArrayList<>();
        // 表头数据
        if (isHead) {
            List<Object> head = new ArrayList<>();
            for (String filedParam : filedParams) {
                head.add(filedParam);
            }
            dataList.add(head);
        }
        // 动态插入列
        List<Object> row;
        for (int i = 0; i < eBaseInfoExcelList.size(); i++) {
            row = new ArrayList<>();
            for (int a = 0; a < filedParams.size(); a++) {
                String filedStr = filedParams.get(a);
                String value = getFiledValue(filedStr, eBaseInfoExcelList.get(i));
                row.add(value);
            }
            dataList.add(row);
        }
        return dataList;
    }

    @Override
    public List<List<Object>> exportInfo2(List<EBaseinfoExcel> list, List<String> filedParams) {
        // 中文渲染
        Map<String, TRBaseCode> industryphyMap = baseCodeService.getBaseCodeMapFormCache("CA05");
        Map<String, TRBaseCode> codeMap = baseCodeService.getBaseCodeMapFormCache("CA19");
        Map<String, String> orgMap = baseCodeService.queryOrgName();
        Map<String, String> entMap = baseCodeService.queryEntType();
        for (EBaseinfoExcel eBaseinfoExcel : list) {
            // 行业门类
            TRBaseCode industryphycode = industryphyMap.get(eBaseinfoExcel.getIndustryphy());
            if (industryphycode != null) {
                eBaseinfoExcel.setIndustryphy(industryphycode.getName());
            }
            // 经营状态
            TRBaseCode code = codeMap.get(eBaseinfoExcel.getRegstate());
            if (code != null) {
                eBaseinfoExcel.setRegstateCn(code.getName());
            }
            // 登记机关
            if (eBaseinfoExcel.getRegorg() != null) {
                eBaseinfoExcel.setRegorgCn(orgMap.get(eBaseinfoExcel.getRegorg()));
            }
            //商事主体类型
            eBaseinfoExcel.setEnttypeCn(entMap.get(eBaseinfoExcel.getEnttype()));
            // 监管机关
            if (eBaseinfoExcel.getRegulatory() != null) {
                eBaseinfoExcel.setRegorgCn(orgMap.get(eBaseinfoExcel.getRegulatory()));
            }
        }

        List<List<Object>> dataList = new ArrayList<>();
        // 表头数据
        List<Object> head = new ArrayList<>();
        for (String filedParam : filedParams) {
            head.add(filedParam);
        }
        dataList.add(head);
        // 动态插入列
        for (int i = 0; i < list.size(); i++) {
            List<Object> row = new ArrayList<>();
            for (int a = 0; a < filedParams.size(); a++) {
                String filedStr = filedParams.get(a);
                String value = getFiledValue(filedStr, list.get(i));
                row.add(value);
            }
            dataList.add(row);
        }
        return dataList;
    }

    @Override
    public IPage<EBaseinfo> selectYearReport(IPage<EBaseinfo> page, Map<String, Object> customParamMap) {
        return baseMapper.selectYearReport(page, customParamMap);
    }

    @Override
    public List<EBaseinfoExcel> selectYearReport(Map<String, Object> customParamMap) {
        return baseMapper.selectYearReportAll(customParamMap);
    }

    @Override
    public List<EBaseinfo> queryForNb(String regorg) {
        return baseMapper.queryForNb(regorg);
    }

    @Override
    public List<EBaseinfo> querynzForNb(String regorg) {
        return baseMapper.querynzForNb(regorg);
    }

    @Override
    public List<EBaseinfo> querygtForNb(String regorg) {
        return baseMapper.querygtForNb(regorg);
    }

    @Override
    public List<EBaseinfo> querybyperson(String name, String cerno, String type) {
        List<EBaseinfo> list = new ArrayList<>();
        List<EBaseinfo> list1 = null;
        List<EBaseinfo> list2 = null;
        list1 = baseMapper.querybyperson(name, cerno);
        list2 = baseMapper.querybyoperator(name, cerno);
//        if ("company".equals(type)) {
//            list1 = baseMapper.querybyperson(name, cerno);
//        } else if ("individual".equals(type)) {
//            list2 = baseMapper.querybyoperator(name, cerno);
//        }
        if (list1.size() > 0) {
            list.addAll(list1);
        }
        if (list2.size() > 0) {
            list.addAll(list2);
        }
        return list;
    }

    @Override
    public List<EAlterRecoder> queryEAlterByPripid(String pripid) {
        return baseMapper.queryEAlterByPripid(pripid);
    }

    /**
     * 找到对应的列在对象里的属性的值
     * @param filedStr
     * @param obj
     * @return
     */
    private String getFiledValue(String filedStr, Object obj) {
        String value = "";
        Field[] fields = obj.getClass().getDeclaredFields();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (Field field : fields) {
            String type = field.getGenericType().toString();
            FcnStr fcnStr = field.getDeclaredAnnotation(FcnStr.class);
            if (fcnStr != null) {
                String filedFcnStr = fcnStr.value();
                if (filedFcnStr.equals(filedStr)) {
                    try {
                        if (type.equals("class java.time.LocalDateTime")) {
                            LocalDateTime time = (LocalDateTime) field.get(obj);
                            if (time != null) value = df.format(time);
                        } else if (type.equals("class java.lang.String")) {
                            value = (String) field.get(obj);
                        } else if (type.equals("class java.math.BigDecimal")) {
                            BigDecimal bigStr = (BigDecimal) field.get(obj);
                            if (bigStr != null) value = bigStr.toString();
                        } else if (type.equals("class java.time.LocalDate")) {
                            LocalDate time = (LocalDate) field.get(obj);
                            if (time != null) value = time.toString();
                        } else if (type.equals("class java.lang.Integer")) {
                            Integer num = (Integer) field.get(obj);
                            if (num != null) value = num.toString();
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return value;
    }

    private HSSFCellStyle getDefaultStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short) 16);
        style.setFont(font);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    private void setCellValue(Cell cell, Object value, CellStyle style) {
        cell.setCellStyle(style);
        if (value == null) return;
        if (value instanceof BigDecimal) {
            cell.setCellValue(((BigDecimal) value).stripTrailingZeros().toPlainString());
        } else if (value instanceof LocalDateTime) {
            LocalDateTime localDateTime = (LocalDateTime) value;
            cell.setCellValue(localDateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
        } else if (value instanceof String) {
            cell.setCellValue(StringUtils.tranObject(value));
        }
    }

    @Override
    public List<EAlterRecoder> queryEAlterByEntNo(String pripid) {

        List<EAlterRecoder> listall = baseMapper.queryEAlterByPripid(pripid);
        List<EAlterRecoder> listnew = new ArrayList<>();

        if (listall.size() > 0) {
            EAlterRecoder eAlterRecoder = listall.get(0);
            for (int i = 0; i < listall.size(); i++) {
                if (eAlterRecoder.getAltdate().equals(listall.get(i).getAltdate())) {
                    listnew.add(listall.get(i));
                }
            }
        }
        return listnew;
    }

    @Override
    public List<Map<String, String>> queryEpriPersonList(String pripid) {
        return baseMapper.queryEpriPersonList(pripid);
    }

    @Override
    public List<ContactVo> queryContactByEntNo(String pripid) {

        List<ContactVo> contactVoList = new ArrayList<>();

        //获取法人信息
        LambdaQueryWrapper<EPriPersonCrgs> tasWrapper = new LambdaQueryWrapper<>();
        tasWrapper.eq(EPriPersonCrgs::getPripid, pripid).eq(EPriPersonCrgs::getLerepsign, "1");
        List<EPriPersonCrgs> ePriPersonList = ePriPersonCrgsService.list(tasWrapper);


        if (ePriPersonList.size() > 0) {
            ContactVo contactVoa = new ContactVo();
            contactVoa.setPosition("法定代表人");
            contactVoa.setName(ePriPersonList.get(0).getName());
            contactVoa.setLandline(ePriPersonList.get(0).getTelnumber());
            contactVoa.setMobile(ePriPersonList.get(0).getMobtel());
            contactVoa.setContactNumber(ePriPersonList.get(0).getTel());
            contactVoList.add(contactVoa);
        }

        //获取工商联络员信息
        LambdaQueryWrapper<E_CONTACTCrgs> ecWrapper = new LambdaQueryWrapper<>();
        ecWrapper.eq(E_CONTACTCrgs::getPripid, pripid);
        List<E_CONTACTCrgs> contactList = eContactCrgsService.list(ecWrapper);

        if (contactList.size() > 0) {
            ContactVo contactVoa = new ContactVo();
            contactVoa.setPosition("工商联络员");
            contactVoa.setName(contactList.get(0).getName());
            contactVoa.setMobile(contactList.get(0).getMobtel());
            contactVoa.setLandline(contactList.get(0).getTel());
            contactVoa.setContactNumber("");
            contactVoList.add(contactVoa);
        }

        //获取联络员信息
        Cipentliaisons cipentliaisons = baseMapper.queryCipByPripid(pripid);

        if (cipentliaisons != null) {
            ContactVo contactVoa = new ContactVo();
            contactVoa.setPosition("年报联络员");
            contactVoa.setName(cipentliaisons.getLiaName());
            contactVoa.setMobile(cipentliaisons.getMobileTel());
            contactVoa.setLandline("");
            contactVoa.setContactNumber("");
            contactVoList.add(contactVoa);
        }

        return contactVoList;
    }

    @Override
    public Map<String, Object> addContactLogByEntNo(String pripid, AICUser aicUser) {

        Map<String, Object> map = new HashMap<>();

        List<ContactVo> contactVoList = new ArrayList<>();

        //获取法人信息
        LambdaQueryWrapper<EPriPersonCrgs> tasWrapper = new LambdaQueryWrapper<>();
        tasWrapper.eq(EPriPersonCrgs::getPripid, pripid).eq(EPriPersonCrgs::getLerepsign, "1");
        List<EPriPersonCrgs> ePriPersonList = ePriPersonCrgsService.list(tasWrapper);


        if (ePriPersonList.size() > 0) {
            ContactVo contactVoa = new ContactVo();
            contactVoa.setPosition("法定代表人");
            contactVoa.setName(ePriPersonList.get(0).getName());
            contactVoa.setLandline(ePriPersonList.get(0).getTelnumber());
            contactVoa.setMobile(ePriPersonList.get(0).getMobtel());
            contactVoa.setContactNumber(ePriPersonList.get(0).getTel());
            contactVoList.add(contactVoa);
        }

        //获取工商联络员信息
        LambdaQueryWrapper<E_CONTACTCrgs> ecWrapper = new LambdaQueryWrapper<>();
        ecWrapper.eq(E_CONTACTCrgs::getPripid, pripid);
        List<E_CONTACTCrgs> contactList = eContactCrgsService.list(ecWrapper);

        if (contactList.size() > 0) {
            ContactVo contactVoa = new ContactVo();
            contactVoa.setPosition("工商联络员");
            contactVoa.setName(contactList.get(0).getName());
            contactVoa.setMobile(contactList.get(0).getMobtel());
            contactVoa.setLandline(contactList.get(0).getTel());
            contactVoa.setContactNumber("");
            contactVoList.add(contactVoa);
        }

        //获取联络员信息
        Cipentliaisons cipentliaisons = baseMapper.queryCipByPripid(pripid);

        if (cipentliaisons != null) {
            ContactVo contactVoa = new ContactVo();
            contactVoa.setPosition("年报联络员");
            contactVoa.setName(cipentliaisons.getLiaName());
            contactVoa.setMobile(cipentliaisons.getMobileTel());
            contactVoa.setLandline("");
            contactVoa.setContactNumber("");
            contactVoList.add(contactVoa);
        }

        ContactLog contactLog = new ContactLog();

        contactLog.setId(UUID.randomUUID().toString());
        contactLog.setPripId(pripid);
        contactLog.setOperatorName(aicUser.getName());
        contactLog.setOperatorId(aicUser.getPrimaryKey());
        if (contactVoList.size() > 0) {
            String result = contactVoList.stream()
                    .map(Object::toString)  // 调用每个对象的toString()方法
                    .collect(Collectors.joining(", "));
            contactLog.setContentText(result);
        } else {
            contactLog.setContentText("");
        }

        contactLog.setOperationTime(new Timestamp(System.currentTimeMillis()));
        contactLog.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        contactLog.setCreateTime(new Timestamp(System.currentTimeMillis()));

        try {
            contactLogService.save(contactLog);
            map.put("flag", "yes");
        } catch (Exception e) {
            map.put("flag", "no");
        }

        return map;
    }

    @Override
    public int automaticClaimCenter() {
        List<Map<String, String>> list = baseMapper.listIndividualLocaladm();
        int i = 0;
        for (Map<String, String> map : list) {

            String regulatory = map.get("regulatory");
            String pdRegulatory = map.get("pdRegulatory");

            // 判断当前编码是否不一致，不一致则进行更新操作
            if (StringUtils.isNotBlank(pdRegulatory) && !pdRegulatory.equals(regulatory)) {
                String pripid = map.get("pripid");
                String pdRegulatoryName = map.get("pdRegulatoryName");
                LambdaUpdateWrapper<EBaseinfo> lwu = Wrappers.lambdaUpdate();
                lwu.eq(EBaseinfo::getPripid, pripid)
                        .set(EBaseinfo::getRegulatoryTemp, pdRegulatory)
                        .set(EBaseinfo::getSuporg, pdRegulatory)
                        .set(EBaseinfo::getRegulatory, pdRegulatory)
                        .set(EBaseinfo::getSuporgCn, pdRegulatoryName)
                        .set(EBaseinfo::getRegulatoryNameTemp, pdRegulatoryName)
                        .set(EBaseinfo::getUpdateTime, LocalDateTime.now());
                update(lwu);
                i++;
            }
        }
        return i;
    }

    @Override
    public int autoEntArea() {

        //第一个方式：先通过四标四实数据-CRGS.E_DOMINFO.POLICE_ADDRESS_ID
        List<Map<String, String>> list = xdzkdyfwMapper.listMatchStreet();
        int i = 0;
        for (Map<String, String> map : list) {
            String pripid = map.get("pripid");
            String ssxzjd = map.get("ssxzjd");//镇街代码
            String sssqcjDm = map.get("sssqcjDm"); //社区代码

            if (StringUtils.isNotBlank(ssxzjd)) {
                //通过镇街查询所，如果存在多个所
                LambdaQueryWrapper<OrgAreas> lrl = Wrappers.lambdaQuery();
                lrl.eq(OrgAreas::getSsxzjd, ssxzjd);
                List<OrgAreas> orgs = orgAreasService.list(lrl);
                if (orgs.size() == 1) {
                    //匹配出只有一个所
                    LambdaUpdateWrapper<EBaseinfo> lwu = Wrappers.lambdaUpdate();
                    lwu.eq(EBaseinfo::getPripid, pripid)
                            .set(EBaseinfo::getRegulatoryTemp, orgs.get(0).getOrgNumber())
                            .set(EBaseinfo::getSuporg, orgs.get(0).getOrgNumber())
                            .set(EBaseinfo::getRegulatory, orgs.get(0).getOrgNumber())
                            .set(EBaseinfo::getSuporgCn, orgs.get(0).getOrgUnitname())
                            .set(EBaseinfo::getRegulatoryNameTemp, orgs.get(0).getOrgUnitname())
                            .set(EBaseinfo::getUpdateTime, LocalDateTime.now());
                    update(lwu);
                    i++;
                } else if (orgs.size() > 1) {
                    //匹配出多个，通过关联的社区取值
                    for (OrgAreas org : orgs) {
                        //判断社区是否存在
                        String sqdm = org.getSssqcjDm();
                        if (StringUtils.isNotBlank(sqdm) && sqdm.contains(sssqcjDm)) {
                            LambdaUpdateWrapper<EBaseinfo> lwu = Wrappers.lambdaUpdate();
                            lwu.eq(EBaseinfo::getPripid, pripid)
                                    .set(EBaseinfo::getRegulatoryTemp, org.getOrgNumber())
                                    .set(EBaseinfo::getSuporg, orgs.get(0).getOrgNumber())
                                    .set(EBaseinfo::getRegulatory, orgs.get(0).getOrgNumber())
                                    .set(EBaseinfo::getSuporgCn, orgs.get(0).getOrgUnitname())
                                    .set(EBaseinfo::getRegulatoryNameTemp, org.getOrgUnitname())
                                    .set(EBaseinfo::getUpdateTime, LocalDateTime.now());
                            update(lwu);
                            i++;
                        }
                    }
                }
            }
        }

        //第二个方式：再次检索，还存在那些没有能够通过四标四实匹配上的。则通过solr模糊匹配一遍
        List<EBaseinfo> eBaseinfos = xdzkdyfwMapper.listEntStreetEmpty();
        for (EBaseinfo eBaseinfo : eBaseinfos) {
            String dom = eBaseinfo.getDom();
            String pripid = eBaseinfo.getPripid();
            if (StringUtils.isNotBlank(dom)) {
                //通过地址模糊匹配搜索出最相近的一条数据
                SolrExGongan128Xdzkdy solrExGongan128Xdzkdy = solrExGongan128XdzkdyService.getTop1AddressMatchingDegree(dom);
                if (solrExGongan128Xdzkdy != null) {
                    String ssxzjd = solrExGongan128Xdzkdy.getSsxzjd();//镇街
                    String sssqcjDm = solrExGongan128Xdzkdy.getSssqcjDm();
                    if (StringUtils.isNotBlank(ssxzjd)) {
                        //通过镇街查询所，如果存在多个所
                        LambdaQueryWrapper<OrgAreas> lrl = Wrappers.lambdaQuery();
                        lrl.eq(OrgAreas::getSsxzjd, ssxzjd);
                        List<OrgAreas> orgs = orgAreasService.list(lrl);
                        if (orgs.size() == 1) {
                            //匹配出只有一个所
                            LambdaUpdateWrapper<EBaseinfo> lwu = Wrappers.lambdaUpdate();
                            lwu.eq(EBaseinfo::getPripid, pripid)
                                    .set(EBaseinfo::getRegulatoryTemp, orgs.get(0).getOrgNumber())
                                    .set(EBaseinfo::getSuporg, orgs.get(0).getOrgNumber())
                                    .set(EBaseinfo::getRegulatory, orgs.get(0).getOrgNumber())
                                    .set(EBaseinfo::getSuporgCn, orgs.get(0).getOrgUnitname())
                                    .set(EBaseinfo::getRegulatoryNameTemp, orgs.get(0).getOrgUnitname())
                                    .set(EBaseinfo::getUpdateTime, LocalDateTime.now());

                            update(lwu);
                            i++;
                        } else if (orgs.size() > 1) {
                            //匹配出多个，通过关联的社区取值
                            for (OrgAreas org : orgs) {
                                //判断社区是否存在
                                String sqdm = org.getSssqcjDm();
                                if (StringUtils.isNotBlank(sqdm) && sqdm.contains(sssqcjDm)) {
                                    LambdaUpdateWrapper<EBaseinfo> lwu = Wrappers.lambdaUpdate();
                                    lwu.eq(EBaseinfo::getPripid, pripid)
                                            .set(EBaseinfo::getRegulatoryTemp, org.getOrgNumber())
                                            .set(EBaseinfo::getSuporg, orgs.get(0).getOrgNumber())
                                            .set(EBaseinfo::getRegulatory, orgs.get(0).getOrgNumber())
                                            .set(EBaseinfo::getSuporgCn, orgs.get(0).getOrgUnitname())
                                            .set(EBaseinfo::getRegulatoryNameTemp, org.getOrgUnitname())
                                            .set(EBaseinfo::getUpdateTime, LocalDateTime.now());
                                    update(lwu);
                                    i++;
                                }
                            }
                        }
                    }
                } else {
                    log.info("通过地址：{}找不到相似的数据", dom);
                }
            }
        }
        return i;
    }

    @Override
    public IPage<QzzxEntDto> queryForcedLogoutEntList(IPage<QzzxEntDto> page, Map<String, Object> customParamMap) {
        return baseMapper.queryForcedLogoutEntList(page, customParamMap);
    }

    @Override
    public List<QzzxEntDto> exportQzzxEntList(Map<String, Object> paramMap) {
        return baseMapper.exportQzzxEntList(paramMap);
    }

    @Override
    public IPage<EBaseinfo> listEBaseinfo(BaseQuery<EBaseinfo> query) {
        EBaseinfo entity = query.getEntity(EBaseinfo.class);
        Page<EBaseinfo> page = query.getPage();

        String uniscId = entity.getUniscid();
        String entName = entity.getEntname();
        String searchUscc = entity.getSearchUscc();
        // 输入了条件才会查询
        if(com.chinaweal.aiccs.common.util.StringUtils.isNotEmpty(uniscId)
                || com.chinaweal.aiccs.common.util.StringUtils.isNotEmpty(entName)
                || com.chinaweal.aiccs.common.util.StringUtils.isNotEmpty(searchUscc)){
            LambdaQueryWrapper<EBaseinfo> lambdaQueryWrapper = Wrappers.lambdaQuery();

            // 添加所有适用的查询条件
            if(com.chinaweal.aiccs.common.util.StringUtils.isNotEmpty(uniscId))
                lambdaQueryWrapper.eq(EBaseinfo::getUniscid, uniscId);

            if(com.chinaweal.aiccs.common.util.StringUtils.isNotEmpty(entName))
                lambdaQueryWrapper.eq(EBaseinfo::getEntname, entName);

            if(com.chinaweal.aiccs.common.util.StringUtils.isNotEmpty(searchUscc))
                lambdaQueryWrapper.and(wrapper ->
                        wrapper.eq(EBaseinfo::getUniscid, searchUscc)
                                .or().eq(EBaseinfo::getRegno, searchUscc));
            page = page(page, lambdaQueryWrapper);

            // 更新监管机构名称
            page.getRecords().forEach(record -> {
                String suporgCn = record.getSuporgCn();
                if(com.chinaweal.aiccs.common.util.StringUtils.isNotEmpty(suporgCn)){
                    String suporg = record.getSuporg();
                    QueryWrapper<OrgUnits> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(OrgUnits::getOrgNumber, suporg)
                            .eq(OrgUnits::getDeleted, '0')
                            .eq(OrgUnits::getUnitType, "1");
                    List<OrgUnits> list = aicorgService.list(queryWrapper);
                    if (list.size() > 0) {
                        OrgUnits tOrgunits = list.get(0);
                        record.setSuporgCn(tOrgunits.getOrgUnitName());
                    }
                }
            });
        }

        return page;
    }

    @Override
    public EBaseinfo updateBaseinfoSuperviseDept(EBaseinfo eBaseinfo, String afterDeptid, AICUser user) {
        OrgUnits org = aicorgService.getOne(new LambdaQueryWrapper<OrgUnits>()
                .eq(OrgUnits::getOrgNumber, afterDeptid)
                .eq(OrgUnits::getDeleted, "0")
                .eq(OrgUnits::getUnitType, "1"));
        // 使用 LambdaUpdateWrapper 只更新指定字段
        LambdaUpdateWrapper<EBaseinfo> updateWrapper = Wrappers.lambdaUpdate(EBaseinfo.class)
                .set(EBaseinfo::getSuporg, afterDeptid)
                .set(EBaseinfo::getSuporgCn, org.getOrgUnitName())
                .set(EBaseinfo::getLocaladm, afterDeptid)
//                .set(EBaseinfo::getAcceptRegorg, afterDeptid)
//                .set(EBaseinfo::getAcceptregorgCn, org.getOrgUnitName())
                .set(EBaseinfo::getRegulatory, afterDeptid)
                .set(EBaseinfo::getRegulatoryName, org.getOrgUnitName())
                .eq(EBaseinfo::getPripid, eBaseinfo.getPripid()); // 根据主键更新
        this.update(updateWrapper);

        // 记录属地调整日志
        XrSuperviseDeptLog log = new XrSuperviseDeptLog()
                .setSuperviseLogId(UUID.randomUUID().toString())
                .setPripId(eBaseinfo.getPripid())
                .setUniscId(StringUtils.isNotEmpty(eBaseinfo.getUniscid()) ? eBaseinfo.getUniscid() : eBaseinfo.getRegno())
                .setEntName(eBaseinfo.getEntname())
                .setDeptBefore(eBaseinfo.getSuporg()) // 记录更新前的值
                .setDeptAfter(afterDeptid)
                .setOperater(user.getName())
                .setOperId(user.getPrimaryKey())
                .setOperTime(LocalDateTime.now());
        iXrSuperviseDeptLogService.save(log);
        return eBaseinfo;
    }

}
