package com.yeejoin.amos.boot.module.ymt.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.biz.common.utils.SnowflakeIdUtil;
import com.yeejoin.amos.boot.module.common.api.dao.ESEquipmentCategory;
import com.yeejoin.amos.boot.module.common.api.dao.EsEquipmentDao;
import com.yeejoin.amos.boot.module.common.api.dto.ESEquipmentCategoryDto;
import com.yeejoin.amos.boot.module.common.api.entity.ESEquipmentInfo;
import com.yeejoin.amos.boot.module.ymt.api.common.BizCommonConstant;
import com.yeejoin.amos.boot.module.ymt.api.dto.EquipExportDto;
import com.yeejoin.amos.boot.module.ymt.api.dto.EquipmentCategoryDto;
import com.yeejoin.amos.boot.module.ymt.api.dto.EquipmentMessageDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.*;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquipmentEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquipmentCategoryEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquipmentTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.*;
import com.yeejoin.amos.boot.module.ymt.api.service.IEquipmentCategoryService;
import com.yeejoin.amos.boot.module.ymt.api.service.IGenerateCodeService;
import com.yeejoin.amos.boot.module.ymt.api.vo.EquipExportVo;
import com.yeejoin.amos.boot.module.ymt.biz.dao.ESElavtorRepository;
import com.yeejoin.amos.boot.module.ymt.biz.utils.JsonUtils;
import com.yeejoin.amos.boot.module.ymt.flc.api.feign.IdxFeignService;
import com.yeejoin.amos.boot.module.ymt.flc.api.feign.PrivilegeFeginService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StopWatch;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.DateUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * 装备分类服务实现类
 *
 * @author system_generator
 * @date 2021-10-20
 */
@Service
@Slf4j
public class EquipmentCategoryServiceImpl extends BaseService<EquipmentCategoryDto, EquipmentCategory, EquipmentCategoryMapper> implements IEquipmentCategoryService {

    // 一码通码自动生成
    final static String CREATE = "1";
    // 一码通码手动输入
    final static String NOT_CREATE = "0";
    @Autowired
    private static final String TABLENAME = "tableName";
    // 管辖机构redis缓存key
    private static final String REGULATOR_UNIT_TREE = "REGULATOR_UNIT_TREE";
    // 行政区划redis缓存key
    private static final String PROVINCE = "PROVINCE";
    private static final String CITY = "CITY";
    private static final String REGION = "REGION";
    private static final String STREET = "STREET";
    // 行政区划level
    private static final String PROVINCE_LEVEL = "1";
    private static final String CITY_LEVEL = "2";
    private static final String REGION_LEVEL = "3";
    private static final String STREET_LEVEL = "4";
    // 西安行政区划code
    private static final String XIAN = "610100";
    // 咸阳行政区划code
    private static final String XIAN_YANG = "610400";
    // 杨陵行政区划code
    private static final String YANG_LING = "610403";
    // 韩城行政区划code
    private static final String HAN_CHENG = "610581";
    // 神木行政区划code
    private static final String SHEN_MU = "610881";
    // 府谷行政区划code
    private static final String FU_GU = "610822";
    // 判断行政区划查询市还是区
    private static final String END_CODE = "0000";
    // 判断行政区划查询街道
    private static final String STREET_END_CODE = "00";
    // 一码通使用信息表单id
    private static final String use_info_form_id = "1627903393253056514";
    // 一码通监督管理表单id
    private static final String supervision_form_id = "1627903532906602497";
    // 一码通设计制造表单页id
    private static final String design_from_id = "1627897116087050241";
    // 一码通检验检测表单页id
    private static final String inspection_form_id = "1636282043618848769";
    // 一码通施工信息表单页id
    private static final String construction_form_id = "1636347672031948801";
    // 一码通维保信息表单页id
    private static final String maintenance_form_id = "1636347684057018369";
    // 一码通注册登记表单页-电梯id
    private static final String dt_register_from_id = "1637431088563384322";
    // 一码通注册登记表单页-起重机械id
    private static final String qzjx_register_from_id = "1635115308320583681";
    // 一码通注册登记表单页-锅炉id
    private static final String gl_register_from_id = "1631125178945662977";
    // 一码通注册登记表单页-游乐设施id
    private static final String ylss_register_from_id = "1631125167914643457";
    // 一码通注册登记表单页-客运索道id
    private static final String kysd_register_from_id = "1631125158229995521";
    // 一码通注册登记表单页-压力管道id
    private static final String ylgd_register_from_id = "1631125206695178241";
    // 一码通注册登记表单页-压力容器id
    private static final String ylrq_register_from_id = "1631125198260432897";
    // 一码通注册登记表单页-厂车id
    private static final String cc_register_from_id = "1631125079347720193";
    // 主要零部件
    private static final String main_parts = "mainParts";
    // 主要零部件
    private static final String protection_devices = "ProtectionDevices";
    // 一码通复制功能url参数key
    private static final String COPY_KEY = "stashType";
    // 一码通判断是否复制
    private static final String IS_COPY = "isCopy";
    // 一码通生成码分布式锁key
    private final static String LOCK_KEY = "RESOURCE_KEY";
    // 一码通checkCode分布式锁key
    private final static String CHECK_CODE_LOCK_KEY = "CHECK_CODE_KEY";
    // 一码通checkCode中96333码redis key
    private final static String CHECK_CODE_CODE96333 = "CODE96333_";
    // 一码通checkCode中设备代码redis key
    private final static String CHECK_CODE_EQU_CODE = "EQU_CODE_";
    // 一码通checkCode中使用登记证编号redis key
    private final static String CHECK_CODE_USE_ORG_CODE = "USE_ORG_CODE_";
    // 管辖机构
    private static final String REGULATOR_UNIT = "监管机构";
    /**
     * levlel=company,是企业,如果不是都是监管单位,
     * * 在接口中查询当前登录人所属单位是监管单位还是企业。
     * * 如果为监管单位添加监管机构查询参数（ORG_BRANCH_CODE）；
     * * 如果为企业添加使用单位查询参数(USE_UNIT_CREDIT_CODE)
     */
    private static final String LEVEL = "company";
    private static final String EQUSTATE = "EQU_STATE";
    private static final String USEPLACE = "USE_PLACE";
    private static final String REC_DATE = "REC_DATE";
    @Autowired
    ESEquipmentCategory esEquipmentCategory;
    @Autowired
    EquipmentCategoryMapper equipmentCategoryMapper;
    @Autowired
    CategoryOtherInfoMapper categoryOtherInfoMapper;
    @Autowired
    SupervisoryCodeInfoMapper supervisoryCodeInfoMapper;
    @Autowired
    SuperviseInfoService superviseInfoService;
    @Autowired
    EquipmentCategoryDataMapper equipmentCategoryDataMapper;
    @Autowired
    EsEquipmentDao esEquipmentDao;
    @Autowired
    IdxBizJgUseInfoServiceImpl idxBizJgUseInfoService;
    @Autowired
    IdxBizJgSupervisionInfoServiceImpl idxBizJgSupervisionInfoService;
    @Autowired
    IdxBizJgOtherInfoServiceImpl idxBizJgOtherInfoService;
    @Autowired
    IdxBizJgOtherInfoMapper idxBizJgOtherInfoMapper;
    @Autowired
    IdxBizJgDesignInfoServiceImpl idxBizJgDesignInfoService;
    @Autowired
    IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;
    @Autowired
    IdxBizJgFactoryInfoMapper idxBizJgFactoryInfoMapper;
    @Autowired
    IdxBizJgInspectionDetectionInfoServiceImpl idxBizJgInspectionDetectionInfoService;
    @Autowired
    IdxBizJgConstructionInfoServiceImpl idxBizJgConstructionInfoService;
    @Autowired
    IdxBizJgMaintenanceRecordInfoServiceImpl idxBizJgMaintenanceRecordInfoService;
    @Autowired
    IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoService;
    @Autowired
    IdxBizJgTechParamsElevatorServiceImpl idxBizJgTechParamsElevatorService;
    @Autowired
    IdxBizJgTechParamsElevatorMapper idxBizJgTechParamsElevatorMapper;
    @Autowired
    IdxBizJgTechParamsVehicleServiceImpl idxBizJgTechParamsVehicleService;
    @Autowired
    IdxBizJgTechParamsVehicleMapper idxBizJgTechParamsVehicleMapper;
    @Autowired
    IdxBizJgTechParamsRopewayServiceImpl idxBizJgTechParamsRopewayService;
    @Autowired
    IdxBizJgTechParamsRopewayMapper idxBizJgTechParamsRopewayMapper;
    @Autowired
    IdxBizJgTechParamsRidesServiceImpl idxBizJgTechParamsRidesService;
    @Autowired
    IdxBizJgTechParamsRidesMapper idxBizJgTechParamsRidesMapper;
    @Autowired
    IdxBizJgTechParamsBoilerServiceImpl idxBizJgTechParamsBoilerService;
    @Autowired
    IdxBizJgTechParamsBoilerMapper idxBizJgTechParamsBoilerMapper;
    @Autowired
    IdxBizJgTechParamsVesselServiceImpl idxBizJgTechParamsVesselService;
    @Autowired
    IdxBizJgTechParamsVesselMapper idxBizJgTechParamsVesselMapper;
    @Autowired
    IdxBizJgTechParamsPipelineServiceImpl idxBizJgTechParamsPipelineService;
    @Autowired
    IdxBizJgTechParamsPipelineMapper idxBizJgTechParamsPipelineMapper;
    @Autowired
    IdxBizJgTechParamsLiftingServiceImpl idxBizJgTechParamsLiftingService;
    @Autowired
    IdxBizJgTechParamsLiftingMapper idxBizJgTechParamsLiftingMapper;
    @Autowired
    IdxBizJgMainPartsServiceImpl idxBizJgMainPartsService;
    @Autowired
    IdxBizJgMainPartsMapper idxBizJgMainPartsMapper;
    @Autowired
    IdxBizJgProtectionDevicesServiceImpl idxBizJgProtectionDevicesService;
    @Autowired
    IdxBizJgProtectionDevicesMapper idxBizJgProtectionDevicesMapper;
    @Autowired
    PrivilegeFeginService privilegeFeginService;
    @Autowired
    IdxFeignService idxFeignService;
    @Autowired
    IGenerateCodeService generateCodeService;
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    private SuperviseInfoMapper superviseInfoMapper;
    @Value("classpath:/json/equipCategory.json")
    private Resource equipCategory;
    @Autowired
    private JdbcTemplate bizJdbcTemplate;
    @Autowired
    private ESElavtorRepository esElavtorRepository;
    @Value("${regulator.unit.code}")
    private String code;

    // 仅测试时使用该起始序列号，默认为空。正式环境不配置该属性时使用枚举里的值
    @Value("${ymt.createCode.96333.startCode:}")
    private String startCode;

    @Autowired
    private SnowflakeIdUtil sequence;

    @Autowired
    private RedisUtils redisUtils;
    // 一码通checkCode中redis key过期时间
    private long time = 300l;
    private ExecutorService threadPool = Executors.newCachedThreadPool();

    /**
     * 获取两个List的不同元素
     *
     * @param list1
     * @param list2
     * @return
     */
    private static List<Integer> getDiffrent(List<Integer> list1, List<Integer> list2) {
        List<Integer> diff = new ArrayList<Integer>();
        Map<Integer, Integer> map = new HashMap<Integer, Integer>(list1.size());
        for (Integer integer : list1) {
            map.put(integer, 1);
        }
        for (Integer integer : list2) {
            if (map.get(integer) != null) {
                map.put(integer, 2);
                continue;
            }
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                diff.add(entry.getKey());
            }
        }
        // 对集合进行排序
        Collections.sort(diff);
        return diff;
    }

    /**
     * 分页查询
     */
    public Page<EquipmentCategoryDto> queryForEquipmentCategoryPage(Page<EquipmentCategoryDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<EquipmentCategoryDto> queryForEquipmentCategoryList() {
        return this.queryForList("", false);
    }

    public List<EquipmentCategoryDto> selectClassify() {
        return equipmentCategoryMapper.selectClassify();
    }

    @Override
    public List<Map<String, Object>> equipTree(String type) {
        List<Map<String, Object>> menus = new ArrayList<>();
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(equipCategory);
        List<Map<String, Object>> mapList;
        if (ValidationUtil.isEmpty(type)) {
            mapList = resourceJson.get(EquipmentClassifityEnum.BDLS.getCode());
        } else {
            if ("QTBF".equals(type)) {
                type = "superviseBusiness";
            }
            mapList = resourceJson.get(type) == null ? resourceJson.get(EquipmentClassifityEnum.BDLS.getCode()) : resourceJson.get(type);
        }
        for (Map map : mapList) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("instanceName", map.get("name"));
            resultMap.put("instanceId", map.get("code"));
            resultMap.put("image", map.get("imageUrl"));
            menus.add(resultMap);
        }
        return menus;
    }

    @Override
    public Page equipClaimOverview() {
        Page page = new Page<>();
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(equipCategory);
        List<Map<String, Object>> mapList = resourceJson.get(EquipmentClassifityEnum.BDLS.getCode());
        List<Map<String, Object>> list = new ArrayList<>();
        List<CompanyModel> companyModels = FeignUtil.remoteCall(() -> Privilege.companyClient.queryListByChild(RequestContext.getExeUserId()));
        if (companyModels.isEmpty()) {
            throw new BadRequest("未指定人员归属单位信息");
        }
        String level = companyModels.get(0).getLevel();
        String orgCode = companyModels.get(0).getOrgCode();
        String companyCode = companyModels.get(0).getCompanyCode();
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();

        if ("company".equals(level)) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            query.must(QueryBuilders.matchPhraseQuery("USE_UNIT_CREDIT_CODE", companyCode));
            boolMust.must(query);
        } else {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            query.must(QueryBuilders.matchPhrasePrefixQuery("ORG_BRANCH_CODE", orgCode));
            boolMust.must(query);
        }
        TermsAggregationBuilder field1Aggregation = AggregationBuilders
                .terms("group_by_code")
                .field("EQU_LIST_CODE")
                .size(1000);

        TermsAggregationBuilder field2Aggregation = AggregationBuilders
                .terms("group_by_status")
                .field("STATUS")
                .size(1000);
        builder.query(boolMust);
        field1Aggregation.subAggregation(field2Aggregation);
        builder.aggregation(field1Aggregation);
        builder.size(0);
        request.source(builder);
        Map<String, Object> statusCountMap = new HashMap<>();
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            Terms field1Terms = response.getAggregations().get("group_by_code");
            for (Terms.Bucket field1Bucket : field1Terms.getBuckets()) {
                Terms field2Terms = field1Bucket.getAggregations().get("group_by_status");
                for (Terms.Bucket field2Bucket : field2Terms.getBuckets()) {
                    String field1Value = field1Bucket.getKeyAsString();
                    String field2Value = EquipmentCategoryEnum.YRL.getName().equals(field2Bucket.getKeyAsString()) ? "alreadyClaim" :
                            EquipmentCategoryEnum.DRL.getName().equals(field2Bucket.getKeyAsString()) ? "waitClaim" :
                                    EquipmentCategoryEnum.YJL.getName().equals(field2Bucket.getKeyAsString()) ? "refuseClaim" : "caogao";
                    long docCount = field2Bucket.getDocCount();
                    statusCountMap.put(field1Value + "|" + field2Value, docCount);
                }
            }
        } catch (IOException e) {
            throw new BadRequest("es数据查询失败");
        }
        for (Map<String, Object> item : mapList) {
            item.put("waitClaim", this.getCountNumber(item.get("code").toString(), "waitClaim", statusCountMap));
            item.put("alreadyClaim", this.getCountNumber(item.get("code").toString(), "alreadyClaim", statusCountMap));
            item.put("refuseClaim", this.getCountNumber(item.get("code").toString(), "refuseClaim", statusCountMap));
            item.put("sum", Long.parseLong(item.get("waitClaim").toString()) + Long.parseLong(item.get("alreadyClaim").toString()) + Long.parseLong(item.get("refuseClaim").toString()));
            list.add(item);
        }
        page.setCurrent(1);
        page.setTotal(list.size());
        page.setRecords(list);
        return page;
    }

    private Long getCountNumber(String type, String status, Map<String, Object> statusCountMap) {
        String key = type + "|" + status;
        return Long.parseLong(statusCountMap.getOrDefault(key, "0").toString());
    }

    /**
     * 生成监管码和电梯96333识别码
     */
    @Override
    public Map<String, String> createSupervisorCode(Map<String, Object> map) {
        String city, county, equipCategory, isNotXiXian, code96333, superviseCode;
        // 获取对应行政区划
        city = String.valueOf(map.get("cityCode"));
        county = String.valueOf(map.get("countyCode"));
        code96333 = String.valueOf(map.get("code96333"));
        superviseCode = String.valueOf(map.get("superviseCode"));
        // 获取对应设备分类
        equipCategory = String.valueOf(map.get("equCategory"));
        if ("null".equals(equipCategory) || "null".equals(city) || "null".equals(county)) {
            throw new BadRequest("请求参数不全，请查看参数中是否携带 cityCode、countyCode、equCategory 三个参数及对应值");
        }
        isNotXiXian = Optional.ofNullable(map.get("isXiXian")).orElse("0").toString();
        // 生成码
        Map<String, String> codeMap = creatCode(isNotXiXian, city, county, equipCategory, code96333, superviseCode);
        if (ObjectUtils.isEmpty(codeMap)) {
            throw new BadRequest("该请求参数未生成监管码或96333码,请核对参数");
        }
        return codeMap;
    }

    /**
     * 批量生成监管码
     */
    @Override
    public List<Map<String, String>> createSupervisoryCodeBatch(Map<String, Object> map) {
        String city, county, equipCategory, isNotXiXian, code96333, superviseCode;
        int batchSize = 1;
        // 获取对应行政区划
        city = String.valueOf(map.get("cityCode"));
        county = String.valueOf(map.get("countyCode"));
        code96333 = String.valueOf(map.get("code96333"));
        superviseCode = String.valueOf(map.get("superviseCode"));
        // 获取对应设备分类
        equipCategory = String.valueOf(map.get("equCategory"));
        if ("null".equals(equipCategory) || "null".equals(city) || "null".equals(county)) {
            throw new BadRequest("请求参数不全，请查看参数中是否携带 cityCode、countyCode、equCategory 三个参数及对应值");
        }
        isNotXiXian = Optional.ofNullable(map.get("isXiXian")).orElse("0").toString();
        batchSize = (int) Optional.ofNullable(map.get("batchSize")).orElse(1);
        // 生成码
        List<Map<String, String>> codeMapList = creatBatchCode(isNotXiXian, city, county, equipCategory, code96333, superviseCode, batchSize);
        if (ObjectUtils.isEmpty(codeMapList)) {
            throw new BadRequest("该请求参数未生成监管码或96333码,请核对参数");
        }
        return codeMapList;
    }

    /**
     * 批量生成监管码
     */
    public List<Map<String, String>> creatBatchCode(String isNotXiXian,
                                                    String city,
                                                    String county,
                                                    String equipCategory,
                                                    String code96333,
                                                    String supervisionCode,
                                                    int batchSize) {
        RLock lock = redissonClient.getLock(LOCK_KEY);
        List<Map<String, String>> resultList = new ArrayList<>();

        try {
            lock.lock();
            log.info("加锁成功，开始生成 {} 条监管码", batchSize);
            List<String> supervisorList = createSupervisoryCodeBatch(isNotXiXian, city, county, equipCategory, batchSize);
            if (CollectionUtils.isEmpty(supervisorList)) {
                throw new BadRequest("未生成任何监管码，请检查参数");
            }

            String equState = EquipmentCategoryEnum.CSZT.getCode();
            List<SupervisoryCodeInfo> supervisoryCodeInfoList = new ArrayList<>();
            for (String supervisorCode : supervisorList) {
                SupervisoryCodeInfo newInfo = new SupervisoryCodeInfo();
                newInfo.setSupervisoryCode(supervisorCode);
                newInfo.setCode96333(code96333);
                newInfo.setCreateStatus("INIT");
                newInfo.setStatus(equState);
                newInfo.setSequenceNbr(sequence.nextId());

                supervisoryCodeInfoList.add(newInfo);
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("superviseCode", supervisorCode);
                resultMap.put("code96333", "");
                resultList.add(resultMap);
            }
            supervisoryCodeInfoMapper.insertBatchSomeColumn(supervisoryCodeInfoList, 500);
            log.info("成功生成 {} 条监管码", resultList.size());
        } catch (Exception e) {
            log.error("批量生成监管码失败", e);
            throw new RuntimeException("批量生成监管码失败: " + e.getMessage(), e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
                log.info("释放锁");
            }
        }
        return resultList;
    }

    @Override
    public List<LinkedHashMap> getTree() {
        List<LinkedHashMap> result = (List<LinkedHashMap>) redisUtils.get(BizCommonConstant.COMPANY_TREE_REDIS_KEY);
        // 判断redis是否存在管辖机构树
        return !ObjectUtils.isEmpty(result) ? result : creatTree();
    }

    /**
     * 创建监管机构树，不包含审批局
     */
    @Override
    public List<LinkedHashMap> creatTree() {
        FeignClientResult tree = privilegeFeginService.tree(RequestContext.getToken(), RequestContext.getAppKey(), RequestContext.getProduct());
        List<LinkedHashMap> result = (List<LinkedHashMap>) tree.getResult();
        List<LinkedHashMap> treeData = deleteTreeData(result, REGULATOR_UNIT);
        List<LinkedHashMap> supervisionTree = treeData.stream().filter(e -> code.equals(e.get("orgCode"))).collect(Collectors.toList());
        List<LinkedHashMap> resultTree = updateNullChildren(supervisionTree);
        redisUtils.set(BizCommonConstant.COMPANY_TREE_REDIS_KEY, resultTree);
        return resultTree;
    }

    private List<LinkedHashMap> deleteTreeData(List<LinkedHashMap> result, String companyType) {
        Iterator it = result.iterator();
        while (it.hasNext()) {
            LinkedHashMap e = (LinkedHashMap) it.next();
            // 删除非对应类型
            if (!e.get("companyType").toString().contains(companyType)) {
                it.remove();
            }
            if (!ObjectUtils.isEmpty(e.get("children"))) {
                deleteTreeData((List<LinkedHashMap>) e.get("children"), companyType);
            }
        }
        return result;
    }

    /**
     * 将管辖机构树中children为[]的修改为null
     *
     * @param result
     * @return
     */
    private List<LinkedHashMap> updateNullChildren(List<LinkedHashMap> result) {
        Iterator it = result.iterator();
        while (it.hasNext()) {
            LinkedHashMap e = (LinkedHashMap) it.next();
            // 将管辖机构树中children为[]的修改为null
            if (e.get("children") != null) {
                if (((List<LinkedHashMap>) e.get("children")).size() == 0) {
                    e.put("children", null);
                }
            }
            if (!ObjectUtils.isEmpty(e.get("children"))) {
                updateNullChildren((List<LinkedHashMap>) e.get("children"));
            }
        }
        return result;
    }

    /**
     * 删除管辖机构树中level为使用单位的数据
     *
     * @param result 管辖机构树
     * @return 筛选过滤后不包含使用单位的管辖机构树
     */
    private List<LinkedHashMap> deleteRegulatorTreeData(List<LinkedHashMap> result) {
        Iterator it = result.iterator();
        while (it.hasNext()) {
            LinkedHashMap e = (LinkedHashMap) it.next();
            // 删除使用单位
            if ("company".equals(e.get("level"))) {
                it.remove();
            }
            if (e.get("companyName").toString().contains("行政审批局")) {
                it.remove();
            }
            // 删除检验检测机构
//            if (!"company".equals(e.get("level")) && e.get("companyType").toString().contains("检验检测机构")) {
//                it.remove();
//            }
            if (!"company".equals(String.valueOf(e.get("level"))) &&
                    Arrays.asList("检验机构", "检测机构").stream().anyMatch(type -> String.valueOf(e.get("companyType")).contains(type))) {
                it.remove();
            }
            if (!ObjectUtils.isEmpty(e.get("children"))) {
                deleteRegulatorTreeData((List<LinkedHashMap>) e.get("children"));
            }
        }
        return result;
    }

    @Override
    public List<LinkedHashMap> getRegion(String level, String parentId) {
        List<LinkedHashMap> list = new ArrayList<>();
        if (!ObjectUtils.isEmpty(level)) {
            list = (List<LinkedHashMap>) redisUtils.get(PROVINCE);
            return ObjectUtils.isEmpty(list) ? getProvinceList(level) : list;
        } else if (!ObjectUtils.isEmpty(parentId)) {
            String regionCode = parentId.split("_")[0];
            // regionCode不是以00结尾查询街道，以0000结果查询市、否则查询区
            if (!regionCode.endsWith(STREET_END_CODE)) {
                list = ObjectUtils.isEmpty(redisUtils.get(STREET)) ? getProvinceList(STREET_LEVEL) : (List<LinkedHashMap>) redisUtils.get(STREET);
            } else if (regionCode.endsWith(END_CODE)) {
                list = ObjectUtils.isEmpty(redisUtils.get(CITY)) ? getProvinceList(CITY_LEVEL) : (List<LinkedHashMap>) redisUtils.get(CITY);
            } else {
                list = ObjectUtils.isEmpty(redisUtils.get(REGION)) ? getProvinceList(REGION_LEVEL) : (List<LinkedHashMap>) redisUtils.get(REGION);
            }
            return list.stream().filter(r -> regionCode.equals(r.get("parentRegionCode").toString())).collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }

    public List<LinkedHashMap> getProvinceList(String level) {
        FeignClientResult result = privilegeFeginService.getProvince(level);
        List<LinkedHashMap> list = (List<LinkedHashMap>) result.getResult();
        for (LinkedHashMap linkedHashMap : list) {
            linkedHashMap.put("sequenceNbr", linkedHashMap.get("regionCode"));
        }
        switch (level) {
            case PROVINCE_LEVEL:
                redisUtils.set(PROVINCE, list);
                break;
            case CITY_LEVEL:
                redisUtils.set(CITY, list);
                break;
            case REGION_LEVEL:
                redisUtils.set(REGION, list);
                break;
            case STREET_LEVEL:
                redisUtils.set(STREET, list);
                break;
            default:
                log.error("不支持的行政区划：{}", level);
                break;
        }
        return list;
    }

    @Override
    public Map<String, Object> getCategoryAndDefineByRecord(String record) {
        if (ObjectUtils.isEmpty(record)) {
            return new HashMap<>();
        }
        return equipmentCategoryMapper.getCategoryAndDefineByRecord(record);
    }

    @Override
    public String checkCode(Map<String, Object> obj) {
        String result = null;
        String type = ObjectUtils.isEmpty(obj.get("type")) ? null : String.valueOf(obj.get("type"));
        String code96333 = ObjectUtils.isEmpty(obj.get("CODE96333")) ? null : String.valueOf(obj.get("CODE96333"));
        String equCode = ObjectUtils.isEmpty(obj.get("EQU_CODE")) ? null : String.valueOf(obj.get("EQU_CODE"));
        String useOrgCode = ObjectUtils.isEmpty(obj.get("USE_ORG_CODE")) ? null : String.valueOf(obj.get("USE_ORG_CODE"));
        String record = ObjectUtils.isEmpty(obj.get("id")) ? null : String.valueOf(obj.get("id"));
        RLock lock = null;
        try {
            lock = redissonClient.getLock(CHECK_CODE_LOCK_KEY);
            if (!ObjectUtils.isEmpty(code96333)) {
                if (redisUtils.hasKey(CHECK_CODE_CODE96333 + code96333)) {
                    redisUtils.del(CHECK_CODE_EQU_CODE + equCode);
                    redisUtils.del(CHECK_CODE_USE_ORG_CODE + useOrgCode);
                    return "96333码重复，请确认数据是否输入正确，或联系管辖机构处理。";
                } else {
                    redisUtils.set(CHECK_CODE_CODE96333 + code96333, "1", time);
                }
            }

            if (!ObjectUtils.isEmpty(equCode)) {
                if (redisUtils.hasKey(CHECK_CODE_EQU_CODE + equCode)) {
                    redisUtils.del(CHECK_CODE_CODE96333 + code96333);
                    redisUtils.del(CHECK_CODE_USE_ORG_CODE + useOrgCode);
                    return "设备代码重复，请确认数据是否输入正确，或联系管辖机构处理。";
                } else {
                    redisUtils.set(CHECK_CODE_EQU_CODE + equCode, "1", time);
                }
            }

            if (!ObjectUtils.isEmpty(useOrgCode)) {
                if (redisUtils.hasKey(CHECK_CODE_USE_ORG_CODE + useOrgCode)) {
                    redisUtils.del(CHECK_CODE_EQU_CODE + equCode);
                    redisUtils.del(CHECK_CODE_CODE96333 + code96333);
                    return "使用登记证编号重复，请确认数据是否输入正确，或联系管辖机构处理。";
                } else {
                    redisUtils.set(CHECK_CODE_USE_ORG_CODE + useOrgCode, "1", time);
                }
            }

            Map<String, Long> map = categoryOtherInfoMapper.checkCode(type, code96333, equCode, useOrgCode, record);
            if (map.containsKey("equCode") && map.get("equCode") > 0) {
                result = "设备代码重复，请确认数据是否输入正确，或联系管辖机构处理。";
            } else if (map.containsKey("useOrgCode") && map.get("useOrgCode") > 0) {
                result = "使用登记证编号重复，请确认数据是否输入正确，或联系管辖机构处理。";
            } else if (map.containsKey("code") && map.get("code") > 0) {
                result = "96333码重复，请确认数据是否输入正确，或联系管辖机构处理。";
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock(); // 释放锁
        }
        return result;
    }

    @Override
    public List<String> updateOtherInfo(Map<String, Object> map) {
        List<String> supervisoryCodeList = (ArrayList) map.get("supervisoryCode");
        List<String> list = new ArrayList<>();
        for (String supervisoryCode : supervisoryCodeList) {
            CategoryOtherInfo categoryOtherInfo = categoryOtherInfoMapper.selectOne(new QueryWrapper<CategoryOtherInfo>().eq("SUPERVISORY_CODE", supervisoryCode));
            if (ObjectUtils.isEmpty(categoryOtherInfo)) {
                list.add(supervisoryCode + "：对应的数据修改失败，请查询对应监管码是否正确");
            } else {
                list.add(supervisoryCode + (categoryOtherInfoMapper.updateOtherInfo(supervisoryCode, "1") == 1 ? "：对应的数据已经修改成功" : "：对应的数据修改失败，请查询对应监管码是否正确"));
            }
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public synchronized String createSupervisoryCodeWithPrefix(Map<String, Object> map) {
        RLock lock = redissonClient.getLock(LOCK_KEY);
        String supervisorCode;
        try {
            lock.lock(); // 获取锁
            log.info("加锁成功");
            String prefix = MapUtil.getStr(map, "prefix");
            String categoryCode = MapUtil.getStr(map, "categoryCode");
            supervisorCode = this.createSupervisorCodeWithPrefix(prefix, categoryCode);
            log.info("生成码成功");
            SupervisoryCodeInfo supervisoryCodeInfo = new SupervisoryCodeInfo();
            SupervisoryCodeInfo selectOne = supervisoryCodeInfoMapper.selectOne(new QueryWrapper<SupervisoryCodeInfo>().eq("supervisory_code", supervisorCode.toString()));
            // 将生成的码添加到码表中，码的使用状态为初始状态
            String equState = EquipmentCategoryEnum.CSZT.getCode();
            supervisoryCodeInfo.setCreateStatus("1");
            supervisoryCodeInfo.setSupervisoryCode(supervisorCode);
            supervisoryCodeInfo.setStatus(equState);
            if (ObjectUtils.isEmpty(selectOne)) {
                supervisoryCodeInfoMapper.insert(supervisoryCodeInfo);
            } else {
                supervisoryCodeInfoMapper.update(selectOne,
                        new QueryWrapper<SupervisoryCodeInfo>().eq("supervisory_code", selectOne.getSupervisoryCode()));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock(); // 释放锁
            log.info("释放锁");
        }
        return supervisorCode;
    }

    /**
     * 具体生成监管码和电梯96333识别码逻辑
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public synchronized Map<String, String> creatCode(String isNotXiXian, String city, String county, String equipCategory, String code96333, String supervisionCode) {
        RLock lock = redissonClient.getLock(LOCK_KEY);
        Map<String, String> resultMap = null;
        try {
            lock.lock(); // 获取锁
            log.info("加锁成功");
            resultMap = new HashMap<>();
            StringBuilder supervisorCode = new StringBuilder();
            StringBuilder elevatorCode = new StringBuilder();
            CategoryOtherInfo categoryOtherInfo = new CategoryOtherInfo();
            String prefix;
            // 判断是否需要生成96333电梯码
            if (equipCategory.startsWith("3") && (((XIAN.equals(city) || XIAN_YANG.equals(city)) && "1".equals(isNotXiXian)) || !XIAN.equals(city))) {
                // 判断数据是否携带96333电梯码，携带则使用，不携带则生成
                if ("null".equals(code96333) || code96333.isEmpty()) {
                    if (((XIAN.equals(city) || XIAN_YANG.equals(city)) && "1".equals(isNotXiXian))) {
                        prefix = EquipmentCategoryEnum.XXCSM.getValue();
                    } else {
                        Map<String, Object> elevatorMap = equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQHDT.getCode(), county);
                        prefix = ObjectUtils.isEmpty(elevatorMap) ? equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQHDT.getCode(), city).get("code").toString() : elevatorMap.get("code").toString();
                    }
                    // 查询未使用的电梯码
                    categoryOtherInfo = categoryOtherInfoMapper.selectElevatorCode(prefix, EquipmentCategoryEnum.WSY.getCode());
                    // 如果存在未使用的电梯码则启用未使用的否则创建
                    String elevator = ObjectUtils.isEmpty(categoryOtherInfo) ? this.createElevatorCode(prefix) : categoryOtherInfo.getCode();
                    if (!ObjectUtils.isEmpty(categoryOtherInfo)) {
                        supervisoryCodeInfoMapper.delete(new QueryWrapper<SupervisoryCodeInfo>().eq("code96333", categoryOtherInfo.getCode()));
                    }
                    elevatorCode.append(elevator);
                    resultMap.put("creatStatus", CREATE);
                } else {
                    elevatorCode.append(code96333);
                    resultMap.put("creatStatus", NOT_CREATE);
                }
            }
            // 判断原数据是否存在监管码，存在则用原监管码即可，不存在则生成
            if ("null".equals(supervisionCode) || StringUtils.isEmpty(supervisionCode)) {
                String supervisor = createSupervisorCode(isNotXiXian, city, county, equipCategory);
                supervisorCode.append(supervisor);
            } else {
                log.info("使用上送的监管码{}，不再生成监管码", supervisionCode);
                supervisorCode = new StringBuilder(supervisionCode);
            }

            if (ObjectUtils.isEmpty(supervisorCode) && ObjectUtils.isEmpty(elevatorCode)) {
                return new HashMap<>();
            }
            log.info("生成码成功");
            SupervisoryCodeInfo supervisoryCodeInfo = new SupervisoryCodeInfo();
            SupervisoryCodeInfo selectOne = supervisoryCodeInfoMapper.selectOne(new QueryWrapper<SupervisoryCodeInfo>().eq("supervisory_code", supervisorCode.toString()));
            // 将生成的码添加到码表中，码的使用状态为初始状态
            String equState = EquipmentCategoryEnum.CSZT.getCode();
            supervisoryCodeInfo.setCode96333(String.valueOf(elevatorCode));
            supervisoryCodeInfo.setCreateStatus(resultMap.get("creatStatus"));
            supervisoryCodeInfo.setSupervisoryCode(String.valueOf(supervisorCode));
            supervisoryCodeInfo.setStatus(equState);
            if (ObjectUtils.isEmpty(selectOne)) {
                supervisoryCodeInfoMapper.insert(supervisoryCodeInfo);
            } else {
                selectOne.setCode96333(String.valueOf(elevatorCode));
                supervisoryCodeInfoMapper.update(selectOne,
                        new QueryWrapper<SupervisoryCodeInfo>().eq("supervisory_code", selectOne.getSupervisoryCode()));
            }
            // 使用UUID生成一个record,多表关联关系用
            resultMap.put("superviseCode", ObjectUtils.isEmpty(supervisorCode) ? null : supervisorCode.toString());
            resultMap.put("code96333", ObjectUtils.isEmpty(elevatorCode) ? null : elevatorCode.toString());
            resultMap.put("qrCode", ObjectUtils.isEmpty(supervisorCode) ? null : supervisorCode.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock(); // 释放锁
            log.info("释放锁");
        }
        return resultMap;
    }

    private String getPrefix(String type, String county) {
        return equipmentCategoryMapper.getAdministrativeDivision(type, county).get("code").toString();
    }


    /**
     * 生成96333电梯识别码
     *
     * @param prefix 电梯码前缀
     * @return 96333电梯识别码
     */
    public String selectExceedElevatorCode(String prefix) {
        return createElevatorCode(prefix);
//        StringBuilder elevatorCode = new StringBuilder();
//        // 生成生成96333电梯码前缀
//        elevatorCode.append(prefix);
//        String initCode = elevatorCode + EquipmentCategoryEnum.getValue.get(elevatorCode.toString());
//        CategoryOtherInfo initSupervisoryCode = categoryOtherInfoMapper.queryInitCode(initCode); // 查询是否已经生成过初始值
//        if (ValidationUtil.isEmpty(initSupervisoryCode)) {
//            elevatorCode.append(EquipmentCategoryEnum.getValue.get(prefix));
//        } else {
//            // 获取行政区划区县、市是否存在历史96333电梯码
//            CategoryOtherInfo elevatorOtherInfo = categoryOtherInfoMapper.selectElevatorCode(elevatorCode.toString(), null);
//            if (!ObjectUtils.isEmpty(elevatorOtherInfo) && elevatorOtherInfo.getCode() != null) {
//                StopWatch stopWatch = new StopWatch();
//                stopWatch.start();
//                Integer start = Integer.valueOf(prefix + EquipmentCategoryEnum.getCode.get(prefix));
//                Integer end = Integer.valueOf(elevatorOtherInfo.getCode());
//                List<Integer> allCodeList = IntStream.rangeClosed(start, end)
//                        .boxed()
//                        .collect(Collectors.toList());
//                List<Integer> codeList = categoryOtherInfoMapper.selectExceedElevatorCodeList(start, prefix);
//                List<Integer> resultList = getDiffrent(allCodeList, codeList);
//                if (!ObjectUtils.isEmpty(resultList)) {
//                    elevatorCode.setLength(0);
//                    elevatorCode.append(resultList.get(0));
//                }
//                stopWatch.stop();
//            }
//        }
//        return elevatorCode.toString();
    }

    @Override
    public String handleErrorElevatorCode(String supervisorCode, String elevatorCode) {
        Map<String, Map<String, Object>> objMap = new HashMap<>();
        // 查询目标记录
        IdxBizJgOtherInfo otherInfo = idxBizJgOtherInfoMapper.selectOne(
                new LambdaQueryWrapper<IdxBizJgOtherInfo>()
                        .eq(IdxBizJgOtherInfo::getSupervisoryCode, supervisorCode)
        );

        if (otherInfo != null) {
            // 更新其他信息表
            otherInfo.setCode96333(elevatorCode);
            idxBizJgOtherInfoService.update(otherInfo,
                    new LambdaQueryWrapper<IdxBizJgOtherInfo>().eq(IdxBizJgOtherInfo::getSupervisoryCode, supervisorCode)
            );

            // 更新码表信息
            SupervisoryCodeInfo supervisoryCodeInfo = new SupervisoryCodeInfo().setCode96333(elevatorCode);
            supervisoryCodeInfoMapper.update(supervisoryCodeInfo,
                    new QueryWrapper<SupervisoryCodeInfo>()
                            .eq("supervisory_code", supervisorCode)
            );

            // 更新 ES 数据
            Map<String, Object> param = new HashMap<>();
            param.put("CODE96333", elevatorCode);
            objMap.put(otherInfo.getRecord(), param);
            this.commonUpdateEsDataByIds(objMap);

            Optional<ESEquipmentInfo> equipmentDaoById = esEquipmentDao.findById(otherInfo.getRecord());
            equipmentDaoById.ifPresent(data -> {
                data.setCODE96333(elevatorCode);
                esEquipmentDao.save(data);
            });
        }
        return "96333码修复成功！";
    }

    /**
     * 根据前缀生成监管码
     * @param division 监管码前缀（A,B,C,D....X等）
     * @param equipCategory 设备类别
     * @return 监管码
     */
    public String createSupervisorCodeWithPrefix(String division, String equipCategory) {
        return generateCodeService.createSupervisoryCode(division + equipCategory);
    }

    /**
     * 生成监管码
     *
     * @param city   行政区划市
     * @param county 行政区划区
     * @return 监管码
     */
    public String createSupervisorCode(String isNotXiXian, String city, String county, String equipCategory) {
        StringBuilder supervisorCode = new StringBuilder();
        String division = null;
        if (((XIAN.equals(city) || XIAN_YANG.equals(city)) && "1".equals(isNotXiXian))) {
            division = "X";
        } else {
            // 生成监管码前缀
            Map<String, Object> divisionMap = equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), county);
            division = ObjectUtils.isEmpty(divisionMap) ? equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), city).get("code").toString() : divisionMap.get("code").toString();
        }
        // supervisorCode.append(division).append(equipCategory).append("-");
        supervisorCode.append(division).append(equipCategory);
        return generateCodeService.createSupervisoryCode(String.valueOf(supervisorCode));

        // 获取行政区划区县、市是否存在历史监管码
        // CategoryOtherInfo supervisor = categoryOtherInfoMapper.selectSupervisorCode(supervisorCode.toString());
        // 生成对应监管码
        // if (!ObjectUtils.isEmpty(supervisor) && supervisor.getSupervisoryCode() != null) {
        //    //获取补零位长度
        //    String supervisoryCode = supervisor.getSupervisoryCode().substring(6);
        //    long num = Long.valueOf(supervisoryCode) + 1;
        //    int numLength = String.valueOf(num).length();
        //    int a = 7 - numLength;
        //    StringBuilder zero = new StringBuilder();
        //    for (int i = 0; i < a; i++) {
        //        zero.append(EquipmentCategoryEnum.BLW.getCode());
        //    }
        //    zero.append(num);
        //    supervisorCode.append(zero);
        //} else {
        //    supervisorCode.append(EquipmentCategoryEnum.JGM.getCode());
        //}
        // return supervisorCode.toString();
    }

    /**
     * 批量生成监管码-设备批量导入使用
     *
     * @param city   行政区划市
     * @param county 行政区划区
     * @return 监管码
     */
    public List<String> createSupervisoryCodeBatch(String isNotXiXian, String city, String county, String equipCategory, int batchSize) {
        StringBuilder supervisorCode = new StringBuilder();
        String division = null;
        if (((XIAN.equals(city) || XIAN_YANG.equals(city)) && "1".equals(isNotXiXian))) {
            division = "X";
        } else {
            Map<String, Object> divisionMap = equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), county);
            division = ObjectUtils.isEmpty(divisionMap) ? equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), city).get("code").toString() : divisionMap.get("code").toString();
        }
        supervisorCode.append(division).append(equipCategory);
        return generateCodeService.createSupervisoryCodeBatch(String.valueOf(supervisorCode), batchSize);
    }

    /**
     * 生成96333电梯识别码
     *
     * @param prefix 电梯码前缀
     * @return 96333电梯识别码
     */
    public String createElevatorCode(String prefix) {
        StringBuilder elevatorCode = new StringBuilder();
        // 生成生成96333电梯码前缀
        elevatorCode.append(prefix);
        String initCode = elevatorCode + EquipmentCategoryEnum.getValue.get(elevatorCode.toString());
        CategoryOtherInfo initSupervisoryCode = categoryOtherInfoMapper.queryInitCode(initCode); // 查询是否已经生成过初始值
        if (ValidationUtil.isEmpty(initSupervisoryCode)) {
            elevatorCode.append(EquipmentCategoryEnum.getValue.get(prefix));
        } else {
            // 获取行政区划区县、市是否存在历史96333电梯码
            CategoryOtherInfo elevatorOtherInfo = categoryOtherInfoMapper.selectElevatorCode(elevatorCode.toString(), null);
            if (!ObjectUtils.isEmpty(elevatorOtherInfo) && elevatorOtherInfo.getCode() != null) {
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();
                // 改为都只拿序列号查找比较
                int start = Integer.parseInt(ValidationUtil.isEmpty(startCode) ? EquipmentCategoryEnum.getCode.get(prefix) : startCode);
                int end = Integer.parseInt(elevatorOtherInfo.getCode().substring(2));

                List<Integer> codeList = categoryOtherInfoMapper.selectExceedElevatorSequenceCodeList(Integer.valueOf(prefix + start), prefix);
                // 使用TreeSet便于快速查找和排序
                TreeSet<Integer> usedCodes = new TreeSet<>(codeList);

                Integer firstAvailableCode = null;
                // 从start开始查找第一个未使用的编码
                for (int i = start; i <= end; i++) {
                    if (!usedCodes.contains(i)) {
                        firstAvailableCode = i;
                        break;
                    }
                }

                if (firstAvailableCode != null) {
                    elevatorCode.setLength(0);
                    // firstAvailableCode 不足5位，前面补0
                    elevatorCode.append(prefix).append(String.format("%05d", firstAvailableCode.longValue()));
                } else {
                    //// 获取补零位长度
                    // String elevatorCode1 = elevatorOtherInfo.getCode().substring(2);
                    // long num = Long.parseLong(elevatorCode1) + 1;
                    // int numLength = String.valueOf(num).length();
                    // int a = 5 - numLength;
                    // StringBuilder zero = new StringBuilder();
                    // for (int i = 0; i < a; i++) {
                    //    zero.append(EquipmentCategoryEnum.BLW.getCode());
                    //}
                    // zero.append(num);
                    // elevatorCode.append(zero);
                    String newCode;
                    Integer repeatCheck;
                    do {
                        newCode = generateCodeService.createElevatorCode("96333_" + prefix);
                        repeatCheck = categoryOtherInfoMapper.checkElevatorCodeRepeat(newCode);
                    } while (repeatCheck != null && repeatCheck > 0);
                    elevatorCode = new StringBuilder(newCode);
                }
                stopWatch.stop();
            }
        }
        return elevatorCode.toString();
    }

    /**
     * 获取当前登录人单位类型
     *
     * @return
     */

    public List<JSONObject> getCompanyType() {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        List<CompanyModel> companys = reginParams.getUserModel().getCompanys();

        List<JSONObject> objectList = new ArrayList<>();
        for (CompanyModel company : companys) {
            JSONObject object = new JSONObject();
            object.put("level", company.getLevel());
            object.put("orgCode", company.getOrgCode());
            object.put("companyCode", company.getCompanyCode());
            objectList.add(object);
        }
        return objectList;
    }

    @Override
    public Map<String, Map<String, Object>> getFormRecordById(Map<String, Object> map) {
//        ResponseModel<Map<String, Map<String, Object>>> responseModel = idxFeignService.getFormRecordById(map);
//        Map<String, Map<String, Object>> result = responseModel.getResult();
        String alias = String.valueOf(map.get("alias"));
        if (ObjectUtils.isEmpty(alias)) {
            return new HashMap<>();
        }
        EquipmentTypeEnum equipmentMessage = EquipmentTypeEnum.getEnumByCode(alias);
        if (equipmentMessage == null && ObjectUtils.isEmpty(equipmentMessage)) {
            return new HashMap<>();
        }
        HashMap<String, Map<String, Object>> result = new HashMap<>();
        // 使用信息
        Map<String, Object> useInfo = getUseInfo(map);
        result.put(equipmentMessage.getUseInfo(), useInfo);
        // 设计信息
        Map<String, Object> desInfo = getDesInfo(map);
        result.put(equipmentMessage.getDesInfo(), desInfo);
        // 监督管理信息
        Map<String, Object> supInfo = getSupInfo(map);
        if ("1".equals(useInfo.get("IS_NOT_XIXIAN"))) {
            supInfo.put("CITY", "咸阳");
        } else {
            supInfo.put("CITY", useInfo.get("CITY_NAME"));
        }
        result.put(equipmentMessage.getSupInfo(), supInfo);
        // 施工信息
        Map<String, Object> comInfo = getComInfo(map);
        result.put(equipmentMessage.getComInfo(), comInfo);
        // 维保信息(只有电梯有)
        if (!ObjectUtils.isEmpty(map) && EquipmentTypeEnum.DT.getCode().equals(alias)) {
            Map<String, Object> mainInfo = getMainInfo(map);
            result.put(equipmentMessage.getMainInfo(), mainInfo);
        }
        // 检验检测信息
        Map<String, Object> insInfo = getInsInfo(map);
        result.put(equipmentMessage.getInsInfo(), insInfo);
        // 注册信息
        Map<String, Object> jriInfo = getJriInfo(map, equipmentMessage);
        result.put(equipmentMessage.getJriInfo(), jriInfo);
        if (!ObjectUtils.isEmpty(map.get(COPY_KEY))) {
            result.get(EquipmentTypeEnum.DT.getSupInfo()).remove("CLAIM_STATUS");
            result.get(EquipmentTypeEnum.DT.getSupInfo()).remove("CODE96333");
            result.get(EquipmentTypeEnum.DT.getSupInfo()).remove("SUPERVISORY_CODE");
        }
        return result;
    }

    @Override
    public Map<String, Object> getFormRecordByIdMap(Map<String, Object> map) {
//        ResponseModel<Map<String, Map<String, Object>>> responseModel = idxFeignService.getFormRecordById(map);
//        Map<String, Map<String, Object>> result = responseModel.getResult();
        String alias = String.valueOf(map.get("alias"));
        if (ObjectUtils.isEmpty(alias)) {
            return new HashMap<>();
        }
        EquipmentTypeEnum equipmentMessage = EquipmentTypeEnum.getEnumByCode(alias);
        if (equipmentMessage == null && ObjectUtils.isEmpty(equipmentMessage)) {
            return new HashMap<>();
        }
        HashMap<String, Map<String, Object>> result = new HashMap<>();
        // 使用信息
        Map<String, Object> useInfo = getUseInfo(map);
        result.put(equipmentMessage.getUseInfo(), useInfo);
        // 设计信息
        Map<String, Object> desInfo = getDesInfo(map);
        result.put(equipmentMessage.getDesInfo(), desInfo);
        // 监督管理信息
        Map<String, Object> supInfo = getSupInfo(map);
        if (!ValidationUtil.isEmpty(supInfo.get("produceDate"))) {
            LocalDate produceDate = LocalDate.parse(supInfo.get("produceDate").toString().substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate localDate = LocalDate.now().minusYears(15);
            if (produceDate.isBefore(localDate)) {
                supInfo.put("OVER_FIFTEEN_YEARS", "0");
            } else {
                supInfo.put("OVER_FIFTEEN_YEARS", "1");
            }
        }
        if ("1".equals(useInfo.get("IS_NOT_XIXIAN"))) {
            supInfo.put("CITY", "咸阳");
        } else {
            supInfo.put("CITY", useInfo.get("CITY_NAME"));
        }
        result.put(equipmentMessage.getSupInfo(), supInfo);
        // 施工信息
        Map<String, Object> comInfo = getComInfo(map);
        result.put(equipmentMessage.getComInfo(), comInfo);
        // 维保信息(只有电梯有)
        if (!ObjectUtils.isEmpty(map) && EquipmentTypeEnum.DT.getCode().equals(alias)) {
            Map<String, Object> mainInfo = getMainInfo(map);
            result.put(equipmentMessage.getMainInfo(), mainInfo);
        }
        // 检验检测信息
        Map<String, Object> insInfo = getInsInfo(map);
        result.put(equipmentMessage.getInsInfo(), insInfo);
        // 注册信息
        Map<String, Object> jriInfo = getJriInfo(map, equipmentMessage);
        result.put(equipmentMessage.getJriInfo(), jriInfo);
        if (!ObjectUtils.isEmpty(map.get(COPY_KEY))) {
            result.get(EquipmentTypeEnum.DT.getSupInfo()).remove("CLAIM_STATUS");
            result.get(EquipmentTypeEnum.DT.getSupInfo()).remove("CODE96333");
            result.get(EquipmentTypeEnum.DT.getSupInfo()).remove("SUPERVISORY_CODE");
        }

        Map<String, Object> resultMapNew = new HashMap<>();
        result.forEach((key, value) -> {
            resultMapNew.putAll(value);
        });
        return resultMapNew;
    }

    /**
     * 使用信息
     *
     * @param map
     * @return
     */
    private Map<String, Object> getUseInfo(Map<String, Object> map) {
        Map<String, Object> useInfo = equipmentCategoryMapper.selectTzsUseInfo(String.valueOf(map.get("id")));
        if (ObjectUtils.isEmpty(useInfo)) {
            return new HashMap<>();
        }
        useInfo.put("LONGITUDE_LATITUDE", JSON.parse(String.valueOf(useInfo.get("LONGITUDE_LATITUDE"))));
        return useInfo;
    }

    /**
     * 监督管理信息
     *
     * @param map
     * @return
     */
    private Map<String, Object> getSupInfo(Map<String, Object> map) {
        Map<String, Object> supInfo = equipmentCategoryMapper.selectTzsSupInfo(String.valueOf(map.get("id")));
        return supInfo;
    }

    /**
     * 注册信息
     *
     * @param map
     * @return
     */
    private Map<String, Object> getJriInfo(Map<String, Object> map, EquipmentTypeEnum equipmentMessage) {
        Map<String, Object> result;
        switch (equipmentMessage.getCode()) {
            case "3000":
                // 电梯
                result = equipmentCategoryMapper.selectTzsqzjJriInfo(String.valueOf(map.get("id")), equipmentMessage.getTableName());
                if (ObjectUtils.isEmpty(result)) {
                    return new HashMap<>();
                }
                result.put("EXPLOSIONPROOF_SIGN_COMPLETE", JSON.parseArray(String.valueOf(result.get("EXPLOSIONPROOF_SIGN_COMPLETE"))));
                break;
            case "4000":
                // 起重机械
                result = equipmentCategoryMapper.selectTzsqzjJriInfo(String.valueOf(map.get("id")), equipmentMessage.getTableName());
                if (ObjectUtils.isEmpty(result)) {
                    return new HashMap<>();
                }
                List<Map<String, Object>> lbjJriInfo = equipmentCategoryMapper.selectTzslbjJriInfo(String.valueOf(map.get("id")));
                List<Map<String, Object>> aqfjJriInfo = equipmentCategoryMapper.selectTzsaqfjJriInfo(String.valueOf(map.get("id")));
                result.put("subForm_bqirdyvztt", lbjJriInfo);
                result.put("subForm_29yy3pdzhl", aqfjJriInfo);
                result.put("subForm_h5h4x0zhur", aqfjJriInfo);
                break;
            case "5000":
                // 厂车
                result = equipmentCategoryMapper.selectTzsqzjJriInfo(String.valueOf(map.get("id")), equipmentMessage.getTableName());
                if (ObjectUtils.isEmpty(result)) {
                    return new HashMap<>();
                }
                List<Map<String, Object>> celbjJriInfo = equipmentCategoryMapper.selectTzslbjJriInfo(String.valueOf(map.get("id")));
                result.put("subForm_sey164b51a", celbjJriInfo);
                result.put("subForm_tef7yf5fbr", celbjJriInfo);
                break;
            case "1000":
                // 锅炉
                result = equipmentCategoryMapper.selectTzsqzjJriInfo(String.valueOf(map.get("id")), equipmentMessage.getTableName());
                if (ObjectUtils.isEmpty(result)) {
                    return new HashMap<>();
                }
                List<Map<String, Object>> glaqfjJriInfo = equipmentCategoryMapper.selectTzsaqfjJriInfo(String.valueOf(map.get("id")));
                result.put("subForm_1hh88r4m69", glaqfjJriInfo);
                break;
            case "2000":
                // 压力容器
                result = equipmentCategoryMapper.selectTzsqzjJriInfo(String.valueOf(map.get("id")), equipmentMessage.getTableName());
                if (ObjectUtils.isEmpty(result)) {
                    return new HashMap<>();
                }
                List<Map<String, Object>> ylrqaqfjJriInfo = equipmentCategoryMapper.selectTzsaqfjJriInfo(String.valueOf(map.get("id")));
                List<Map<String, Object>> ylrqjJriInfo = equipmentCategoryMapper.selectTzslbjJriInfo(String.valueOf(map.get("id")));
                result.put("subForm_fie04854f2", ylrqjJriInfo);
                result.put("subForm_d4xdzhsgdj", ylrqaqfjJriInfo);
                break;
            case "8000":
                // 压力容器
                result = equipmentCategoryMapper.selectTzsqzjJriInfo(String.valueOf(map.get("id")), equipmentMessage.getTableName());
                if (ObjectUtils.isEmpty(result)) {
                    return new HashMap<>();
                }
                List<Map<String, Object>> ylgdjJriInfo = equipmentCategoryMapper.selectTzslbjJriInfo(String.valueOf(map.get("id")));
                result.put("subForm_9n7nu55z8r", ylgdjJriInfo);
                break;
            case "6000":
                // 游乐设施
                result = equipmentCategoryMapper.selectTzsqzjJriInfo(String.valueOf(map.get("id")), equipmentMessage.getTableName());
                if (ObjectUtils.isEmpty(result)) {
                    return new HashMap<>();
                }
                break;
            case "9000":
                // 游乐设施
                result = equipmentCategoryMapper.selectTzsqzjJriInfo(String.valueOf(map.get("id")), equipmentMessage.getTableName());
                if (ObjectUtils.isEmpty(result)) {
                    return new HashMap<>();
                }
                List<Map<String, Object>> sdJriLbjInfo = equipmentCategoryMapper.selectTzslbjJriInfo(String.valueOf(map.get("id")));
                result.put("subForm_5fi0jewuyh", sdJriLbjInfo);
                break;
            default:
                result = new HashMap<>();
        }
        result.put("PRODUCT_PHOTO", JSON.parseArray(String.valueOf(result.get("PRODUCT_PHOTO"))));
        result.put("USE_REGISTRATION_CERTIFICATE", JSON.parseArray(String.valueOf(result.get("USE_REGISTRATION_CERTIFICATE"))));
        result.put("USE_SIGN", JSON.parseArray(String.valueOf(result.get("USE_SIGN"))));
        return result;
    }

    /**
     * 检验检测信息
     *
     * @param map
     * @return
     */
    private Map<String, Object> getInsInfo(Map<String, Object> map) {
        List<Map<String, Object>> InsInfo = equipmentCategoryMapper.selectTzsInsInfo(String.valueOf(map.get("id")));
        if (ObjectUtils.isEmpty(InsInfo)) {
            return new HashMap<>();
        }
        HashMap<String, Object> insInfoMap = new HashMap<>();
        InsInfo.forEach(item -> {
            item.put("INSPECT_REPORT", JSON.parseArray(String.valueOf(item.get("INSPECT_REPORT"))));
            if (!insInfoMap.containsKey("id")) {
                insInfoMap.put("id", item.get("RECORD"));
            }
            if (!insInfoMap.containsKey("sequenceNbr")) {
                insInfoMap.put("sequenceNbr", item.get("SEQUENCE_NBR"));
            }
            item.put("Symbol_key", item.get("SEQUENCE_NBR"));
        });
        insInfoMap.put("subForm_pbim1pfid8", InsInfo);
        return insInfoMap;
    }

    /**
     * 维保信息
     *
     * @param map
     * @return
     */
    private Map<String, Object> getMainInfo(Map<String, Object> map) {
        List<Map<String, Object>> mainInfo = equipmentCategoryMapper.selectTzsMainInfo(String.valueOf(map.get("id")));
        if (ObjectUtils.isEmpty(mainInfo)) {
            return new HashMap<>();
        }
        HashMap<String, Object> mainInfoMap = new HashMap<>();
        mainInfo.forEach(item -> {
            item.put("REPAIR_INFORM", JSON.parseArray(String.valueOf(item.get("REPAIR_INFORM"))));
            if (!mainInfoMap.containsKey("id")) {
                mainInfoMap.put("id", item.get("RECORD"));
            }
            if (!mainInfoMap.containsKey("sequenceNbr")) {
                mainInfoMap.put("sequenceNbr", item.get("SEQUENCE_NBR"));
            }
            item.put("Symbol_key", item.get("SEQUENCE_NBR"));
        });
        mainInfoMap.put("subForm_6i16fox27e", mainInfo);
        return mainInfoMap;
    }

    /**
     * 施工信息
     *
     * @param map
     * @return
     */
    private Map<String, Object> getComInfo(Map<String, Object> map) {
        List<Map<String, Object>> comList = equipmentCategoryMapper.selectTzsConInfo(String.valueOf(map.get("id")));
        if (ObjectUtils.isEmpty(comList)) {
            return new HashMap<>();
        }
        HashMap<String, Object> comMap = new HashMap<>();
        comList.forEach(item -> {
            if (!comMap.containsKey("id")) {
                comMap.put("id", item.get("RECORD"));
            }
            if (!comMap.containsKey("sequenceNbr")) {
                comMap.put("sequenceNbr", item.get("SEQUENCE_NBR"));
            }
            item.put("Symbol_key", item.get("SEQUENCE_NBR"));
        });
        comMap.put("subForm_b2x2wmcy2s", comList);
        return comMap;
    }

    /**
     * 设计信息
     *
     * @param map
     * @return
     */
    private Map<String, Object> getDesInfo(Map<String, Object> map) {
        Map<String, Object> desInfo = equipmentCategoryMapper.selectTzsDesInfo(String.valueOf(map.get("id")));
        if (ObjectUtils.isEmpty(desInfo)) {
            return new HashMap<>();
        }
        desInfo.put("DESIGN_DOC", JSON.parseArray(String.valueOf(desInfo.get("DESIGN_DOC"))));
        desInfo.put("SUPERVISION_AGENCY_CREDENTIAL", JSON.parseArray(String.valueOf(desInfo.get("SUPERVISION_AGENCY_CREDENTIAL"))));
        desInfo.put("INS_USE_MAINTAIN_EXPLAIN", JSON.parseArray(String.valueOf(desInfo.get("INS_USE_MAINTAIN_EXPLAIN"))));
        desInfo.put("TYPE_TEST_CREDENTIAL", JSON.parseArray(String.valueOf(desInfo.get("TYPE_TEST_CREDENTIAL"))));
        desInfo.put("FACTORY_STANDARD", JSON.parseArray(String.valueOf(desInfo.get("FACTORY_STANDARD"))));
        desInfo.put("DESIGN_STANDARD", JSON.parseArray(String.valueOf(desInfo.get("DESIGN_STANDARD"))));
        desInfo.put("PRODUCT_QUALITY_YIELD_PROVE", JSON.parseArray(String.valueOf(desInfo.get("PRODUCT_QUALITY_YIELD_PROVE"))));
        return desInfo;
    }

    /**
     * 分页查询数据
     */
    public Page<Map<String, Object>> getPage(Map<String, Object> map) {
        String tableName = map.get(TABLENAME).toString();
        Object sort = map.get("sort");
        Integer number = ValidationUtil.isEmpty(map.get("number")) ? 0 : Integer.valueOf(map.get("number").toString());
        Integer size = ValidationUtil.isEmpty(map.get("size")) ? 0 : Integer.valueOf(map.get("size").toString());

        Page<Map<String, Object>> page = new Page<>(number, size);
        Assert.hasText(tableName, "表名不能为空");
        String selectSql = "SELECT * FROM  " + tableName;
        String countSql = " SELECT COUNT(*) count FROM  " + tableName;

        StringJoiner andJoiner = new StringJoiner(" AND ");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!(entry.getKey().equals("tableName") || entry.getKey().equals("number") || entry.getKey().equals("size") || entry.getKey().equals("sort")) && !ValidationUtil.isEmpty(entry.getValue())) {
                if (!ValidationUtil.isEmpty(entry.getValue()) && entry.getValue().toString().contains("[") && entry.getValue().toString().contains("]")) {
                    String jsonValue = entry.getValue().toString().replace("[", "[\"").replace("]", "\"]").replaceAll(" ", "").replaceAll(",", "\",\"");
                    StringJoiner orJoiner = new StringJoiner(" or ");
                    // 兼容数据库存储String和list格式
                    JSON.parseArray(jsonValue).stream().forEach(x -> {
                        orJoiner.add(entry.getKey() + " like '%" + x + "%'");
                    });
                    andJoiner.add("(" + orJoiner + ")");
                } else {
                    andJoiner.add(entry.getKey() + " like '%" + entry.getValue().toString() + "%'");
                }
            }
        }

        if (!ValidationUtil.isEmpty(andJoiner.toString())) {
            selectSql = selectSql + " WHERE " + andJoiner;
            countSql = countSql + " WHERE " + andJoiner;
        }
        if (!ValidationUtil.isEmpty(sort)) {
            String[] split = sort.toString().split(",");
            selectSql = selectSql + " ORDER BY " + split[0] + (split[1].equals("descend") ? " DESC " : " ASC ");
        }
        int begin = (number - 1) * size;
        if (size > 0) {
            selectSql += " LIMIT " + begin + "," + size;
        }
        Long count = bizJdbcTemplate.queryForObject(countSql, Long.class);
        String finalSelectSql = selectSql;
        System.out.println("列表查询sql为--------->>>>>>>>" + finalSelectSql);
        List<Map<String, Object>> mapList = bizJdbcTemplate.queryForList(finalSelectSql);
        page.setTotal(count);
        page.setRecords(mapList);
        return page;
    }

    public Page<Map<String, Object>> getTable(Map<String, Object> map) {

        if (!ValidationUtil.isEmpty(map.get(EQUSTATE))) {
            map.put(EQUSTATE, EquipmentEnum.getCode.get(map.get(EQUSTATE).toString()).toString());
        }
        ResponseModel<Page<Map<String, Object>>> model = new ResponseModel<>();
        List<JSONObject> objectList = getCompanyType();
        List<Map<String, Object>> res = new ArrayList<>();
        if (!ObjectUtils.isEmpty(map.get(USEPLACE))) {
            String uesPlace = map.get(USEPLACE).toString();
            String address = uesPlace.substring(1, uesPlace.length() - 1);
            address = address.replace(", ", "/");
            map.put(USEPLACE, address);
        }
        Long total = 0L;
        for (JSONObject object : objectList) {
            String level = object.getString("level");
            String code = object.getString("orgCode");
            String companyCode = object.getString("companyCode");
            if (!ValidationUtil.isEmpty(level)) {
                Page<Map<String, Object>> m = new Page<>();
                if (LEVEL.equals(level)) {
                    // 企业
                    map.put("USE_UNIT_CREDIT_CODE", companyCode);
                    m = this.getPage(map);
                    map.remove("USE_UNIT_CREDIT_CODE");
                } else {
                    // 监管单位
                    map.put("ORG_BRANCH_CODE", code);
                    m = this.getPage(map);
                    map.remove("ORG_BRANCH_CODE");
                }
                total += m.getTotal();
                if (!ValidationUtil.isEmpty(m) && !ValidationUtil.isEmpty(m.getRecords())) {
                    res.addAll(m.getRecords());
                }
            }
        }

        Page<Map<String, Object>> objectPage = new Page<>();
        objectPage.setRecords(res);
        objectPage.setTotal(total);
        objectPage.setSize(Long.valueOf(map.get("size").toString()));
        objectPage.setCurrent(Long.valueOf(map.get("number").toString()));
        model.setResult(objectPage);
        // 设备状态码对应枚举值
        List<Map<String, Object>> records = model.getResult().getRecords();
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> record : records) {
            if (!ValidationUtil.isEmpty(record.get(EQUSTATE))) {
                Integer integer = Integer.valueOf(record.get(EQUSTATE).toString());
                String status = EquipmentEnum.getName.get(integer);
                record.put(EQUSTATE, status);
            }
            result.add(record);
        }
        Page<Map<String, Object>> mapPage = model.getResult().setRecords(result);
        return mapPage;
    }


    public List<Map<String, Object>> scalp(Map<String, Object> map) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (!ValidationUtil.isEmpty(map.get("orgBranchName"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    map.get("orgBranchName").toString(), null, null, null, null);
        }
        if (!ValidationUtil.isEmpty(map.get("equList"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    null, map.get("equList").toString(), null, null, null);
        }
        if (!ValidationUtil.isEmpty(map.get("equCategory"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    null, null, map.get("equCategory").toString(), null, null);
        }
        if (!ValidationUtil.isEmpty(map.get("usePlace"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    null, null, null, map.get("usePlace").toString(), null);
        }
        if (!ValidationUtil.isEmpty(map.get("equState"))) {
            list = equipmentCategoryMapper.getSrcee(map.get(TABLENAME).toString(),
                    null, null, null, null, map.get("equState").toString());
        }
        return list;
    }

    public List<EquipExportVo> getEquipExportData(EquipExportDto dto) {
        ArrayList<EquipExportVo> list = new ArrayList<>();
        List<JSONObject> objectList = getCompanyType();
        if (!ValidationUtil.isEmpty(dto.getEQU_STATE())) {
            dto.setEQU_STATE(EquipmentEnum.getCode.get(dto.getEQU_STATE()).toString());
        }
        for (JSONObject object : objectList) {
            String level = object.getString("level");
            String orgCode = object.getString("orgCode");
            String companyCode = object.getString("companyCode");
            if (!ValidationUtil.isEmpty(level)) {
                if (LEVEL.equals(level)) {
                    // 企业
                    dto.setUSE_UNIT_CREDIT_CODE(companyCode);
                } else {
                    // 监管单位
                    dto.setORG_BRANCH_CODE(ObjectUtils.isEmpty(dto.getORG_BRANCH_CODE()) ? orgCode : dto.getORG_BRANCH_CODE());
                }
                List<EquipExportVo> equipExportData = equipmentCategoryMapper.getEquipExportData(dto);
                if (!ObjectUtils.isEmpty(equipExportData)) {
                    list.addAll(equipExportData);
                }
            }
        }
        return list;
    }

    public List<EquipExportVo> exportImageZip(EquipExportDto dto, Long pageNum, Long size) {
        ArrayList<EquipExportVo> list = new ArrayList<>();
        List<JSONObject> objectList = getCompanyType();
        if (!ValidationUtil.isEmpty(dto.getEQU_STATE())) {
            dto.setEQU_STATE(EquipmentEnum.getCode.get(dto.getEQU_STATE()).toString());
        }
        for (JSONObject object : objectList) {
            String level = object.getString("level");
            String orgCode = object.getString("orgCode");
            String companyCode = object.getString("companyCode");
            if (!ValidationUtil.isEmpty(level)) {
                Page<EquipExportVo> equipExportVoPage = new Page<>(pageNum, size);
                if (LEVEL.equals(level)) {
                    // 企业
                    dto.setUSE_UNIT_CREDIT_CODE(companyCode);
                } else {
                    // 监管单位
                    dto.setORG_BRANCH_CODE(orgCode);
                }
                Page<EquipExportVo> equipExportData = equipmentCategoryMapper.exportImageZip(equipExportVoPage, dto);
                if (!ObjectUtils.isEmpty(equipExportData) && !ObjectUtils.isEmpty(equipExportData.getRecords())) {
                    list.addAll(equipExportData.getRecords());
                }
            }
        }
        return list;
    }

    /**
     * 设备字典,通过设备父类code,获得子类
     */
    public List<EquipmentCategory> getChildren(String code) {
        LambdaQueryWrapper<EquipmentCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipmentCategory::getCode, code);
        EquipmentCategory equipmentCategory = baseMapper.selectOne(wrapper);
        LambdaQueryWrapper<EquipmentCategory> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(EquipmentCategory::getParentId, equipmentCategory.getId());
        List<EquipmentCategory> equipmentCategories = baseMapper.selectList(wrapper2);
        return equipmentCategories;
    }


    @Override
    public void checkEsData(String id) {
        Map<String, Object> map = categoryOtherInfoMapper.selectJgAllViewDataById(id);
        categoryOtherInfoMapper.updateEsStatus(id);
        ESEquipmentCategoryDto dto = JSON.parseObject(toJSONString(map), ESEquipmentCategoryDto.class);
        Optional<ESEquipmentCategoryDto> data = esEquipmentCategory.findById(id);
        if (!ObjectUtils.isEmpty(data)) {
            esEquipmentCategory.deleteById(id);
        }
        if (!ObjectUtils.isEmpty(dto)) {
            long time = Timestamp.valueOf(map.get("REC_DATE").toString().substring(0, 19)).getTime();
            dto.setREC_DATE(time);
            esEquipmentCategory.save(dto);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> deleteBatch(Map<String, Object> map) {
        Object recordList = map.get("recordList");
        List<String> records = new ArrayList<>();
        List<ESEquipmentCategoryDto> list = new ArrayList<>();
        List<EsElevator> esElevatorList = new ArrayList<>();
        if (recordList.toString().contains("[")) {
            for (String record : (List<String>) recordList) {
                records.add(record);
                ESEquipmentCategoryDto esEquipmentCategoryDto = new ESEquipmentCategoryDto();
                esEquipmentCategoryDto.setSEQUENCE_NBR(record);
                list.add(esEquipmentCategoryDto);
                EsElevator esElevator = new EsElevator();
                esElevator.setSequenceNbr(record);
                esElevatorList.add(esElevator);
            }
        } else {
            records.add(recordList.toString());
            ESEquipmentCategoryDto esEquipmentCategoryDto = new ESEquipmentCategoryDto();
            esEquipmentCategoryDto.setSEQUENCE_NBR(recordList.toString());
            list.add(esEquipmentCategoryDto);
            EsElevator esElevator = new EsElevator();
            esElevator.setSequenceNbr(recordList.toString());
            esElevatorList.add(esElevator);
        }
        // 删除监管码表数据
        List<String> superviseCodeList = superviseInfoMapper.selectSuperviseCodeList(records);
        List<Map<String, Object>> unitCodeAndOrgBranchCodeList = superviseInfoMapper.selectUnitCodeList(records);
        List<String> unitCodeList = new ArrayList<>();
        List<String> orgBranchCodeList = new ArrayList<>();
        for (Map<String, Object> objectMap : unitCodeAndOrgBranchCodeList) {
            unitCodeList.add(String.valueOf(objectMap.get("unitCode")));
            orgBranchCodeList.add(String.valueOf(objectMap.get("orgBranchCode")));
        }

        if (!ObjectUtils.isEmpty(superviseCodeList)) {
            supervisoryCodeInfoMapper.updateStatus(superviseCodeList);
        }
        // 删除es中elev中的相关数据
        esElavtorRepository.deleteAll(esElevatorList);
        // 删除涉及的19张表的数据
        superviseInfoMapper.deleteDataAll(records);
        // 删除es中的数据
        esEquipmentCategory.deleteAll(list);
        return records;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseModel submit(Map<String, Object> map) {
        SupervisoryCodeInfo supervisoryCodeInfo = new SupervisoryCodeInfo();
        LinkedHashMap useInfoFrom = (LinkedHashMap) map.get(use_info_form_id);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        useInfoFrom.put("REC_DATE", dateFormat.format(calendar.getTime()));
        String unitCode = String.valueOf(useInfoFrom.get("USE_UNIT_CREDIT_CODE"));
        String isNotXiXian = "null".equals(String.valueOf(useInfoFrom.get("IS_NOT_XIXIAN"))) ? "0" : String.valueOf(useInfoFrom.get("IS_NOT_XIXIAN"));
        LinkedHashMap supervisionMap = (LinkedHashMap) map.get(supervision_form_id);
        String record = null;
        LinkedHashMap superviseMap = (LinkedHashMap) map.get("data");
        String equCategory = String.valueOf(superviseMap.get("equCategory"));
        String code96333 = String.valueOf(superviseMap.get("code96333"));
        String useOrgCode = null;
        String equCode = null;
        String alias = String.valueOf(supervisionMap.get("ALIAS"));
        if ("null".equals(alias)) {
            throw new BadRequest("该数据存在问题，请联系管理员补充数据的ALIAS字段");
        }
        LinkedHashMap registerForm = null;
        if (EquipmentTypeEnum.GL.getCode().equals(alias)) {
            registerForm = (LinkedHashMap) map.get(gl_register_from_id);
        } else if (EquipmentTypeEnum.YL_RQ.getCode().equals(alias)) {
            registerForm = (LinkedHashMap) map.get(ylrq_register_from_id);
        } else if (EquipmentTypeEnum.DT.getCode().equals(alias)) {
            registerForm = (LinkedHashMap) map.get(dt_register_from_id);
        } else if (EquipmentTypeEnum.QZJ.getCode().equals(alias)) {
            registerForm = (LinkedHashMap) map.get(qzjx_register_from_id);
        } else if (EquipmentTypeEnum.CS.getCode().equals(alias)) {
            registerForm = (LinkedHashMap) map.get(cc_register_from_id);
        } else if (EquipmentTypeEnum.YL_SS.getCode().equals(alias)) {
            registerForm = (LinkedHashMap) map.get(ylss_register_from_id);
        } else if (EquipmentTypeEnum.YL_GD.getCode().equals(alias)) {
            registerForm = (LinkedHashMap) map.get(ylgd_register_from_id);
        } else {
            registerForm = (LinkedHashMap) map.get(kysd_register_from_id);
        }
        useOrgCode = ObjectUtils.isEmpty(registerForm.get("USE_ORG_CODE")) ? null : String.valueOf(registerForm.get("USE_ORG_CODE"));
        equCode = ObjectUtils.isEmpty(registerForm.get("EQU_CODE")) ? null : String.valueOf(registerForm.get("EQU_CODE"));
        try {
            String claimStatus = String.valueOf(superviseMap.get("claimStatus"));
            String operateType = String.valueOf(superviseMap.get("operateType"));
            String isCopy = String.valueOf(useInfoFrom.get("isCopy"));
            // 生成码
            Map<String, String> codeMap = new HashMap<>();
            if (EquipmentCategoryEnum.YRL.getName().equals(claimStatus)) {
                log.info("准备生成监管码或96333电梯识别码");
                String city = String.valueOf(superviseMap.get("city"));
                String county = String.valueOf(superviseMap.get("county"));
                String supervisionCode = String.valueOf(superviseMap.get("supervisionCode"));
                EquipmentCategoryServiceImpl categoryService = (EquipmentCategoryServiceImpl) AopContext.currentProxy();
                // 生成码
                codeMap = categoryService.creatCode(isNotXiXian, city, county, equCategory, code96333, supervisionCode);
                // 删除map中的冗余数据，添加对应监管码和96333码调用idx多表单页提交接口吧保存数据
                map.remove("data");
                supervisionMap.put("CODE96333", codeMap.get("code96333"));
                supervisionMap.put("SUPERVISORY_CODE", codeMap.get("superviseCode"));
                map.put(supervision_form_id, supervisionMap);
                record = batchSubmitOrUpdate(map, registerForm, alias, isCopy, operateType, claimStatus);
                if (!ObjectUtils.isEmpty(record)) {
                    supervisoryCodeInfo.setStatus(EquipmentCategoryEnum.YSY.getCode());
                } else {
                    equipmentCategoryMapper.updateIsNotEs(String.valueOf(supervisionMap.get("SUPERVISORY_CODE")));
                    supervisoryCodeInfo.setStatus(EquipmentCategoryEnum.WSY.getCode());
                }
            } else if (EquipmentCategoryEnum.DRL.getName().equals(claimStatus)) {
                supervisionMap.put("CODE96333", "null".equals(code96333) ? null : code96333);
                map.put(supervision_form_id, supervisionMap);
                supervisoryCodeInfo.setCode96333("null".equals(code96333) ? null : code96333);
                // 根据操作状态判断是调用新增还是修改接口
                record = batchSubmitOrUpdate(map, registerForm, alias, isCopy, operateType, claimStatus);
            } else {
                record = batchSubmitOrUpdate(map, registerForm, alias, isCopy, operateType, claimStatus);
            }
            if (!ObjectUtils.isEmpty(record)) {
                checkEsData(record);
            }
            String finalRecord = record;
            threadPool.submit(() -> {
                if (log.isInfoEnabled()) {
                    log.info("企业统一信用代码-------->>>>>>>>>>{}", unitCode);
                    log.info("已生成对应监管码" + supervisionMap.get("SUPERVISORY_CODE"));
                    log.info("已生成对应96333电梯识别码" + supervisionMap.get("CODE96333"));
                }
                saveEsElevator2ES(finalRecord);
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            equipmentCategoryMapper.updateIsNotEs(String.valueOf(supervisionMap.get("SUPERVISORY_CODE")));
            if (!ObjectUtils.isEmpty(record)) {
                List<String> records = new ArrayList<>();
                records.add(record);
                superviseInfoMapper.deleteDataAll(records);
                esEquipmentCategory.deleteById(record);
            }
            supervisoryCodeInfo.setStatus(EquipmentCategoryEnum.WSY.getCode());
            ResponseModel<Object> response = new ResponseModel<>();
            response.setDevMessage(e.getMessage());
            response.setResult(null);
            response.setMessage("操作失败，请检查数据输入后重新提交");
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            return response;
        } finally {
            redisUtils.del(CHECK_CODE_EQU_CODE + equCode);
            redisUtils.del(CHECK_CODE_CODE96333 + code96333);
            redisUtils.del(CHECK_CODE_USE_ORG_CODE + useOrgCode);
            supervisoryCodeInfoMapper.update(supervisoryCodeInfo, new QueryWrapper<SupervisoryCodeInfo>().eq("supervisory_code", supervisionMap.get("SUPERVISORY_CODE")));
        }
        return ResponseHelper.buildResponse(record);
    }

    @Override
    public void creatXiXian(String type) {
        // 1查找以31或者33开头且为用户手动录入的96333码对应的数据writeRecordList
        List<String> writeRecordList = equipmentCategoryMapper.selectWriteXiXian();
        if (!ObjectUtils.isEmpty(writeRecordList)) {
            // 1.1删除码表中以31或者33开头且为用户手动录入
            equipmentCategoryMapper.clearSupervisoryCodeAndXiXian();
            // 1.2将以31或者33开头且为用户手动录入的96333码对应的数据的监管码清空
            equipmentCategoryMapper.updateSupervisoryCode(writeRecordList);
        }
        // 2查找管辖机构为西咸，但96333码不为31开头的数据recordList
        List<String> recordList = !"new".equals(type) ? equipmentCategoryMapper.selectXiXian() : equipmentCategoryMapper.selectXiXianNew();
        if (!ObjectUtils.isEmpty(recordList)) {
            // 2.1删除码表中recordList对应的码数据
            equipmentCategoryMapper.clearSupervisoryCode();
            // 2.2清空业务表中recordList对应的96333码和监管码
            equipmentCategoryMapper.clearCode(recordList);
        }
        // 3 将recordList合并到writeRecordList
        writeRecordList.addAll(recordList);
        List<Map<String, Object>> equCategoryList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(writeRecordList)) {
            equCategoryList = equipmentCategoryMapper.getEquCategory(writeRecordList);
            // 4、生成对应的96333和监管码
            for (Map<String, Object> map : equCategoryList) {
                String code96333 = null;
                String category = map.get("category").toString();
                String supervisoryCode = createSupervisorCode("1", XIAN_YANG, null, category);
                SupervisoryCodeInfo supervisoryCodeInfo = new SupervisoryCodeInfo();
                supervisoryCodeInfo.setSupervisoryCode(supervisoryCode);
                supervisoryCodeInfo.setStatus(EquipmentCategoryEnum.YSY.getCode());
                if (category.startsWith("3")) {
                    if ("null".equals(map.get("code"))) {
                        // code96333 = createElevatorCode("31");
                        code96333 = generateCodeService.createElevatorCode("96333_31");
                        supervisoryCodeInfo.setCreateStatus(CREATE);
                    } else {
                        supervisoryCodeInfo.setCreateStatus(NOT_CREATE);
                        code96333 = map.get("code").toString();
                    }
                }
                supervisoryCodeInfo.setCode96333(code96333);
                // 更新至码表
                supervisoryCodeInfoMapper.insert(supervisoryCodeInfo);
                CategoryOtherInfo categoryOtherInfo = new CategoryOtherInfo();
                categoryOtherInfo.setCode(code96333);
                categoryOtherInfo.setSupervisoryCode(supervisoryCode);
                // 更新至业务表
                categoryOtherInfoMapper.updateSupervisorCode(supervisoryCode, code96333, map.get("record").toString());
                // 更新至一码通es
                checkEsData(map.get("record").toString());
                // 更新至电梯es
                saveEsElevator2ES(map.get("record").toString());
            }
        }
    }

    private String batchSubmitOrUpdate(Map<String, Object> map, LinkedHashMap registerForm, String alias, String isCopy, String type, String claimStatus) {
        Date date = new Date();
        String record = null;
        LinkedHashMap useInfoForm = (LinkedHashMap) map.get(use_info_form_id);
        IdxBizJgFactoryInfo idxBizJgFactoryInfo = null;
        IdxBizJgOtherInfo otherInfo = null;
        IdxBizJgTechParamsElevator techParamsElevator = null;
        IdxBizJgTechParamsVehicle techParamsVehicle = null;
        IdxBizJgTechParamsRopeway techParamsRopeway = null;
        IdxBizJgTechParamsRides techParamsRides = null;
        IdxBizJgTechParamsBoiler techParamsBoiler = null;
        IdxBizJgTechParamsVessel techParamsVessel = null;
        IdxBizJgTechParamsPipeline techParamsPipeline = null;
        IdxBizJgTechParamsLifting techParamsLifting = null;
        if ("save".equals(type)) {
            record = UUID.randomUUID().toString();
        } else {
            record = useInfoForm.get("id").toString();
            idxBizJgFactoryInfo = idxBizJgFactoryInfoMapper.selectOne(new QueryWrapper<IdxBizJgFactoryInfo>().eq("RECORD", record));
            otherInfo = idxBizJgOtherInfoMapper.selectOne(new QueryWrapper<IdxBizJgOtherInfo>().eq("RECORD", record));
            techParamsElevator = idxBizJgTechParamsElevatorMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsElevator>().eq("RECORD", record));
            techParamsVehicle = idxBizJgTechParamsVehicleMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsVehicle>().eq("RECORD", record));
            techParamsRopeway = idxBizJgTechParamsRopewayMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsRopeway>().eq("RECORD", record));
            techParamsRides = idxBizJgTechParamsRidesMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsRides>().eq("RECORD", record));
            techParamsBoiler = idxBizJgTechParamsBoilerMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsBoiler>().eq("RECORD", record));
            techParamsVessel = idxBizJgTechParamsVesselMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsVessel>().eq("RECORD", record));
            techParamsPipeline = idxBizJgTechParamsPipelineMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsPipeline>().eq("RECORD", record));
            techParamsLifting = idxBizJgTechParamsLiftingMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsLifting>().eq("RECORD", record));
        }
        // 使用信息
        IdxBizJgUseInfo useInfo = JSON.parseObject(JSON.toJSONString(useInfoForm), IdxBizJgUseInfo.class);
        useInfo.setRecord(record);
        useInfo.setRecDate(date);
        useInfo.setCreateDate("save".equals(type) ? new Date() : null);
        useInfo.setClaimDate((EquipmentCategoryEnum.YRL.getName().equals(claimStatus) || EquipmentCategoryEnum.YJL.getName().equals(claimStatus)) ? new Date() : null);
        if ("save".equals(type)) {
            useInfo.setDataSource(IS_COPY.equals(isCopy) ? useInfo.getSequenceNbr() : "0");
        }
        if (IS_COPY.equals(isCopy)) {
            useInfo.setSequenceNbr(null);
        }

        idxBizJgUseInfoService.saveOrUpdate(useInfo);

        // 监督管理信息
        LinkedHashMap supervisionForm = (LinkedHashMap) map.get(supervision_form_id);
        IdxBizJgSupervisionInfo supervisionInfo = JSON.parseObject(JSON.toJSONString(supervisionForm), IdxBizJgSupervisionInfo.class);
        supervisionInfo.setRecord(record);
        supervisionInfo.setRecDate(date);
        idxBizJgSupervisionInfoService.saveOrUpdate(supervisionInfo);

        IdxBizJgOtherInfo idxBizJgOtherInfo = JSON.parseObject(JSON.toJSONString(supervisionForm), IdxBizJgOtherInfo.class);
        if (!ObjectUtils.isEmpty(idxBizJgOtherInfo)) {
            if (EquipmentCategoryEnum.DRL.getName().equals(claimStatus) && "save".equals(type)) {
                idxBizJgOtherInfo.setClaimStatus("草稿");
            }
            idxBizJgOtherInfo.setRecord(record);
            idxBizJgOtherInfo.setRecDate(date);
            idxBizJgOtherInfo.setSequenceNbr("save".equals(type) ? null : otherInfo.getSequenceNbr());
            idxBizJgOtherInfoService.saveOrUpdate(idxBizJgOtherInfo);
        }

        // 设计制造信息
        LinkedHashMap designForm = (LinkedHashMap) map.get(design_from_id);
        IdxBizJgDesignInfo designInfo = JSON.parseObject(JSON.toJSONString(designForm), IdxBizJgDesignInfo.class);
        designInfo.setRecord(record);
        designInfo.setRecDate(date);
        designInfo.setSequenceNbr("save".equals(type) ? null : designInfo.getSequenceNbr());
        idxBizJgDesignInfoService.saveOrUpdate(designInfo);

        IdxBizJgFactoryInfo factoryInfo = JSON.parseObject(JSON.toJSONString(designForm), IdxBizJgFactoryInfo.class);
        if (!ObjectUtils.isEmpty(factoryInfo)) {
            factoryInfo.setRecord(record);
            factoryInfo.setRecDate(date);
            factoryInfo.setSequenceNbr("save".equals(type) ? null : idxBizJgFactoryInfo.getSequenceNbr());
            idxBizJgFactoryInfoService.saveOrUpdate(factoryInfo);
        }

        // 检验检测信息
        LinkedHashMap inspectionForm = (LinkedHashMap) map.get(inspection_form_id);
        List inspectionList = (ArrayList) inspectionForm.get("subForm_pbim1pfid8");
        List<IdxBizJgInspectionDetectionInfo> detectionInfoList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(inspectionList)) {
            for (Object obj : inspectionList) {
                IdxBizJgInspectionDetectionInfo inspectionDetectionInfo = JSON.parseObject(JSON.toJSONString(obj), IdxBizJgInspectionDetectionInfo.class);
                inspectionDetectionInfo.setRecord(record);
                inspectionDetectionInfo.setRecDate(date);
                inspectionDetectionInfo.setSequenceNbr("save".equals(type) ? null : inspectionDetectionInfo.getSequenceNbr());
                detectionInfoList.add(inspectionDetectionInfo);
            }
            idxBizJgInspectionDetectionInfoService.saveOrUpdateBatch(detectionInfoList);
        }

        // 施工信息
        LinkedHashMap constructionForm = (LinkedHashMap) map.get(construction_form_id);
        List constructionlist = (ArrayList) constructionForm.get("subForm_b2x2wmcy2s");
        if (!ObjectUtils.isEmpty(constructionlist)) {
            List<IdxBizJgConstructionInfo> constructionInfoList = new ArrayList<>();
            for (Object obj : constructionlist) {
                IdxBizJgConstructionInfo constructionInfo = JSON.parseObject(JSON.toJSONString(obj), IdxBizJgConstructionInfo.class);
                constructionInfo.setRecord(record);
                constructionInfo.setRecDate(date);
                constructionInfo.setSequenceNbr("save".equals(type) ? null : constructionInfo.getSequenceNbr());
                constructionInfoList.add(constructionInfo);
            }
            idxBizJgConstructionInfoService.saveOrUpdateBatch(constructionInfoList);
        }

        // 八大类技术参数实体填充
        List<IdxBizJgMainParts> mainPartsList = new ArrayList<>();
        List<IdxBizJgProtectionDevices> protectionDevicesList = new ArrayList<>();
        if (EquipmentTypeEnum.DT.getCode().equals(alias)) {
            // 维保备案信息
            LinkedHashMap maintenanceForm = (LinkedHashMap) map.get(maintenance_form_id);
            List subFormMaintenanceList = (ArrayList) maintenanceForm.get("subForm_6i16fox27e");
            if (!ObjectUtils.isEmpty(subFormMaintenanceList)) {
                List<IdxBizJgMaintenanceRecordInfo> maintenanceList = new ArrayList<>();
                for (Object obj : subFormMaintenanceList) {
                    IdxBizJgMaintenanceRecordInfo maintenanceRecordInfo = JSON.parseObject(JSON.toJSONString(obj), IdxBizJgMaintenanceRecordInfo.class);
                    maintenanceRecordInfo.setRecord(record);
                    maintenanceRecordInfo.setRecDate(date);
                    maintenanceRecordInfo.setSequenceNbr("save".equals(type) ? null : maintenanceRecordInfo.getSequenceNbr());
                    maintenanceList.add(maintenanceRecordInfo);
                }
                idxBizJgMaintenanceRecordInfoService.saveOrUpdateBatch(maintenanceList);
            }
            // 技术参数
            IdxBizJgTechParamsElevator elevator = JSON.parseObject(JSON.toJSONString(registerForm), IdxBizJgTechParamsElevator.class);
            if (!ObjectUtils.isEmpty(elevator)) {
                elevator.setRecord(record);
                elevator.setRecDate(date);
                elevator.setSequenceNbr("save".equals(type) ? null : techParamsElevator.getSequenceNbr());
                idxBizJgTechParamsElevatorService.saveOrUpdate(elevator);
            }
        } else if (EquipmentTypeEnum.GL.getCode().equals(alias)) {
            IdxBizJgTechParamsBoiler boiler = JSON.parseObject(JSON.toJSONString(registerForm), IdxBizJgTechParamsBoiler.class);
            if (!ObjectUtils.isEmpty(boiler)) {
                boiler.setRecord(record);
                boiler.setRecDate(date);
                boiler.setSequenceNbr("save".equals(type) ? null : techParamsBoiler.getSequenceNbr());
                idxBizJgTechParamsBoilerService.saveOrUpdate(boiler);
                List<String> subFormMainPartsList = new ArrayList<>();
                subFormMainPartsList.add("subForm_1hh88r4m69");
                mainPartsList = getAccessoryEntity(registerForm, subFormMainPartsList, main_parts, record, date, type);
            }
        } else if (EquipmentTypeEnum.YL_RQ.getCode().equals(alias)) {
            IdxBizJgTechParamsVessel vessel = JSON.parseObject(JSON.toJSONString(registerForm), IdxBizJgTechParamsVessel.class);
            if (!ObjectUtils.isEmpty(vessel)) {
                vessel.setRecord(record);
                vessel.setRecDate(date);
                vessel.setSequenceNbr("save".equals(type) ? null : techParamsVessel.getSequenceNbr());
                idxBizJgTechParamsVesselService.saveOrUpdate(vessel);
                List<String> subFormMainPartsList = new ArrayList<>();
                subFormMainPartsList.add("subForm_fie04854f2");
                mainPartsList = getAccessoryEntity(registerForm, subFormMainPartsList, main_parts, record, date, type);
                List<String> subFormProtectionDevicesList = new ArrayList<>();
                subFormProtectionDevicesList.add("subForm_d4xdzhsgdj");
                protectionDevicesList = getAccessoryEntity(registerForm, subFormProtectionDevicesList, protection_devices, record, date, type);
            }
        } else if (EquipmentTypeEnum.QZJ.getCode().equals(alias)) {
            IdxBizJgTechParamsLifting lifting = JSON.parseObject(JSON.toJSONString(registerForm), IdxBizJgTechParamsLifting.class);
            if (!ObjectUtils.isEmpty(lifting)) {
                lifting.setRecord(record);
                lifting.setRecDate(date);
                lifting.setSequenceNbr("save".equals(type) ? null : techParamsLifting.getSequenceNbr());
                idxBizJgTechParamsLiftingService.saveOrUpdate(lifting);
                List<String> subFormMainPartsList = new ArrayList<>();
                subFormMainPartsList.add("subForm_bqirdyvztt");
                mainPartsList = getAccessoryEntity(registerForm, subFormMainPartsList, main_parts, record, date, type);
                List<String> subFormProtectionDevicesList = new ArrayList<>();
                subFormProtectionDevicesList.add("subForm_29yy3pdzhl");
                subFormProtectionDevicesList.add("subForm_h5h4x0zhur");
                protectionDevicesList = getAccessoryEntity(registerForm, subFormProtectionDevicesList, protection_devices, record, date, type);
            }
        } else if (EquipmentTypeEnum.CS.getCode().equals(alias)) {
            IdxBizJgTechParamsVehicle vehicle = JSON.parseObject(JSON.toJSONString(registerForm), IdxBizJgTechParamsVehicle.class);
            if (!ObjectUtils.isEmpty(vehicle)) {
                vehicle.setRecord(record);
                vehicle.setRecDate(date);
                vehicle.setSequenceNbr("save".equals(type) ? null : techParamsVehicle.getSequenceNbr());
                idxBizJgTechParamsVehicleService.saveOrUpdate(vehicle);
                List<String> subFormMainPartsList = new ArrayList<>();
                subFormMainPartsList.add("subForm_sey164b51a");
                subFormMainPartsList.add("subForm_tef7yf5fbr");
                mainPartsList = getAccessoryEntity(registerForm, subFormMainPartsList, main_parts, record, date, type);
            }
        } else if (EquipmentTypeEnum.YL_SS.getCode().equals(alias)) {
            registerForm = (LinkedHashMap) map.get(ylss_register_from_id);
            IdxBizJgTechParamsRides rides = JSON.parseObject(JSON.toJSONString(registerForm), IdxBizJgTechParamsRides.class);
            if (!ObjectUtils.isEmpty(rides)) {
                rides.setRecord(record);
                rides.setRecDate(date);
                rides.setSequenceNbr("save".equals(type) ? null : techParamsRides.getSequenceNbr());
                idxBizJgTechParamsRidesService.saveOrUpdate(rides);
            }
        } else if (EquipmentTypeEnum.YL_GD.getCode().equals(alias)) {
            registerForm = (LinkedHashMap) map.get(ylgd_register_from_id);
            IdxBizJgTechParamsPipeline pipeline = JSON.parseObject(JSON.toJSONString(registerForm), IdxBizJgTechParamsPipeline.class);
            if (!ObjectUtils.isEmpty(pipeline)) {
                pipeline.setRecord(record);
                pipeline.setRecDate(date);
                pipeline.setSequenceNbr("save".equals(type) ? null : techParamsPipeline.getSequenceNbr());
                idxBizJgTechParamsPipelineService.saveOrUpdate(pipeline);
                List<String> subFormMainPartsList = new ArrayList<>();
                subFormMainPartsList.add("subForm_9n7nu55z8r");
                mainPartsList = getAccessoryEntity(registerForm, subFormMainPartsList, main_parts, record, date, type);
            }
        } else {
            IdxBizJgTechParamsRopeway ropeway = JSON.parseObject(JSON.toJSONString(registerForm), IdxBizJgTechParamsRopeway.class);
            if (!ObjectUtils.isEmpty(ropeway)) {
                ropeway.setRecord(record);
                ropeway.setRecDate(date);
                ropeway.setSequenceNbr("save".equals(type) ? null : techParamsRopeway.getSequenceNbr());
                idxBizJgTechParamsRopewayService.saveOrUpdate(ropeway);
                List<String> subFormMainPartsList = new ArrayList<>();
                subFormMainPartsList.add("subForm_5fi0jewuyh");
                mainPartsList = getAccessoryEntity(registerForm, subFormMainPartsList, main_parts, record, date, type);
            }
        }
        IdxBizJgRegisterInfo registerInfo = JSON.parseObject(JSON.toJSONString(registerForm), IdxBizJgRegisterInfo.class);
        if (!ObjectUtils.isEmpty(registerInfo)) {
            registerInfo.setRecord(record);
            registerInfo.setRecDate(date);
            registerInfo.setSequenceNbr("save".equals(type) ? null : registerForm.get("sequenceNbr").toString());
            idxBizJgRegisterInfoService.saveOrUpdate(registerInfo);
        }

        if (!ObjectUtils.isEmpty(mainPartsList)) {
            idxBizJgMainPartsService.saveOrUpdateBatch(mainPartsList);
        }
        if (!ObjectUtils.isEmpty(protectionDevicesList)) {
            idxBizJgProtectionDevicesService.saveOrUpdateBatch(protectionDevicesList);
        }
        return record;
    }

    private List getAccessoryEntity(Map<String, Object> map, List<String> list, String subFormType, String record, Date date, String type) {
        List<IdxBizJgMainParts> mainPartsList = new ArrayList<>();
        List<IdxBizJgProtectionDevices> protectionDevicesList = new ArrayList<>();

        if ("mainParts".equals(subFormType)) {
            for (Object s : list) {
                List subFormMainPartsList = (ArrayList) map.get(s);
                if (!ObjectUtils.isEmpty(subFormMainPartsList)) {
                    for (Object obj : subFormMainPartsList) {
                        IdxBizJgMainParts mainParts = JSON.parseObject(JSON.toJSONString(obj), IdxBizJgMainParts.class);
                        mainParts.setRecord(record);
                        mainParts.setRecDate(date);
                        mainParts.setSequenceNbr("save".equals(type) ? null : mainParts.getSequenceNbr());
                        mainPartsList.add(mainParts);
                    }
                }
            }
            return mainPartsList;
        } else {
            for (Object s : list) {
                List subFormProtectionDevicesList = (ArrayList) map.get(s);
                if (!ObjectUtils.isEmpty(subFormProtectionDevicesList)) {
                    for (Object obj : subFormProtectionDevicesList) {
                        IdxBizJgProtectionDevices protectionDevices = JSON.parseObject(JSON.toJSONString(obj), IdxBizJgProtectionDevices.class);
                        protectionDevices.setRecord(record);
                        protectionDevices.setRecDate(date);
                        protectionDevices.setSequenceNbr("save".equals(type) ? null : protectionDevices.getSequenceNbr());
                        protectionDevicesList.add(protectionDevices);
                    }
                }
            }
            return protectionDevicesList;
        }
    }


    private void saveEsElevator2ES(String record) {
        List<String> recordList = new ArrayList<>();
        recordList.add(record);
        EsElevator esElevator = superviseInfoMapper.selectElevatorEsList(record);
        if (!ObjectUtils.isEmpty(esElevator)) {
            Double lat = esElevator.getLatitude();
            Double lon = esElevator.getLongitude();
            esElevator.setLocation(new GeoPoint(lat, lon));
            esElavtorRepository.save(esElevator);
            superviseInfoMapper.updateRecordBatch(recordList);
        }
    }

    /**
     * 分页查询所有数据
     *
     * @param map
     * @return
     */
    public Page<Map<String, Object>> getAll(Map<String, Object> map) {
        String tableName = map.get(TABLENAME).toString();
        Assert.hasText(tableName, "表名不能为空");
        String selectSql = " SELECT * FROM  " + tableName + " WHERE IS_NOT_ES IS NULL ";
        Integer number = ValidationUtil.isEmpty(map.get("number")) ? 0 : Integer.valueOf(map.get("number").toString());
        Integer size = ValidationUtil.isEmpty(map.get("size")) ? 0 : Integer.valueOf(map.get("size").toString());
        Page<Map<String, Object>> page = new Page<>(number, size);
        int begin = (number - 1) * size;
        if (size > 0) {
            selectSql = selectSql + " LIMIT " + begin + "," + size;
        }
        List<Map<String, Object>> mapList = bizJdbcTemplate.queryForList(selectSql);
        page.setRecords(mapList);
        page.setTotal(mapList.size());
        return page;
    }

    // 查询总条数
    public Long counts(Map<String, Object> map) {
        String tableName = map.get(TABLENAME).toString();
        Assert.hasText(tableName, "表名不能为空");
        String countSql = " SELECT COUNT(SEQUENCE_NBR) count FROM  " + tableName + " WHERE IS_NOT_ES <> 1 or IS_NOT_ES IS NULL";
        Long count = bizJdbcTemplate.queryForObject(countSql, Long.class);
        return count;
    }

    /**
     * es数据同步
     *
     * @return
     */

    public void saveEs() {
        long start = System.currentTimeMillis();
        Map<String, Object> map = new HashMap<>();
        map.put(TABLENAME, "idx_biz_view_jg_all");
        Long counts = counts(map);
        Long times = counts / 1000;
        Long yushu = counts % 1000;
        if (yushu > 0) {
            times++;
        }
        long total = 0;
        for (int i = 1; i <= times; i++) {
            map.put("number", 1);
            map.put("size", 1000);
            Page<Map<String, Object>> page = getAll(map);
            total = total + page.getTotal();
            saveBatchEquipment2Es(page.getRecords());
        }
        long end = System.currentTimeMillis();
        log.info("本次一码通同步设备数据：【" + total + "】条，耗时：" + (end - start) + " 毫秒");
    }

    public void saveBatchEquipment2Es(List<Map<String, Object>> equipList) {
        List<ESEquipmentCategoryDto> esEquipDtoList = Lists.newArrayList();
        List<String> recordList = Lists.newArrayList();
        if (ValidationUtil.isEmpty(equipList)) {
            return;
        }
        for (Map<String, Object> e : equipList) {
            String recDate1 = "";
            if (ValidationUtil.isEmpty(e.get("REC_DATE"))) {
                try {
                    recDate1 = DateUtil.formatDate(new Date(), "yyyy-MM-dd hh:mm:ss");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } else {
                recDate1 = e.get("REC_DATE").toString().substring(0, 19);
            }
            long time = Timestamp.valueOf(recDate1).getTime();
            e.put("REC_DATE", time);
            ESEquipmentCategoryDto esEquipDto = JSONObject.parseObject(toJSONString(e),
                    ESEquipmentCategoryDto.class);
            esEquipDtoList.add(esEquipDto);

            recordList.add((String) e.get("SEQUENCE_NBR"));
        }
        long start = System.currentTimeMillis();
        esEquipmentCategory.saveAll(esEquipDtoList);
        long end = System.currentTimeMillis();
        long cost = end - start;
        System.out.println("批量存入es1000条数据耗时：" + cost);

        long start1 = System.currentTimeMillis();
        superviseInfoMapper.updateEsRecordBatch(recordList);
        long end1 = System.currentTimeMillis();
        long cost1 = end1 - start1;
        System.out.println("批量更新1000条业务数据耗时：" + cost1);
    }

    public Page<JSONObject> queryByKeys(JSONObject map) {
//        //根据当前登录人查询
        if (!ValidationUtil.isEmpty(map.get(EQUSTATE))) {
            map.put(EQUSTATE, EquipmentEnum.getCode.get(map.get(EQUSTATE).toString()).toString());
        }
        JSONObject object = getCompanyType().get(0);
        String level = object.getString("level");
        String code = object.getString("orgCode");
        String companyCode = object.getString("companyCode").contains("_") ?
                object.getString("companyCode").split("_")[1] : object.getString("companyCode");
        Page<JSONObject> result = new Page<>(map.getInteger("number"), map.getInteger("size"));
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        // 通用匹配规则，条件构建
        // 根据当前登录用户类型及管辖机构筛选条件添加对应参数
        if (!ValidationUtil.isEmpty(level)) {
            if (LEVEL.equals(level)) {
                // 企业
                map.put("USE_UNIT_CREDIT_CODE", companyCode);
                if (!ObjectUtils.isEmpty(map.getString("ORG_BRANCH_CODE"))) {
                    BoolQueryBuilder query = QueryBuilders.boolQuery();
                    String test = QueryParser.escape(map.getString("ORG_BRANCH_CODE"));
                    query.must(QueryBuilders.matchPhrasePrefixQuery("ORG_BRANCH_CODE", test));
                    boolMust.must(query);
                }
            } else {
                if (!ObjectUtils.isEmpty(map.getString("ORG_BRANCH_CODE"))) {
                    String paramCode = map.getString("ORG_BRANCH_CODE");
                    if (paramCode.contains(code)) {
                        BoolQueryBuilder query = QueryBuilders.boolQuery();
                        String test = QueryParser.escape(map.getString("ORG_BRANCH_CODE"));
                        query.must(QueryBuilders.matchPhrasePrefixQuery("ORG_BRANCH_CODE", test));
                        boolMust.must(query);
                    } else {
                        return result;
                    }
                } else {
                    // 监管单位
                    map.put("ORG_BRANCH_CODE", code);
                }
            }
        }
        // SEQUENCE_NBR
        if (!ObjectUtils.isEmpty(map.getString("SEQUENCE_NBR"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("SEQUENCE_NBR"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("SEQUENCE_NBR", "*" + test + "*"));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("ORG_BRANCH_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("ORG_BRANCH_CODE"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("ORG_BRANCH_CODE", "*" + test + "*"));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_NAME"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_UNIT_NAME"));
            query.must(QueryBuilders.matchPhraseQuery("USE_UNIT_NAME", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_CREDIT_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_UNIT_CREDIT_CODE"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("USE_UNIT_CREDIT_CODE", test));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_LIST_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_LIST_CODE"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_LIST_CODE", test));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_LIST"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_LIST"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_LIST", "*" + test + "*"));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_CATEGORY"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_CATEGORY"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_CATEGORY", "*" + test + "*"));
            boolMust.must(meBuilder);

        }
        if (!ObjectUtils.isEmpty(map.getString("USE_ORG_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_ORG_CODE"));
            meBuilder.must(QueryBuilders.wildcardQuery("USE_ORG_CODE", "*" + test + "*"));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("CODE96333"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("CODE96333"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("CODE96333", "*" + test + "*"));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_CODE"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_CODE", "*" + test + "*"));
            boolMust.must(meBuilder);
        }

        if (!ObjectUtils.isEmpty(map.getString("SUPERVISORY_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("SUPERVISORY_CODE"));
            meBuilder.must(QueryBuilders.wildcardQuery("SUPERVISORY_CODE", "*" + test + "*"));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("USE_PLACE"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_PLACE"));
            query.must(QueryBuilders.matchPhraseQuery("USE_PLACE", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("ADDRESS"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("ADDRESS"));
            query.must(QueryBuilders.matchPhraseQuery("ADDRESS", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_STATE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getLong("EQU_STATE").toString());
            meBuilder.must(QueryBuilders.matchQuery("EQU_STATE", test));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("STATUS"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("STATUS"));
            if (test.contains("非")) {
                boolMust.mustNot(QueryBuilders.matchPhraseQuery("STATUS", "草稿"));
                boolMust.must(QueryBuilders.existsQuery("STATUS"));
            } else {
                meBuilder.must(QueryBuilders.matchPhraseQuery("STATUS", test));
                boolMust.must(meBuilder);
            }
        }
        if (!ObjectUtils.isEmpty(map.getString("CLAIM_STATUS"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("CLAIM_STATUS"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("STATUS", test));
            boolMust.must(meBuilder);
        }
        builder.query(boolMust);

        builder.sort("REC_DATE", Optional.ofNullable(map.getString("sort"))
                .map(s -> s.split(","))
                .filter(sortParams -> "ascend".equals(sortParams[1]))
                .map(s -> SortOrder.ASC)
                .orElse(SortOrder.DESC));

        builder.from((map.getInteger("number") - 1) * map.getInteger("size"));
        builder.size(map.getInteger("size"));
        request.source(builder);
        List<JSONObject> list = new LinkedList<>();
        long totle = 0;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (org.elasticsearch.search.SearchHit hit : response.getHits().getHits()) {
                System.out.println(hit);
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hit);
                JSONObject dto2 = jsonObject.getJSONObject("sourceAsMap");
                if (!ValidationUtil.isEmpty(dto2.get(EQUSTATE))) {
                    Integer integer = Integer.valueOf(dto2.get(EQUSTATE).toString());
                    String status = EquipmentEnum.getName.get(integer);
                    dto2.put(EQUSTATE, status);
                }
                dto2.put(REC_DATE, dateFormat.format(dto2.get(REC_DATE)));
                list.add(dto2);
            }
            totle = response.getInternalResponse().hits().getTotalHits().value;
            result.setRecords(list);
            result.setTotal(totle);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    // es统计总记录数
    public Long getCount(String indexs, RestHighLevelClient esClient) {
        Long totle = 0L;
        SearchRequest searchRequest = new SearchRequest(indexs);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchSourceBuilder.trackTotalHits(true);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
            totle = searchResponse.getInternalResponse().hits().getTotalHits().value;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return totle;
    }

    @Transactional
    public Boolean saveSupervisoryData(EquipmentMessageDto data) {
        if (ObjectUtils.isEmpty(data) || ObjectUtils.isEmpty(data.getSupervisoryCode())) {
            return false;
        }
        Date date = new Date();
        String supervisoryCode = data.getSupervisoryCode();
        Integer saveStatus = data.getSaveStatus();
        Integer alias = 0;
        // 使用信息
        if (!ObjectUtils.isEmpty(data.getUseInfo())) {
            IdxBizJgUseInfo useInfo = data.getUseInfo();
            useInfo.setRecDate(date);
            if (saveStatus == 1) {
                useInfo.setRecord(supervisoryCode);
                useInfo.setClaimDate(date);
                useInfo.setCreateDate(date);
                useInfo.setDataSource("1");
                idxBizJgUseInfoService.save(useInfo);

            } else {
                LambdaQueryWrapper<IdxBizJgUseInfo> lambda = new QueryWrapper<IdxBizJgUseInfo>().lambda();
                lambda.eq(IdxBizJgUseInfo::getRecord, supervisoryCode);
                idxBizJgUseInfoService.update(data.getUseInfo(), lambda);
            }
        }
        // 设计信息
        if (!ObjectUtils.isEmpty(data.getDesignInfo())) {
            IdxBizJgDesignInfo designInfo = data.getDesignInfo();
            designInfo.setRecDate(date);
            if (saveStatus == 1) {
                designInfo.setRecord(supervisoryCode);
                idxBizJgDesignInfoService.save(designInfo);
            } else {
                LambdaQueryWrapper<IdxBizJgDesignInfo> lambda = new QueryWrapper<IdxBizJgDesignInfo>().lambda();
                lambda.eq(IdxBizJgDesignInfo::getRecord, supervisoryCode);
                idxBizJgDesignInfoService.update(designInfo, lambda);
            }
        }
        // 制造信息
        if (!ObjectUtils.isEmpty(data.getFactoryInfo())) {
            IdxBizJgFactoryInfo factoryInfo = data.getFactoryInfo();
            factoryInfo.setRecDate(date);
            if (saveStatus == 1) {
                factoryInfo.setRecord(supervisoryCode);
                idxBizJgFactoryInfoService.save(factoryInfo);
            } else {
                LambdaQueryWrapper<IdxBizJgFactoryInfo> lambda = new QueryWrapper<IdxBizJgFactoryInfo>().lambda();
                lambda.eq(IdxBizJgFactoryInfo::getRecord, supervisoryCode);
                idxBizJgFactoryInfoService.update(factoryInfo, lambda);
            }
        }
        // 注册登记
        if (!ObjectUtils.isEmpty(data.getRegisterInfo())) {
            IdxBizJgRegisterInfo registerInfo = data.getRegisterInfo();
            registerInfo.setRecDate(date);
            if (saveStatus == 1) {
                registerInfo.setRecord(supervisoryCode);
                alias = Integer.parseInt(String.valueOf(ValidationUtil.isEmpty(registerInfo.getEquList()) ? 3000 :
                        registerInfo.getEquList()));
                registerInfo.setEquList("3000");
                idxBizJgRegisterInfoService.save(registerInfo);
            } else {
                LambdaQueryWrapper<IdxBizJgRegisterInfo> lambda = new QueryWrapper<IdxBizJgRegisterInfo>().lambda();
                lambda.eq(IdxBizJgRegisterInfo::getRecord, supervisoryCode);
                idxBizJgRegisterInfoService.update(registerInfo, lambda);
            }
        }
        // 维保信息
        if (!ObjectUtils.isEmpty(data.getMaintenanceRecordInfo())) {
            IdxBizJgMaintenanceRecordInfo maintenanceRecordInfo = data.getMaintenanceRecordInfo();
            maintenanceRecordInfo.setRecDate(date);
            if (saveStatus == 1) {
                maintenanceRecordInfo.setRecord(supervisoryCode);
                idxBizJgMaintenanceRecordInfoService.save(maintenanceRecordInfo);
            } else {
                LambdaQueryWrapper<IdxBizJgMaintenanceRecordInfo> lambda = new QueryWrapper<IdxBizJgMaintenanceRecordInfo>().lambda();
                lambda.eq(IdxBizJgMaintenanceRecordInfo::getRecord, supervisoryCode);
                idxBizJgMaintenanceRecordInfoService.update(maintenanceRecordInfo, lambda);
            }
        }
        // 其他信息
        if (!ObjectUtils.isEmpty(data.getOtherInfo())) {
            IdxBizJgOtherInfo otherInfo = data.getOtherInfo();
            otherInfo.setRecDate(date);
            if (saveStatus == 1) {
                otherInfo.setRecord(supervisoryCode);
                otherInfo.setClaimStatus("已认领");
                otherInfo.setAlias(alias);
                idxBizJgOtherInfoService.save(otherInfo);
            } else {
                LambdaQueryWrapper<IdxBizJgOtherInfo> lambda = new QueryWrapper<IdxBizJgOtherInfo>().lambda();
                lambda.eq(IdxBizJgOtherInfo::getRecord, supervisoryCode);
                idxBizJgOtherInfoService.update(otherInfo, lambda);
            }
        }
        // 监管信息
        if (!ObjectUtils.isEmpty(data.getSupervisionInfo())) {
            IdxBizJgSupervisionInfo supervisionInfo = data.getSupervisionInfo();
            supervisionInfo.setRecDate(date);
            if (saveStatus == 1) {
                supervisionInfo.setRecord(supervisoryCode);
                idxBizJgSupervisionInfoService.save(supervisionInfo);
            } else {
                LambdaQueryWrapper<IdxBizJgSupervisionInfo> lambda = new QueryWrapper<IdxBizJgSupervisionInfo>().lambda();
                lambda.eq(IdxBizJgSupervisionInfo::getRecord, supervisoryCode);
                idxBizJgSupervisionInfoService.update(supervisionInfo, lambda);
            }
        }
        // 参数信息
        if (!ObjectUtils.isEmpty(data.getParams())) {
            Map<String, Object> params = data.getParams();
            IdxBizJgTechParamsElevator idxBizJgTechParamsElevator = new IdxBizJgTechParamsElevator();
            BeanUtil.copyProperties(params, idxBizJgTechParamsElevator);
            idxBizJgTechParamsElevator.setRecDate(date);
            if (saveStatus == 1) {
                idxBizJgTechParamsElevator.setRecord(supervisoryCode);
                idxBizJgTechParamsElevatorService.save(idxBizJgTechParamsElevator);
            } else {
                LambdaQueryWrapper<IdxBizJgTechParamsElevator> lambda = new QueryWrapper<IdxBizJgTechParamsElevator>().lambda();
                lambda.eq(IdxBizJgTechParamsElevator::getRecord, supervisoryCode);
                idxBizJgTechParamsElevatorService.update(idxBizJgTechParamsElevator, lambda);
            }
        }
        // 同步es
        checkEsData(supervisoryCode);
        // 修改码表状态
        updateStatus(supervisoryCode);
        return true;
    }

    public void updateStatus(String supervisoryCode) {
        SupervisoryCodeInfo info = new SupervisoryCodeInfo();
        info.setStatus("1");
        LambdaQueryWrapper<SupervisoryCodeInfo> lambda = new QueryWrapper<SupervisoryCodeInfo>().lambda();
        lambda.eq(SupervisoryCodeInfo::getSupervisoryCode, supervisoryCode);
        supervisoryCodeInfoMapper.update(info, lambda);
    }

    @Transactional
    public Boolean saveConstructionInfoData(IdxBizJgConstructionInfo data) {
        if (!ObjectUtils.isEmpty(data) && !ObjectUtils.isEmpty(data.getSupervisoryCode())) {
            String supervisoryCode = data.getSupervisoryCode();
            data.setRecDate(new Date());
            if (!ObjectUtils.isEmpty(data.getSequenceNbr())) {
                idxBizJgConstructionInfoService.updateById(data);
            } else {
                data.setRecord(supervisoryCode);
                idxBizJgConstructionInfoService.save(data);
            }
        } else {
            return false;
        }
        return true;
    }

    @Transactional
    public Boolean saveMaintenanceRecordInfoData(IdxBizJgMaintenanceRecordInfo data) {
        if (!ObjectUtils.isEmpty(data) && !ObjectUtils.isEmpty(data.getSupervisoryCode())) {
            String supervisoryCode = data.getSupervisoryCode();
            data.setRecDate(new Date());
            if (!ObjectUtils.isEmpty(data.getSequenceNbr())) {
                idxBizJgMaintenanceRecordInfoService.updateById(data);
            } else {
                data.setRecord(supervisoryCode);
                idxBizJgMaintenanceRecordInfoService.save(data);
            }
        } else {
            return false;
        }
        return true;
    }

    @Transactional
    public Boolean saveDetectionInfoData(IdxBizJgInspectionDetectionInfo data) {
        if (!ObjectUtils.isEmpty(data) && !ObjectUtils.isEmpty(data.getSupervisoryCode())) {
            String supervisoryCode = data.getSupervisoryCode();
            data.setRecDate(new Date());
            if (!ObjectUtils.isEmpty(data.getSequenceNbr())) {
                idxBizJgInspectionDetectionInfoService.updateById(data);
            } else {
                data.setRecord(supervisoryCode);
                idxBizJgInspectionDetectionInfoService.save(data);
            }
        } else {
            return false;
        }
        return true;
    }

    public Boolean deleteByRecord(String record) {
        if (!ObjectUtils.isEmpty(record)) {
            // 使用信息删除
            LambdaQueryWrapper<IdxBizJgUseInfo> lambda = new QueryWrapper<IdxBizJgUseInfo>().lambda();
            lambda.eq(IdxBizJgUseInfo::getRecord, record);
            idxBizJgUseInfoService.getBaseMapper().delete(lambda);
            // 设计信息删除
            LambdaQueryWrapper<IdxBizJgDesignInfo> lambdaDes = new QueryWrapper<IdxBizJgDesignInfo>().lambda();
            lambdaDes.eq(IdxBizJgDesignInfo::getRecord, record);
            idxBizJgDesignInfoService.getBaseMapper().delete(lambdaDes);
            // 制造信息删除
            LambdaQueryWrapper<IdxBizJgFactoryInfo> lambdaFac = new QueryWrapper<IdxBizJgFactoryInfo>().lambda();
            lambdaFac.eq(IdxBizJgFactoryInfo::getRecord, record);
            idxBizJgFactoryInfoService.getBaseMapper().delete(lambdaFac);
            // 施工信息删除
            LambdaQueryWrapper<IdxBizJgConstructionInfo> lambdaCon = new QueryWrapper<IdxBizJgConstructionInfo>().lambda();
            lambdaCon.eq(IdxBizJgConstructionInfo::getRecord, record);
            idxBizJgConstructionInfoService.getBaseMapper().delete(lambdaCon);
            // 注册信息删除
            LambdaQueryWrapper<IdxBizJgRegisterInfo> lambdaReg = new QueryWrapper<IdxBizJgRegisterInfo>().lambda();
            lambdaReg.eq(IdxBizJgRegisterInfo::getRecord, record);
            idxBizJgRegisterInfoService.getBaseMapper().delete(lambdaReg);
            // 维保信息删除
            LambdaQueryWrapper<IdxBizJgMaintenanceRecordInfo> lambdaMain = new QueryWrapper<IdxBizJgMaintenanceRecordInfo>().lambda();
            lambdaMain.eq(IdxBizJgMaintenanceRecordInfo::getRecord, record);
            idxBizJgMaintenanceRecordInfoService.getBaseMapper().delete(lambdaMain);
            // 监督信息删除
            LambdaQueryWrapper<IdxBizJgSupervisionInfo> lambdaSup = new QueryWrapper<IdxBizJgSupervisionInfo>().lambda();
            lambdaSup.eq(IdxBizJgSupervisionInfo::getRecord, record);
            idxBizJgSupervisionInfoService.getBaseMapper().delete(lambdaSup);
            // 其他信息删除
            LambdaQueryWrapper<IdxBizJgOtherInfo> lambdaOth = new QueryWrapper<IdxBizJgOtherInfo>().lambda();
            lambdaOth.eq(IdxBizJgOtherInfo::getRecord, record);
            idxBizJgOtherInfoService.getBaseMapper().delete(lambdaOth);
            // 检验检测信息删除
            LambdaQueryWrapper<IdxBizJgInspectionDetectionInfo> lambdaIns = new QueryWrapper<IdxBizJgInspectionDetectionInfo>().lambda();
            lambdaIns.eq(IdxBizJgInspectionDetectionInfo::getRecord, record);
            idxBizJgInspectionDetectionInfoService.getBaseMapper().delete(lambdaIns);
            // 参数删除
            LambdaQueryWrapper<IdxBizJgTechParamsElevator> lambdaPar = new QueryWrapper<IdxBizJgTechParamsElevator>().lambda();
            lambdaPar.eq(IdxBizJgTechParamsElevator::getRecord, record);
            idxBizJgTechParamsElevatorService.getBaseMapper().delete(lambdaPar);
        } else {
            return false;
        }
        return true;
    }

    /**
     * 更新ES中的数据（公共方法）
     *
     * @param paramMap 更新的参数
     */
//    @Override
//    public Map<String, Object> commonUpdateEsDataByIds(Map<String, Map<String, Object>> paramMap) {
//        if (paramMap.isEmpty()) {
//            return null;
//        }
//        String oldUscUnitCreditCode = "";
//        String oldUscUnitName = "";
//        Map<String, Object> resultMap = new HashMap<>();
//        for (Map.Entry<String, Map<String, Object>> entry : paramMap.entrySet()) {
//            String record = entry.getKey();
//            Map<String, Object> childMap = entry.getValue();
//            if (!childMap.isEmpty()) {
//                ESEquipmentCategoryDto oldData = null;
//                // 获取Es中旧的数据
//                Optional<ESEquipmentCategoryDto> optional = esEquipmentCategory.findById(record);
//                if (!ObjectUtils.isEmpty(optional)) {
//                    oldData = optional.get();
//                    oldUscUnitCreditCode = oldData.getUSC_UNIT_CREDIT_CODE();
//                    oldUscUnitName = oldData.getUSC_UNIT_NAME();
//                }
//                // 获取Es中新的参数
//                ESEquipmentCategoryDto newData = JSON.parseObject(toJSONString(childMap), ESEquipmentCategoryDto.class);
//                String newUscUnitCreditCode = newData.getUSC_UNIT_CREDIT_CODE();
//                String newUscUnitName = newData.getUSC_UNIT_NAME();
//
//                // 删除Es中旧的数据
//                if (!ObjectUtils.isEmpty(oldData)) {
//                    esEquipmentCategory.deleteById(record);
//                    // 整合新旧数据
//                    Bean.copyExistPropertis(newData, oldData);
//                    // 处理施工单位信息[去重]
//                    if (!ValidationUtil.isEmpty(newUscUnitCreditCode)) {
//                        // if (!ValidationUtil.isEmpty(oldUscUnitCreditCode)) {
//                        //     if (!oldUscUnitCreditCode.contains(newUscUnitCreditCode)) {
//                        //         oldData.setUSC_UNIT_CREDIT_CODE(oldUscUnitCreditCode + "," + newUscUnitCreditCode);
//                        //         oldData.setUSC_UNIT_NAME(oldUscUnitName + "," + newUscUnitName);
//                        //     }
//                        // } else {
//                            oldData.setUSC_UNIT_CREDIT_CODE(newUscUnitCreditCode);
//                            oldData.setUSC_UNIT_NAME(newUscUnitName);
//                        // }
//                    }
//
//                }
//                if (!ObjectUtils.isEmpty(oldData)) {
//                    oldData.setREC_DATE(System.currentTimeMillis());
//                    ESEquipmentCategoryDto saveData = esEquipmentCategory.save(oldData);
//
//                    // 组装返回数据
//                    resultMap.put(record, saveData);
//                }
//            }
//
//        }
//        return resultMap;
//    }
    @Override
    public Map<String, Object> commonUpdateEsDataByIds(Map<String, Map<String, Object>> paramMap) {
        if (paramMap.isEmpty()) {
            return null;
        }

        Map<String, ESEquipmentCategoryDto> oldDataMap = new HashMap<>();
        List<ESEquipmentCategoryDto> saveList = new ArrayList<>();

        // 批量获取旧数据
//        for (String record : paramMap.keySet()) {
//            Optional<ESEquipmentCategoryDto> optional = esEquipmentCategory.findById(record);
//            optional.ifPresent(dto -> oldDataMap.put(record, dto));
//        }
        Iterable<ESEquipmentCategoryDto> optiona = esEquipmentCategory.findAllById(paramMap.keySet());
        optiona.forEach(dto -> oldDataMap.put(dto.getSEQUENCE_NBR(), dto));

        for (Map.Entry<String, Map<String, Object>> entry : paramMap.entrySet()) {
            String record = entry.getKey();
            Map<String, Object> childMap = entry.getValue();
            if (!childMap.isEmpty()) {
                ESEquipmentCategoryDto oldData = oldDataMap.get(record);
                ESEquipmentCategoryDto newData = JSON.parseObject(JSON.toJSONString(childMap), ESEquipmentCategoryDto.class);

                if (oldData != null) {
                    Bean.copyExistPropertis(newData, oldData);

                    // 处理施工单位信息[去重]
                    String newUscUnitCreditCode = newData.getUSC_UNIT_CREDIT_CODE();
                    String newUscUnitName = newData.getUSC_UNIT_NAME();

                    if (!ValidationUtil.isEmpty(newUscUnitCreditCode)) {
                        oldData.setUSC_UNIT_CREDIT_CODE(newUscUnitCreditCode);
                        oldData.setUSC_UNIT_NAME(newUscUnitName);
                    }

                    oldData.setREC_DATE(System.currentTimeMillis());
                    saveList.add(oldData);
                }
            }
        }

        // 批量删除旧数据
        esEquipmentCategory.deleteAll(oldDataMap.values());

        // 批量保存新数据
        Iterable<ESEquipmentCategoryDto> savedData = esEquipmentCategory.saveAll(saveList);

        // 组装返回数据
        Map<String, Object> resultMap = new HashMap<>();
        savedData.forEach(dto -> resultMap.put(dto.getSEQUENCE_NBR(), dto));

        return resultMap;
    }

    /**
     * 批量更新电梯的96333码
     * 1，先于【码表 biz_jg_supervisory_code】中进行匹配，有的话使用码表的写入other_info数据库
     * 2，码表没有直接生成后写入
     *
     * @return 异常的需要手动处理的数据集合
     */
    @Override
    public JSONObject batchHandlerCode96333() {
        log.info("开始处理96333的异常数据。。。");
        // 程序无法处理的，需要手动处理的数据，需要返回
        AtomicReference<Integer> handlerDataNums = new AtomicReference<>(0);
        StringBuilder handlerData = new StringBuilder();
        List<JSONObject> manualProcessData = new ArrayList<>();
        List<Map<String, String>> exceptionData = equipmentCategoryMapper.selectExceptionCode96333();

        exceptionData.forEach(data -> {
            JSONObject jsonObj = JSONObject.parseObject(toJSONString(data));
            String city = jsonObj.getString("city");
            String county = jsonObj.getString("county");
            String isNotXixian = jsonObj.getString("isNotXixian");
            // 监管码
            String supervisoryCode = jsonObj.getString("supervisoryCode");
            if (StringUtils.isEmpty(city) || "null".equals(city) || StringUtils.isEmpty(supervisoryCode)) {
                manualProcessData.add(jsonObj);
                return;
            }
            // record
            String record = jsonObj.getString("record");
            String code96333 = "";
            String createStatus = "";

            // 1. 先查码表，有则使用码表中的code96333更新
            SupervisoryCodeInfo supervisoryCodeInfo = equipmentCategoryMapper.searchSupervisoryBySupervisoryCode(supervisoryCode);
            if (supervisoryCodeInfo != null && !ObjectUtils.isEmpty(supervisoryCodeInfo.getCode96333())) {
                code96333 = supervisoryCodeInfo.getCode96333();
                createStatus = NOT_CREATE;
            } else {
                // 2. 生成code96333
                String prefix = "";
                try {
                    prefix = this.cityCodeTo96333CodePrefix(city, county, isNotXixian);
                } catch (Exception exception) {
                    log.error("cityCode转化地区初始码失败：{}", city);
                    log.error(exception.getMessage());
                    return;
                }
                code96333 = this.createElevatorCode(prefix);
                createStatus = CREATE;
            }
            log.info("正在处理数据：{},96333码为：{}，是否为新生成的96333：{}", record, code96333, "1".equals(createStatus) ? "是" : "否");
            handlerDataNums.getAndSet(handlerDataNums.get() + 1);
            handlerData.append(supervisoryCode).append(",");
            // 更新数据库other_info 更新/新增码表
            this.saveCode96333ForDataBase(supervisoryCode, createStatus, code96333, supervisoryCodeInfo);
            // 更新es，索引：idx_biz_view_jg_all，idx_biz_equipment_info
            this.saveCode96333ForEs(record, code96333);
        });

        return new JSONObject()
                .fluentPut("总共异常数据：", exceptionData.size() + "条")
                .fluentPut("程序处理数据条数：", handlerDataNums + "条")
                .fluentPut("程序处理数据：", handlerData)
                .fluentPut("异常数据，需手动处理：", JSONObject.toJSONString(manualProcessData));
    }

    @Override
    public String handleError96333Code() {
        List<Map<String, String>> exceptionData = equipmentCategoryMapper.selectError96333Code();
        exceptionData.stream()
                .map(data -> data.get("supervisoryCode"))
                .filter(Objects::nonNull)
                .forEach(supervisoryCode -> {
                    String elevatorCode = createElevatorCode("31");
                    handleErrorElevatorCode(supervisoryCode, elevatorCode);
                });
        return String.format("修复96333码成功，共处理 %d 条", exceptionData.size());
    }


    private void saveCode96333ForEs(String record, String code96333) {
        // idx_biz_view_jg_all
        Optional<ESEquipmentCategoryDto> esEquipmentCategoryDto = esEquipmentCategory.findById(record);
        esEquipmentCategoryDto.ifPresent(data -> {
            data.setCODE96333(code96333);
            esEquipmentCategory.save(data);
        });
        // idx_biz_equipment_info
        Optional<ESEquipmentInfo> equipmentDaoById = esEquipmentDao.findById(record);
        equipmentDaoById.ifPresent(data -> {
            data.setCODE96333(code96333);
            esEquipmentDao.save(data);
        });
    }

    private void saveCode96333ForDataBase(String supervisoryCode, String createStatus, String code96333, SupervisoryCodeInfo supervisoryCodeInfo) {
        if (supervisoryCodeInfo != null && !ObjectUtils.isEmpty(supervisoryCodeInfo.getSequenceNbr())) {
            // 更新码表
            supervisoryCodeInfoMapper.update(new SupervisoryCodeInfo().setCode96333(code96333),
                    new LambdaQueryWrapper<SupervisoryCodeInfo>()
                            .eq(SupervisoryCodeInfo::getSupervisoryCode, supervisoryCode));
        } else {
            // 新增码表
            supervisoryCodeInfoMapper.insert(new SupervisoryCodeInfo()
                    .setCode96333(code96333)
                    .setSupervisoryCode(supervisoryCode)
                    .setStatus(EquipmentCategoryEnum.YSY.getCode())
                    .setCreateStatus(createStatus)
            );
        }
        // otherInfo 表
        IdxBizJgOtherInfo otherInfo = idxBizJgOtherInfoMapper.selectOne(
                new LambdaQueryWrapper<IdxBizJgOtherInfo>()
                        .eq(IdxBizJgOtherInfo::getSupervisoryCode, supervisoryCode)
        );
        if (otherInfo != null) {
            otherInfo.setCode96333(code96333);
            idxBizJgOtherInfoService.update(otherInfo,
                    new LambdaQueryWrapper<IdxBizJgOtherInfo>().eq(IdxBizJgOtherInfo::getSupervisoryCode, supervisoryCode)
            );
        }
    }

    // 对应关系转化
    // city/county --> EquipmentCategoryEnum.value
    private String cityCodeTo96333CodePrefix(String city, String county, String isNotXixian) {
        String prefixCode = "";
        prefixCode = EquipmentCategoryEnum.getCityCodeValue.get(city);
        // 西咸
        if (XIAN.equals(city) && "0".equals(isNotXixian)) {
            prefixCode = EquipmentCategoryEnum.XXCSM.getValue();
        }
        // 杨陵
        if (YANG_LING.equals(county)) {
            prefixCode = EquipmentCategoryEnum.YLCSM.getValue();
        }
        // 韩城
        if (HAN_CHENG.equals(county)) {
            prefixCode = EquipmentCategoryEnum.HCCSM.getValue();
        }
        // 神木
        if (SHEN_MU.equals(county)) {
            prefixCode = EquipmentCategoryEnum.SMCSM.getValue();
        }
        // 府谷
        if (FU_GU.equals(county)) {
            prefixCode = EquipmentCategoryEnum.FGCSM.getValue();
        }
        if (StringUtils.isEmpty(prefixCode)) {
            throw new RuntimeException("未匹配到对应的cityCode/countyCode：" + city + "/" + county);
        }
        return prefixCode;
    }

}