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

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
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.core.toolkit.Sequence;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dao.ESEquipmentCategory;
import com.yeejoin.amos.boot.module.common.api.dto.ESEquipmentCategoryDto;
import com.yeejoin.amos.boot.module.jg.api.dto.CodeGenerateDto;
import com.yeejoin.amos.boot.module.jg.api.dto.EquipInfoCylinderExcelDto;
import com.yeejoin.amos.boot.module.jg.api.dto.EquipmentInfoDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgCertificateChangeRecord;
import com.yeejoin.amos.boot.module.jg.api.entity.JgCertificateChangeRecordEq;
import com.yeejoin.amos.boot.module.jg.api.entity.JgUseRegistrationManage;
import com.yeejoin.amos.boot.module.jg.api.entity.SafetyProblemTracing;
import com.yeejoin.amos.boot.module.jg.api.enums.*;
import com.yeejoin.amos.boot.module.jg.api.mapper.CommonMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgUseRegistrationMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgVehicleInformationMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.SafetyProblemTracingMapper;
import com.yeejoin.amos.boot.module.jg.biz.config.PressureVesselListener;
import com.yeejoin.amos.boot.module.jg.biz.context.EquipUsedCheckStrategyContext;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.jg.biz.service.*;
import com.yeejoin.amos.boot.module.jg.biz.utils.CodeUtil;
import com.yeejoin.amos.boot.module.ymt.api.dto.IdxBizJgRegisterInfoDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.*;
import com.yeejoin.amos.boot.module.ymt.api.enums.ApplicationFormTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquimentEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.CategoryOtherInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.IdxBizJgRegisterInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.RegistrationInfoMapper;
import com.yeejoin.amos.boot.module.ymt.api.mapper.SuperviseInfoMapper;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
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.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
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.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.fastjson.JSON.toJSONString;
import static com.yeejoin.amos.boot.module.jg.api.enums.CylinderTypeEnum.SPECIAL_CYLINDER;
import static com.yeejoin.amos.boot.module.jg.api.enums.VehicleApanageEnum.XIAN_YANG;
import static com.yeejoin.amos.boot.module.jg.api.enums.VehicleApanageEnum.XI_XIAN;


/**
 * 注册登记信息表服务实现类
 *
 * @author system_generator
 * @date 2023-08-17
 */
@Service
@Slf4j
public class IdxBizJgRegisterInfoServiceImpl extends BaseService<IdxBizJgRegisterInfoDto, IdxBizJgRegisterInfo, IdxBizJgRegisterInfoMapper> implements IIdxBizJgRegisterInfoService {
    public final static String USE_TYPE_NAME = "使用单位";
    public final static String INDIVIDUAL_TYPE_NAME = "个人主体";
    public final static String MAINTENANCE_TYPE_NAME = "安装改造维修单位";
    // 设备分类表单id
    private static final String EQUIP_CLASS_FORM_ID = "equipClass";
    // 设备基本信息表单id
    private static final String EQUIP_INFO_FORM_ID = "equipInfo";
    // 设备技术参数表单id
    private static final String EQUIP_PARAMS_FORM_ID = "equipParams";
    // 主要零部件
    private static final String EQUIP_MAINPARTS_FORM_ID = "mainParts";
    // 安全附件
    private static final String EQUIP_PROTECTIONDEVICES_FORM_ID = "protectionDevices";
    private static final String EQUSTATE = "EQU_STATE";
    private static final String CONSTRUCTIONTYPE = "CONSTRUCTION_TYPE";
    // 新增修改标识
    private static final String OPERATESAVE = "save";
    private static final String OPERATEEDIT = "edit";
    // 单位办理类型
    private static final String MANAGE_TYPE_UNIT = "unit";
    private static final String RECORD = "RECORD";
    private static final String MANAGE_TYPE = "manageType";
    // 设备代码
    private static final String EQU_CODE = "EQU_CODE";
    private static final String SEQUENCE_NBR = "SEQUENCE_NBR";
    private static final String FACTORY_NUM = "FACTORY_NUM";
    // 新增设备是否复制而来
    private static final String IS_COPY = "isCopy";
    // 设备种类
    public static final String EQU_LIST = "EQU_LIST";
    // 模版上传集合
    public static final String EQU_LISTS = "equLists";
    // 设备类别
    public static final String EQU_CATEGORY = "EQU_CATEGORY";
    // 设备品种
    public static final String EQU_DEFINE = "EQU_DEFINE";
    // 是否车用气瓶
    public static final String WHETHER_VEHICLE_CYLINDER = "WHETHER_VEHICLE_CYLINDER";
    // 是否撬装式压力容器
    public static final String WHETHER_SKID_MOUNTED_PRESSURE_VESSEL = "WHETHER_SKID_MOUNTED_PRESSURE_VESSEL";
    // 检验检测机构
    public static final String INSPECTION_AND_TESTING_INSTITUTIONS = "检验检测机构";
    // 设备纳管  纳管：true 未纳管：false
    public static final String IS_INTO_MANAGEMENT = "IS_INTO_MANAGEMENT";

    // 设备来源 jg：新设备录入  jg_his：历史数据录入
    public static final String DATA_SOURCE = "DATA_SOURCE";
    // 设备来源名称 jg：新设备  jg_his：历史数据
    public static final String DATA_SOURCE_NAME = "DATA_SOURCE_NAME";
    private static final String ATTACHMENT_UPLOAD = "attachmentUpload";
    public static final String USE_PLACE_CODE = "USE_PLACE_CODE";

    private final List<String> resultError = new ArrayList<>();
    List<String> useInnerCodeList = new ArrayList<>();// 单位内部编号集合
    List<String> equCodeList = new ArrayList<>();// 设备代码集合
    List<String> factoryNumList = new ArrayList<>();// 出厂编码集合

    /**
     * 业务类型 0：单个新增 1:批量导入
     */
    public static final String BUSINESS_SCENARIOS = "businessScenarios";
    // 需要转化成jsonObject的附件字段
    public static String[] jsonFields = {"insOtherAccessories", "installContractAttachment", "installProxyStatementAttachment"};
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    RegistrationInfoMapper tzsJgRegistrationInfoMapper;
    @Autowired
    IIdxBizJgUseInfoService idxBizJgUseInfoService;
    @Autowired
    IIdxBizJgDesignInfoService iIdxBizJgDesignInfoService;
    @Autowired
    IIdxBizJgFactoryInfoService iIdxBizJgFactoryInfoService;
    @Autowired
    IIdxBizJgConstructionInfoService iIdxBizJgConstructionInfoService;
    @Autowired
    IIdxBizJgMaintenanceRecordInfoService iIdxBizJgMaintenanceRecordInfoService;
    @Autowired
    IIdxBizJgSupervisionInfoService iIdxBizJgSupervisionInfoService;
    @Autowired
    IIdxBizJgOtherInfoService iIdxBizJgOtherInfoService;
    @Autowired
    IIdxBizJgInspectionDetectionInfoService iIdxBizJgInspectionDetectionInfoService;
    @Autowired
    IIdxBizJgTechParamsElevatorService iIdxBizJgTechParamsElevatorService;
    @Autowired
    IIdxBizJgTechParamsVehicleService iIdxBizJgTechParamsVehicleService;
    @Autowired
    IIdxBizJgTechParamsRopewayService iIdxBizJgTechParamsRopewayService;
    @Autowired
    IIdxBizJgTechParamsRidesService iIdxBizJgTechParamsRidesService;
    @Autowired
    IIdxBizJgTechParamsBoilerService iIdxBizJgTechParamsBoilerService;
    @Autowired
    IIdxBizJgTechParamsVesselService iIdxBizJgTechParamsVesselService;
    @Autowired
    IIdxBizJgTechParamsPipelineService iIdxBizJgTechParamsPipelineService;
    @Autowired
    IIdxBizJgTechParamsLiftingService iIdxBizJgTechParamsLiftingService;
    @Autowired
    IIdxBizJgMainPartsService iIdxBizJgMainPartsService;
    @Autowired
    IIdxBizJgProtectionDevicesService iIdxBizJgProtectionDevicesService;
    @Autowired
    ESEquipmentCategory esEquipmentCategory;
    @Autowired
    ICommonService commonService;
    @Autowired
    CommonMapper commonMapper;
    @Autowired
    DataDictionaryServiceImpl iDataDictionaryService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private CategoryOtherInfoMapper categoryOtherInfoMapper;
    @Autowired
    private SuperviseInfoMapper superviseInfoMapper;
    @Autowired
    private JgUseRegistrationMapper jgUseRegistrationMapper;
    @Autowired
    private JgInstallationNoticeServiceImpl jgInstallationNoticeService;
    @Value("${add.equip.dict.code.suffix:CATEGORY_LIST_ADD}")
    private String equipAddDictCodeSuffix;
    @Autowired
    private IdxBizJgDesignInfoServiceImpl idxBizJgDesignInfoService;
    @Autowired
    private IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;
    @Autowired
    private IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoService;
    @Autowired
    private IdxBizJgTechParamsVesselServiceImpl idxBizJgTechParamsVesselService;
    @Autowired
    private IdxBizJgInspectionDetectionInfoServiceImpl idxBizJgInspectionDetectionInfoService;
    @Autowired
    private IIdxBizJgOtherInfoService idxBizJgOtherInfoService;
    @Autowired
    private CodeUtil codeUtil;
    @Autowired
    private TzsServiceFeignClient tzsServiceFeignClient;
    @Autowired
    private JgUseRegistrationManageServiceImpl jgUseRegistrationManageService;
    @Autowired
    private JgVehicleInformationMapper jgVehicleInformationMapper;
    @Autowired
    private JgCertificateChangeRecordServiceImpl certificateChangeRecordService;
    @Autowired
    private Sequence sequence;
    @Autowired
    private JgCertificateChangeRecordEqServiceImpl certificateChangeRecordEqService;

    /**
     * 将对象的属性由驼峰转为纯大写下划线格式
     *
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> convertCamelToUnderscore(Object object, String[] strToJsonArrayFields) {
        Map<String, Object> result = new HashMap<>();
        Class<?> clazz = object.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            String underscoreFieldName = StringUtils.camelToUnderline(fieldName).toUpperCase();
            Object value;
            try {
                value = field.get(object);
                // 需要转为jsonArray的字段
                if (!ValidationUtil.isEmpty(strToJsonArrayFields) && Arrays.asList(strToJsonArrayFields).contains(underscoreFieldName)) {
                    value = JSON.parseArray((String) field.get(object));
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            if (!ValidationUtil.isEmpty(value)) {
                result.put(underscoreFieldName.toUpperCase(), value);
            }
        }
        return result;
    }

    /**
     * 设备注册信息
     *
     * @param paramMap
     * @return
     */
    @Transactional
    public ResponseModel equipmentRegisterSubmit(Map<String, Object> paramMap) {
        if (paramMap == null) {
            throw new IllegalArgumentException("参数Map不能为空");
        }
        String record = null;
        LinkedHashMap equipmentClassForm = (LinkedHashMap) checkAndCast(paramMap.get(EQUIP_CLASS_FORM_ID));
        LinkedHashMap equipmentInfoForm = (LinkedHashMap) checkAndCast(paramMap.get(EQUIP_INFO_FORM_ID));
        LinkedHashMap equipmentParamsForm = (LinkedHashMap) checkAndCast(paramMap.get(EQUIP_PARAMS_FORM_ID));

        try {
            // 设备代码 字段的唯一性校验
            checkEquCodeUniqueness(equipmentInfoForm);
            // 车用气瓶业务里面的 产品编号 校验唯一性（产品编号在车用气瓶范围内全局唯一）
            checkFactoryNumUniqueness(equipmentInfoForm);
        } catch (Exception e) {
            handleError(e, null);
        }

        // 使用登记按照单位办理除外，其余进行编辑校验
        Object manageType = equipmentInfoForm.get(MANAGE_TYPE);
        boolean isManageType = (!ObjectUtils.isEmpty(manageType) && MANAGE_TYPE_UNIT.equals(manageType));
        if (!isManageType) {
            // 编辑校验
            this.checkForEquipEdit(equipmentInfoForm.get(RECORD));
        }
        // 操作类型
        try {
            // 保存数据
            record = batchSubmitOrUpdate(equipmentClassForm, equipmentInfoForm, equipmentParamsForm);
            // 保存Es数据
            if (!ObjectUtils.isEmpty(record)) {
                checkEsData(record);
            }
        } catch (Exception e) {
            log.error("操作失败，数据异常: " + e.getMessage(), e);

            handleError(e, record);
        }
        return ResponseHelper.buildResponse(record);
    }

    private Object checkAndCast(Object obj) {
        if (obj instanceof LinkedHashMap) {
            return obj;
        } else {
            throw new ClassCastException("对象类型不匹配");
        }
    }

    private void checkEquCodeUniqueness(LinkedHashMap equipmentInfoForm) {
        // 根据设备代码检查唯一性
        LambdaQueryWrapper<RegistrationInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RegistrationInfo::getEquCode, equipmentInfoForm.get(EQU_CODE));
        wrapper.ne(!ObjectUtils.isEmpty(equipmentInfoForm.get(SEQUENCE_NBR)), RegistrationInfo::getSequenceNbr, equipmentInfoForm.get(SEQUENCE_NBR));
        Integer count = tzsJgRegistrationInfoMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BadRequest("设备代码已存在，请重新输入！");
        }
    }

    private void checkFactoryNumUniqueness(LinkedHashMap equipmentInfoForm) {
        // 车用气瓶业务里面的 出厂编号/产品编码 校验唯一性（产品编号在车用气瓶范围内全局唯一）
        Integer factoryNum = commonMapper.checkFactoryNumUniquenessForVehicleCylinder((String) equipmentInfoForm.get(FACTORY_NUM), (String) equipmentInfoForm.get(RECORD));
        if (factoryNum > 0) {
            throw new BadRequest("出厂编号/产品编码 已存在，请重新输入！");
        }
    }

    private void handleError(Exception e, String record) {
        log.error("处理异常: " + e.getMessage(), e);
        // 删除数据库数据和ES数据
        if (!ObjectUtils.isEmpty(record)) {
            List<String> records = new ArrayList<>();
            records.add(record);
            superviseInfoMapper.deleteDataAll(records);
            esEquipmentCategory.deleteById(record);
        }
        throw new BadRequest(e.getMessage());
    }

    private void checkForEquipEdit(Object record) {
        // 标识编辑
        if (record != null) {
            Integer inUseTime = commonService.countEquipInUseTimesForEdit(record.toString());
            if (inUseTime > 0) {
                throw new BadRequest("此设备在被其他业务引用，不可编辑！");
            }
        }
    }

    private Boolean checkEquipIsCanEdit(String record) {
        Integer inUseTime = commonService.countEquipInUseTimesForEdit(record);
        return inUseTime <= 0;
    }

    /**
     * 删除设备注册信息（批量删除）
     *
     * @param map
     * @return
     */
    @Override
    public boolean batchDeleteByRecord(Map<String, Object> map) {
        Object recordList = map.get("recordList");
        List<String> records = new ArrayList<>();
        List<ESEquipmentCategoryDto> list = new ArrayList<>();
        // 删除ES数据
        if (recordList.toString().contains("[")) {
            for (String record : (List<String>) recordList) {
                records.add(record);
                ESEquipmentCategoryDto esEquipmentCategoryDto = new ESEquipmentCategoryDto();
                esEquipmentCategoryDto.setSEQUENCE_NBR(record);
                list.add(esEquipmentCategoryDto);
            }
        } else {
            records.add(recordList.toString());
            ESEquipmentCategoryDto esEquipmentCategoryDto = new ESEquipmentCategoryDto();
            esEquipmentCategoryDto.setSEQUENCE_NBR(recordList.toString());
            list.add(esEquipmentCategoryDto);
        }
        // 删除校验，被引用时不可删除
        this.checkForDelete(records);

        // 删除涉及的19张表的数据
        superviseInfoMapper.deleteDataAll(records);
        // 删除es中的数据
        esEquipmentCategory.deleteAll(list);
        return true;
    }

    private void checkForDelete(List<String> records) {
        for (String record : records) {
            Integer useTime = commonService.countEquipInUseTimesForDel(record);
            if (useTime > 0) {
                String msg = getTipMsgString(record);
                throw new BadRequest(msg);
            }
        }

    }

    private Boolean checkEquipIsCanDelete(String record) {
        Integer useTime = commonService.countEquipInUseTimesForDel(record);
        return useTime <= 0;
    }

    private String getTipMsgString(String record) {
        IdxBizJgRegisterInfo registerInfo = this.getOne(new QueryWrapper<IdxBizJgRegisterInfo>().eq("RECORD", record));
        return String.format("存在被引用的设备,设备代码:%s", registerInfo.getEquCode());
    }

    /**
     * 查询设备注册信息详情
     *
     * @param record
     * @return
     */
    public Map<String, Map<String, Object>> getEquipmentRegisterByRecord(String record, String isCopy) {
        Map<String, Map<String, Object>> resultMap = new HashMap<>();
        // 设备种类
        Map<String, Object> equIpClassMap = this.getEquIpClassMap(record, "");
        // 设备注册信息
        Map<String, Object> equipInfoMap = this.getEquipInfoMap(record, "");
        if (!ValidationUtil.isEmpty(equIpClassMap)) {
            resultMap.put(EQUIP_CLASS_FORM_ID, equIpClassMap);
        }
        if (!ValidationUtil.isEmpty(equipInfoMap)) {
            resultMap.put(EQUIP_INFO_FORM_ID, equipInfoMap);
        }
        // 设备参数
        if (equIpClassMap.containsKey(EQU_LIST) && !ValidationUtil.isEmpty(equIpClassMap.get(EQU_LIST).toString())) {
            Map<String, Object> equipParamsMap = this.getEquipParamsMap(record, "", equIpClassMap.get(EQU_LIST).toString());

            if (!ValidationUtil.isEmpty(equipParamsMap)) {
                // 给技术参数中添加设备种类，标记技术参数属于那个设备
                equipParamsMap.put(EQU_LIST, String.valueOf(equIpClassMap.get(EQU_LIST)));
                equipParamsMap.put(EQU_CATEGORY, String.valueOf(equIpClassMap.get(EQU_CATEGORY)));
                equipParamsMap.put(EQU_DEFINE, String.valueOf(equIpClassMap.get(EQU_DEFINE)));
                resultMap.put(EQUIP_PARAMS_FORM_ID, equipParamsMap);
            }
        }

        // 处理复制设备信息
        if ("1".equals(isCopy)) {
            equipInfoMap.put("EQU_CODE_TYPE", "1");
            equipInfoMap.put("SUPERVISORY_CODE", null);
            equipInfoMap.put("CAR_NUMBER", null);
            equIpClassMap.put("CAR_NUMBER", null);
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getDetailByRecord(String record) {
        Map<String, Object> resultMap = new HashMap<>();
        // 设备种类
        Map<String, Object> equIpClassMap = this.getEquIpClassMap(record, "");
        // 设备注册信息
        Map<String, Object> equipInfoMap = this.getEquipInfoMap(record, "");
        if (!ValidationUtil.isEmpty(equIpClassMap)) {
            resultMap.putAll(equIpClassMap);
        }
        if (!ValidationUtil.isEmpty(equipInfoMap)) {
            resultMap.putAll(equipInfoMap);
        }
        // 设备参数
        if (equIpClassMap.containsKey(EQU_LIST) && !ValidationUtil.isEmpty(equIpClassMap.get(EQU_LIST).toString())) {
            Map<String, Object> equipParamsMap = this.getEquipParamsMap(record, "", equIpClassMap.get(EQU_LIST).toString());

            if (!ValidationUtil.isEmpty(equipParamsMap)) {
                resultMap.putAll(equipParamsMap);
            }
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> getDetailFieldCamelCaseByRecord(String record) {
        Map<String, Object> resultMap = new HashMap<>();
        // 设备种类
        Map<String, Object> equIpClassMap = this.getEquIpClassMap(record, "CamelCase");
        // 设备注册信息
        Map<String, Object> equipInfoMap = this.getEquipInfoMap(record, "CamelCase");
        SuperviseInfo superviseInfo = superviseInfoMapper.selectOne(new LambdaQueryWrapper<SuperviseInfo>().eq(AbstractEquipBaseEntity::getRecord, record));
        if (!ValidationUtil.isEmpty(equIpClassMap)) {
            resultMap.putAll(equIpClassMap);
        }
        if (!ValidationUtil.isEmpty(equipInfoMap)) {
            resultMap.putAll(equipInfoMap);
        }
        // 设备参数
        if (equIpClassMap.containsKey("equList") && !ValidationUtil.isEmpty(equIpClassMap.get("equList").toString())) {
            Map<String, Object> equipParamsMap = this.getEquipParamsMap(record, "CamelCase", equIpClassMap.get("equList").toString());
            if (!ValidationUtil.isEmpty(equipParamsMap)) {
                resultMap.putAll(equipParamsMap);
            }
        }
        if (!ValidationUtil.isEmpty(superviseInfo)) {
            resultMap.put("orgBranchCode", superviseInfo.getOrgBranchCode());
            resultMap.put("orgBranchName", superviseInfo.getOrgBranchName());
        }
        resultMap.remove("instanceId");
        for (String field : jsonFields) {
            if (resultMap.get(field) != null && resultMap.get(field) instanceof String) {
                resultMap.put(field, JSON.parse(resultMap.get(field).toString()));
            }
        }
        return resultMap;
    }

    @Override
    public List<DictionarieValueModel> equCategoryListByCompanyType(ReginParams selectedOrgInfo, String equList, String businessScenarios, String dataSource, String type) {
        // 历史设备录入 直接取所有的设备种类（equList）下的所有设备类别
        if ("his".equals(dataSource)) {
            // 历史数据导入设备类别限制  bug-21172
            if (!ObjectUtils.isEmpty(type) && "PL_DR".equals(type)) {
                return this.baseMapper.queryAllEquCategoriesUnderTheEquList(equList).stream()
                        .filter(x -> "2300".equals(x.getDictDataKey()))
                        .collect(Collectors.toList());
            }
            // 历史数据新增设备类别限制 bug-21139
            if (!ObjectUtils.isEmpty(equList) && "8000".equals(equList)) {
                return this.baseMapper.queryAllEquCategoriesUnderTheEquList(equList).stream()
                        .filter(x -> "8300".equals(x.getDictDataKey()))
                        .collect(Collectors.toList());
            }
            return this.baseMapper.queryAllEquCategoriesUnderTheEquList(equList);
        }

        String companyType = selectedOrgInfo.getCompany().getCompanyType();
        String dictCodePrefix = getDictCodePrefix(companyType, equList);
        if (StringUtils.isEmpty(dictCodePrefix)) {
            return new ArrayList<>();
        }
        String dictCode = String.format("%s_%s", dictCodePrefix, equipAddDictCodeSuffix);
        List<DictionarieValueModel> result = FeignUtil.remoteCall(() -> Systemctl.dictionarieClient.dictValues(dictCode));
        if (CompanyTypeEnum.CONSTRUCTION.getName().equals(companyType) || ValidationUtil.isEmpty(businessScenarios)) {
            return result;
        }
        // 初始化collect列表
        List<DictionarieValueModel> collect = new ArrayList<>();
        // 使用单位 包含 企业的使用单位类型 or 个人主体
        // 使用单位 && 业务场景businessScenarios为1（场景选择）&& 设备种类为2000（压力容器） =》 设备类别只保留固定式压力容器（2100）
        // 使用单位 && 业务场景businessScenarios为0（场景选择）&& 设备种类为2000（压力容器） =》 设备类别排除固定式压力容器（2100）
        boolean shouldInclude2100 = (CompanyTypeEnum.USE.getName().equals(companyType) || CompanyTypeEnum.INDIVIDUAL.getName().equals(companyType)) && "1".equals(businessScenarios) && "2000".equals(equList);
        collect = result.stream()
                .filter(x -> shouldInclude2100 == "2100".equals(x.getDictDataKey()))
                .collect(Collectors.toList());

        return collect;
    }

    private String getDictCodePrefix(String companyType, String equList) {
        String dictCodePrefix = "";
        if ((companyType.contains(USE_TYPE_NAME) || companyType.contains(INDIVIDUAL_TYPE_NAME)) && !companyType.contains(MAINTENANCE_TYPE_NAME)) { // 使用单位
            dictCodePrefix = "USE";
        }
        if (companyType.contains(MAINTENANCE_TYPE_NAME) && !companyType.contains(USE_TYPE_NAME)) { // 安改维单位
            dictCodePrefix = "MAINTENANCE";
        }
        if (companyType.contains(MAINTENANCE_TYPE_NAME) && companyType.contains(USE_TYPE_NAME)) { // 所有单位
            dictCodePrefix = "ALL";
        }
        return StringUtils.isNotEmpty(equList) ? equList + "_" + dictCodePrefix : dictCodePrefix;
    }

    /**
     * 查询设备种类信息
     *
     * @param record    设备Id
     * @param fieldType 返回字段类型【CamelCase:驼峰命名，“”：纯大写加下划线】
     * @return
     */
    private Map<String, Object> getEquIpClassMap(String record, String fieldType) {
        Map<String, Object> objMap = new HashMap<>();
        // 注册登记
        IdxBizJgRegisterInfo registerInfo = this.getOne(new QueryWrapper<IdxBizJgRegisterInfo>().eq("RECORD", record));
        if (!ValidationUtil.isEmpty(registerInfo)) {
            String equList = registerInfo.getEquList();// 设备种类
            String equCategory = registerInfo.getEquCategory();// 设备类别
            String equDefine = registerInfo.getEquDefine();// 设备品种
            List<EquipmentCategory> categoryList0 = commonService.getEquipmentCategoryList(equList, null);
            List<EquipmentCategory> categoryList1 = commonService.getEquipmentCategoryList(equCategory, null);
            List<EquipmentCategory> categoryList2 = commonService.getEquipmentCategoryList(equDefine, null);
            Map<String, Object> registerInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                registerInfoMap = Bean.BeantoMap(registerInfo);
                registerInfoMap.put("registerinfoSeq", registerInfo.getSequenceNbr());
                registerInfoMap.put("sequenceNbr", registerInfo.getSequenceNbr());
                registerInfoMap.put("productPhoto", JSON.parseArray(registerInfo.getProductPhoto()));
                registerInfoMap.put("useRegistrationCode", registerInfo.getUseOrgCode());
                if (CollectionUtils.isNotEmpty(categoryList0)) {
                    registerInfoMap.put("equListDesc", categoryList0.get(0).getName());
                }
                if (CollectionUtils.isNotEmpty(categoryList1)) {
                    registerInfoMap.put("equCategoryDesc", categoryList1.get(0).getName());
                }
                if (CollectionUtils.isNotEmpty(categoryList2)) {
                    registerInfoMap.put("equDefineDesc", categoryList2.get(0).getName());
                }
            } else {
                String[] fields = {"PRODUCT_PHOTO"};
                registerInfoMap = convertCamelToUnderscore(registerInfo, fields);
                registerInfoMap.put("REGISTERINFO_SEQ", registerInfo.getSequenceNbr());
                registerInfoMap.put(SEQUENCE_NBR, registerInfo.getSequenceNbr());
                if (CollectionUtils.isNotEmpty(categoryList1)) {
                    registerInfoMap.put("EQU_CATEGORY_DESC", categoryList1.get(0).getName());
                }
                if (CollectionUtils.isNotEmpty(categoryList2)) {
                    registerInfoMap.put("EQU_DEFINE_DESC", categoryList2.get(0).getName());
                }
            }
            if (!registerInfoMap.isEmpty()) {
                Map<String, Object> filterMap = registerInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        return objMap;
    }

    @Autowired
    private SafetyProblemTracingMapper safetyProblemTracingMapper;

    /**
     * 查询设备基本信息
     *
     * @param record    设备Id
     * @param fieldType 返回字段类型【CamelCase:驼峰命名，“”：纯大写加下划线】
     * @return
     */
    private Map<String, Object> getEquipInfoMap(String record, String fieldType) {
        Map<String, Object> objMap = new HashMap<>();
        String province = "";
        String city = "";
        String county = "";
        String street = "";
        String fullAddress = "";

        // 设备问题信息（大屏二级页面使用）
        LambdaQueryWrapper<SafetyProblemTracing> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SafetyProblemTracing::getSourceId, record);
        lambdaQueryWrapper.orderByDesc(SafetyProblemTracing::getRecDate);
        List<SafetyProblemTracing> safetyProblemTracings = safetyProblemTracingMapper.selectList(lambdaQueryWrapper);
        if (!ObjectUtils.isEmpty(safetyProblemTracings)) {
            objMap.put("problemStatus", ProblemStatusEnum.getNameByDesc.get(safetyProblemTracings.get(0).getProblemStatus()));
            objMap.put("problemTime", safetyProblemTracings.get(0).getProblemTime());
        }

        // 使用信息
        IdxBizJgUseInfo useInfo = idxBizJgUseInfoService.getOneData(record);
        if (!ValidationUtil.isEmpty(useInfo)) {

            if (!ValidationUtil.isEmpty(useInfo.getProvince()) && !ValidationUtil.isEmpty(useInfo.getProvinceName())) {
                province = useInfo.getProvince() + "_" + useInfo.getProvinceName();
                fullAddress += useInfo.getProvinceName();
            }
            if (!ValidationUtil.isEmpty(useInfo.getCity()) && !ValidationUtil.isEmpty(useInfo.getCityName())) {
                city = useInfo.getCity() + "_" + useInfo.getCityName();
                fullAddress += useInfo.getCityName();
            }
            if (!ValidationUtil.isEmpty(useInfo.getCounty()) && !ValidationUtil.isEmpty(useInfo.getCountyName())) {
                county = useInfo.getCounty() + "_" + useInfo.getCountyName();
                fullAddress += useInfo.getCountyName();
            }
            if (!ValidationUtil.isEmpty(useInfo.getFactoryUseSiteStreet()) && !ValidationUtil.isEmpty(useInfo.getStreetName())) {
                street = useInfo.getFactoryUseSiteStreet() + "_" + useInfo.getStreetName();
                fullAddress += useInfo.getStreetName();
            }
            if (!ValidationUtil.isEmpty(useInfo.getAddress())) {
                fullAddress += useInfo.getAddress();
            }

            Map<String, Object> useInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                useInfoMap = Bean.BeantoMap(useInfo);
                if (!ValidationUtil.isEmpty(province)) {
                    useInfoMap.put("province", province);
                }
                if (!ValidationUtil.isEmpty(city)) {
                    useInfoMap.put("city", city);
                }
                if (!ValidationUtil.isEmpty(county)) {
                    useInfoMap.put("county", county);
                }
                if (!ValidationUtil.isEmpty(street)) {
                    useInfoMap.put("street", street);
                }
                if (!ValidationUtil.isEmpty(fullAddress)) {
                    useInfoMap.put("fullAddress", fullAddress);
                }
                useInfoMap.put("useinfoSeq", useInfo.getSequenceNbr());
                if (!ValidationUtil.isEmpty(useInfo.getLongitudeLatitude())) {
                    useInfoMap.put("longitudeLatitude", JSON.parseObject(useInfo.getLongitudeLatitude()));
                    useInfoMap.put("useLongitudeLatitude", JSON.parseObject(useInfo.getLongitudeLatitude()));
                }
                if (!ValidationUtil.isEmpty(useInfo.getAddress())) {
                    useInfoMap.put("useAddress", useInfo.getAddress());
                }

            } else {
                useInfoMap = convertCamelToUnderscore(useInfo, null);
                if (!ValidationUtil.isEmpty(province)) {
                    useInfoMap.put("PROVINCE", province);
                }
                if (!ValidationUtil.isEmpty(city)) {
                    useInfoMap.put("CITY", city);
                }
                if (!ValidationUtil.isEmpty(county)) {
                    useInfoMap.put("COUNTY", county);
                }
                if (!ValidationUtil.isEmpty(street)) {
                    useInfoMap.put("STREET", street);
                }
                if (!ValidationUtil.isEmpty(fullAddress)) {
                    useInfoMap.put("FULLADDRESS", fullAddress);
                }
                useInfoMap.put("USEINFO_SEQ", useInfo.getSequenceNbr());
                useInfoMap.put("USE_PLACE", useInfo.getUsePlace());
                if (!ValidationUtil.isEmpty(useInfo.getLongitudeLatitude())) {
                    useInfoMap.put("LONGITUDE_LATITUDE", JSON.parseObject(useInfo.getLongitudeLatitude()));
                    useInfoMap.put("USE_LONGITUDE_LATITUDE", JSON.parseObject(useInfo.getLongitudeLatitude()));
                }
                if (!ValidationUtil.isEmpty(useInfo.getAddress())) {
                    useInfoMap.put("USE_ADDRESS", useInfo.getAddress());
                    useInfoMap.put("FULL_ADDRESS", useInfo.getAddress());
                }
            }
            if (!useInfoMap.isEmpty()) {
                Map<String, Object> filterMap = useInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        // 设计制造
        IdxBizJgDesignInfo designInfo = iIdxBizJgDesignInfoService.getOneData(record);
        if (!ValidationUtil.isEmpty(designInfo)) {
            Map<String, Object> designInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                designInfoMap = Bean.BeantoMap(designInfo);
                designInfoMap.put("designinfoSeq", designInfo.getSequenceNbr());
                designInfoMap.put("designDoc", JSON.parseArray(designInfo.getDesignDoc()));
                designInfoMap.put("designStandard", JSON.parseArray(designInfo.getDesignStandard()));
                if (!ObjectUtils.isEmpty(designInfoMap.get("otherAccessoriesDes"))) {
                    designInfoMap.put("otherAccessoriesDes", JSON.parse(String.valueOf(designInfoMap.get("otherAccessoriesDes"))));
                }
            } else {
                String[] fields = {"DESIGN_DOC", "DESIGN_STANDARD", "OTHER_ACCESSORIES_DES"};
                designInfoMap = convertCamelToUnderscore(designInfo, fields);
                designInfoMap.put("DESIGNINFO_SEQ", designInfo.getSequenceNbr());
            }
            if (!designInfoMap.isEmpty()) {
                Map<String, Object> filterMap = designInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        // 制造信息
        IdxBizJgFactoryInfo factoryInfo = iIdxBizJgFactoryInfoService.getOneData(record);
        if (!ValidationUtil.isEmpty(factoryInfo)) {
            Map<String, Object> factoryInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                factoryInfoMap = Bean.BeantoMap(factoryInfo);
                String imported = factoryInfo.getImported();
                if ("0".equals(imported)) {
                    factoryInfoMap.put("importedDesc", "否");
                } else if ("1".equals(imported)) {
                    factoryInfoMap.put("importedDesc", "是");
                }
                factoryInfoMap.put("factoryinfoSeq", factoryInfo.getSequenceNbr());
                factoryInfoMap.put("factoryStandard", JSON.parseArray(factoryInfo.getFactoryStandard()));
                factoryInfoMap.put("productQualityYieldProve", JSON.parseArray(factoryInfo.getProductQualityYieldProve()));
                factoryInfoMap.put("insUseMaintainExplain", JSON.parseArray(factoryInfo.getInsUseMaintainExplain()));
                factoryInfoMap.put("factSupervisionInspectionReport", JSON.parseArray(factoryInfo.getFactSupervisionInspectionReport()));
                factoryInfoMap.put("boilerEnergyEfficiencyCertificate", JSON.parseArray(factoryInfo.getBoilerEnergyEfficiencyCertificate()));
                if (!ObjectUtils.isEmpty(factoryInfoMap.get("otherAccessoriesFact"))) {
                    factoryInfoMap.put("otherAccessoriesFact", JSON.parse(String.valueOf(factoryInfoMap.get("otherAccessoriesFact"))));
                }
            } else {
                String[] fields = {"FACTORY_STANDARD", "PRODUCT_QUALITY_YIELD_PROVE", "INS_USE_MAINTAIN_EXPLAIN",
                        "OTHER_ACCESSORIES_FACT", "FACT_SUPERVISION_INSPECTION_REPORT", "BOILER_ENERGY_EFFICIENCY_CERTIFICATE"};
                factoryInfoMap = convertCamelToUnderscore(factoryInfo, fields);
                String imported = factoryInfo.getImported();
                if ("0".equals(imported)) {
                    factoryInfoMap.put("IMPORTED_DESC", "否");
                } else if ("1".equals(imported)) {
                    factoryInfoMap.put("IMPORTED_DESC", "是");
                }
                factoryInfoMap.put("FACTORYINFO_SEQ", factoryInfo.getSequenceNbr());
            }
            if (!factoryInfoMap.isEmpty()) {
                Map<String, Object> filterMap = factoryInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        // 施工信息 【一对多，暂时只取最新一条数据】
        IdxBizJgConstructionInfo constructionInfo = iIdxBizJgConstructionInfoService.queryNewestDetailByRecord(record);
        if (!ValidationUtil.isEmpty(constructionInfo)) {
            Map<String, Object> constructionInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                constructionInfoMap = Bean.BeantoMap(constructionInfo);
                constructionInfoMap.put("constructioninfoSeq", constructionInfo.getSequenceNbr());
            } else {
                constructionInfoMap = convertCamelToUnderscore(constructionInfo, null);
                constructionInfoMap.put("CONSTRUCTIONINFO_SEQ", constructionInfo.getSequenceNbr());
            }
            if (!constructionInfoMap.isEmpty()) {
                Map<String, Object> filterMap = constructionInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        // 注册登记
        IdxBizJgRegisterInfo registerInfo = this.getOne(new QueryWrapper<IdxBizJgRegisterInfo>().eq("RECORD", record));
        if (!ValidationUtil.isEmpty(registerInfo)) {
            String equCategory = registerInfo.getEquCategory();// 设备类别
            String equDefine = registerInfo.getEquDefine();// 设备品种
            List<EquipmentCategory> categoryList1 = commonService.getEquipmentCategoryList(equCategory, null);
            List<EquipmentCategory> categoryList2 = commonService.getEquipmentCategoryList(equDefine, null);
            Map<String, Object> registerInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                registerInfoMap = Bean.BeantoMap(registerInfo);
                registerInfoMap.put("registerinfoSeq", registerInfo.getSequenceNbr());
                registerInfoMap.put("sequenceNbr", registerInfo.getSequenceNbr());
                registerInfoMap.put("productPhoto", JSON.parseArray(registerInfo.getProductPhoto()));
                if (CollectionUtils.isNotEmpty(categoryList1)) {
                    registerInfoMap.put("equCategoryDesc", categoryList1.get(0).getName());
                }
                if (CollectionUtils.isNotEmpty(categoryList2)) {
                    registerInfoMap.put("equDefineDesc", categoryList2.get(0).getName());
                }
                if (!ObjectUtils.isEmpty(registerInfoMap.get("otherAccessoriesReg"))) {
                    registerInfoMap.put("otherAccessoriesReg", JSON.parse(String.valueOf(registerInfoMap.get("otherAccessoriesReg"))));
                }
            } else {
                String[] fields = {"PRODUCT_PHOTO", "OTHER_ACCESSORIES_REG"};
                registerInfoMap = convertCamelToUnderscore(registerInfo, fields);
                registerInfoMap.put("REGISTERINFO_SEQ", registerInfo.getSequenceNbr());
                registerInfoMap.put(SEQUENCE_NBR, registerInfo.getSequenceNbr());
                if (CollectionUtils.isNotEmpty(categoryList1)) {
                    registerInfoMap.put("EQU_CATEGORY_DESC", categoryList1.get(0).getName());
                }
                if (CollectionUtils.isNotEmpty(categoryList2)) {
                    registerInfoMap.put("EQU_DEFINE_DESC", categoryList2.get(0).getName());
                }
            }
            if (!registerInfoMap.isEmpty()) {
                Map<String, Object> filterMap = registerInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        // 维保备案【一对多，暂时只取最新一条数据】
        IdxBizJgMaintenanceRecordInfo maintenanceRecordInfo = iIdxBizJgMaintenanceRecordInfoService.queryNewestDetailByRecord(record);
        if (!ValidationUtil.isEmpty(maintenanceRecordInfo)) {
            Map<String, Object> maintenanceRecordInfoMap;

            if (!ValidationUtil.isEmpty(fieldType)) {
                maintenanceRecordInfoMap = Bean.BeantoMap(maintenanceRecordInfo);
                maintenanceRecordInfoMap.put("repairInform", JSON.parse(maintenanceRecordInfo.getRepairInform()));
                maintenanceRecordInfoMap.put("maintenancerecordinfoSeq", maintenanceRecordInfo.getSequenceNbr());
            } else {
                String[] toArrayFields = {"repairInform"};
                maintenanceRecordInfoMap = convertCamelToUnderscore(maintenanceRecordInfo, toArrayFields);
                maintenanceRecordInfoMap.put("MAINTENANCERECORDINFO_SEQ", maintenanceRecordInfo.getSequenceNbr());
            }
            if (!maintenanceRecordInfoMap.isEmpty()) {
                Map<String, Object> filterMap = maintenanceRecordInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        // 监督管理
        IdxBizJgSupervisionInfo supervisionInfo = iIdxBizJgSupervisionInfoService.getOneData(record);
        if (!ValidationUtil.isEmpty(supervisionInfo)) {
            Map<String, Object> supervisionInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                supervisionInfoMap = Bean.BeantoMap(supervisionInfo);
                supervisionInfoMap.put("supervisioninfoSeq", supervisionInfo.getSequenceNbr());
            } else {
                supervisionInfoMap = convertCamelToUnderscore(supervisionInfo, null);
                supervisionInfoMap.put("SUPERVISIONINFO_SEQ", supervisionInfo.getSequenceNbr());
            }
            if (!supervisionInfoMap.isEmpty()) {
                Map<String, Object> filterMap = supervisionInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        // 其他信息
        IdxBizJgOtherInfo otherInfo = iIdxBizJgOtherInfoService.getOneData(record);
        if (!ValidationUtil.isEmpty(otherInfo)) {
            Map<String, Object> otherInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                otherInfoMap = Bean.BeantoMap(otherInfo);
                otherInfoMap.put("otherinfoSeq", otherInfo.getSequenceNbr());
            } else {
                otherInfoMap = convertCamelToUnderscore(otherInfo, null);
                otherInfoMap.put("OTHERINFO_SEQ", otherInfo.getSequenceNbr());
            }
            if (!otherInfoMap.isEmpty()) {
                Map<String, Object> filterMap = otherInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        // 检验检测【一对多，暂时只取最新一条数据】
        IdxBizJgInspectionDetectionInfo inspectionDetectionInfo = iIdxBizJgInspectionDetectionInfoService.queryNewestDetailByRecord(record);
        if (!ValidationUtil.isEmpty(inspectionDetectionInfo)) {
            Map<String, Object> inspectionDetectionInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                inspectionDetectionInfoMap = Bean.BeantoMap(inspectionDetectionInfo);
                inspectionDetectionInfoMap.put("inspectiondetectioninfoSeq", inspectionDetectionInfo.getSequenceNbr());
                inspectionDetectionInfoMap.put("inspectReport", JSON.parseArray(inspectionDetectionInfo.getInspectReport()));
            } else {
                String[] fields = {"INSPECT_REPORT"};
                inspectionDetectionInfoMap = convertCamelToUnderscore(inspectionDetectionInfo, fields);
                inspectionDetectionInfoMap.put("INSPECTIONDETECTIONINFO_SEQ", inspectionDetectionInfo.getSequenceNbr());
            }
            if (!inspectionDetectionInfoMap.isEmpty()) {
                Map<String, Object> filterMap = inspectionDetectionInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }

        objMap.put("completedBusinessTypes", judgeTheBusinessAccordingByRecord(record, objMap));
        // 账号类型（用于车用气瓶流程页面-》监管审核-》打开设备详情 时隐藏保存按钮）
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        objMap.put("accountType", reginParams.getCompany().getCompanyType());
        return objMap;
    }

    /**
     * 根据record判断设备完成了哪些业务（安装告知/维保备案/使用登记）
     *
     * @return
     */
    public String judgeTheBusinessAccordingByRecord(String record, Map<String, Object> objMap) {
        String business = "";
        // 安装告知
        Map<String, Object> installDetail = jgUseRegistrationMapper.getiInstallDetail(record);
        if (!ObjectUtils.isEmpty(installDetail)) {
            business = business + ",安装告知";
            objMap.putAll(installDetail);
            objMap.put("insOtherAccessories", JSON.parse(Optional.ofNullable(installDetail.get("insOtherAccessories")).orElse("").toString()));
            objMap.put("installProxyStatementAttachment", JSON.parse(Optional.ofNullable(installDetail.get("installProxyStatementAttachment")).orElse("").toString()));
            objMap.put("installContractAttachment", JSON.parse(Optional.ofNullable(installDetail.get("installContractAttachment")).orElse("").toString()));
        }
        // 维保备案
        Map<String, Object> maintenanceDetail = jgUseRegistrationMapper.getMaintenanceDetail(record);
        if (!ObjectUtils.isEmpty(maintenanceDetail)) {
            business = business + ",维保备案";
            objMap.putAll(maintenanceDetail);
            objMap.put("maintenanceContract", JSON.parse(Optional.ofNullable(maintenanceDetail.get("maintenanceContract")).orElse("").toString()));
            objMap.put("maintOtherAccessories", JSON.parse(Optional.ofNullable(maintenanceDetail.get("maintOtherAccessories")).orElse("").toString()));
        }
        // 使用登记
        Map<String, Object> useRegistrationDetail = jgUseRegistrationMapper.getUseRegistrationDetail(record);
        if (!ObjectUtils.isEmpty(useRegistrationDetail)) {
            business = business + ",使用登记";
            objMap.putAll(useRegistrationDetail);
        }
        return business;
    }

    /**
     * 查询设备技术参数
     *
     * @param record    设备Id
     * @param fieldType 返回字段类型【CamelCase:驼峰命名，“”：纯大写加下划线】
     * @return
     */
    private Map<String, Object> getEquipParamsMap(String record, String fieldType, String equipCode) {

        Map<String, Object> objMap = new HashMap<>();
        if (EquipmentClassifityEnum.DT.getCode().equals(equipCode)) {
            // 电梯
            IdxBizJgTechParamsElevator elevator = iIdxBizJgTechParamsElevatorService.getOneData(record);
            if (!ValidationUtil.isEmpty(elevator)) {
                Map<String, Object> elevatorMap;
                if (!ValidationUtil.isEmpty(fieldType)) {
                    elevatorMap = Bean.BeantoMap(elevator);
                    elevatorMap.put("elevatorSeq", elevator.getSequenceNbr());
                    elevatorMap.put("explosionproofSignComplete", JSON.parseArray(elevator.getExplosionproofSignComplete()));
                } else {
                    String[] fields = {"EXPLOSIONPROOF_SIGN_COMPLETE"};
                    elevatorMap = convertCamelToUnderscore(elevator, fields);
                    elevatorMap.put("ELEVATOR_SEQ", elevator.getSequenceNbr());
                }
                if (!elevatorMap.isEmpty()) {
                    Map<String, Object> filterMap = elevatorMap.entrySet()
                            .stream()
                            .filter(e -> e.getValue() != null && e.getValue() != "")
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                    objMap.putAll(filterMap);
                }
            }
        } else if (EquipmentClassifityEnum.CC.getCode().equals(equipCode)) {
            // 厂车
            IdxBizJgTechParamsVehicle vehicle = iIdxBizJgTechParamsVehicleService.getOneData(record);
            if (!ValidationUtil.isEmpty(vehicle)) {
                Map<String, Object> vehicleMap;
                if (!ValidationUtil.isEmpty(fieldType)) {
                    vehicleMap = Bean.BeantoMap(vehicle);
                    vehicleMap.put("vehicleSeq", vehicle.getSequenceNbr());
                } else {
                    vehicleMap = convertCamelToUnderscore(vehicle, null);
                    vehicleMap.put("VEHICLE_SEQ", vehicle.getSequenceNbr());
                }
                if (!vehicleMap.isEmpty()) {
                    Map<String, Object> filterMap = vehicleMap.entrySet()
                            .stream()
                            .filter(e -> e.getValue() != null && e.getValue() != "")
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                    objMap.putAll(filterMap);
                }
            }
            // 主要零部件
            List<Map<String, Object>> mainPartsMapsByRecord = this.getMainPartsMapsByRecord(record, fieldType);
            objMap.put("subForm_sey164b51a", mainPartsMapsByRecord);
            objMap.put("subForm_tef7yf5fbr", mainPartsMapsByRecord);
        } else if (EquipmentClassifityEnum.KYSD.getCode().equals(equipCode)) {
            // 索道
            IdxBizJgTechParamsRopeway ropeway = iIdxBizJgTechParamsRopewayService.getOneData(record);
            if (!ValidationUtil.isEmpty(ropeway)) {
                Map<String, Object> ropewayMap;
                if (!ValidationUtil.isEmpty(fieldType)) {
                    ropewayMap = Bean.BeantoMap(ropeway);
                    ropewayMap.put("ropewaySeq", ropeway.getSequenceNbr());
                } else {
                    ropewayMap = convertCamelToUnderscore(ropeway, null);
                    ropewayMap.put("ROPEWAY_SEQ", ropeway.getSequenceNbr());
                }
                if (!ropewayMap.isEmpty()) {
                    Map<String, Object> filterMap = ropewayMap.entrySet()
                            .stream()
                            .filter(e -> e.getValue() != null && e.getValue() != "")
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                    objMap.putAll(filterMap);
                }
            }
            // 主要零部件
            List<Map<String, Object>> mainPartsMapsByRecord = this.getMainPartsMapsByRecord(record, fieldType);
            objMap.put("subForm_5fi0jewuyh", mainPartsMapsByRecord);
        } else if (EquipmentClassifityEnum.YLSS.getCode().equals(equipCode)) {
            // 游乐设施
            IdxBizJgTechParamsRides rides = iIdxBizJgTechParamsRidesService.getOneData(record);
            if (!ValidationUtil.isEmpty(rides)) {
                Map<String, Object> ridesMap;
                if (!ValidationUtil.isEmpty(fieldType)) {
                    ridesMap = Bean.BeantoMap(rides);
                    ridesMap.put("ridesSeq", rides.getSequenceNbr());
                } else {
                    ridesMap = convertCamelToUnderscore(rides, null);
                    ridesMap.put("RIDES_SEQ", rides.getSequenceNbr());
                }
                if (!ridesMap.isEmpty()) {
                    Map<String, Object> filterMap = ridesMap.entrySet()
                            .stream()
                            .filter(e -> e.getValue() != null && e.getValue() != "")
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                    objMap.putAll(filterMap);
                }
            }

        } else if (EquipmentClassifityEnum.GL.getCode().equals(equipCode)) {
            // 锅炉
            IdxBizJgTechParamsBoiler boiler = iIdxBizJgTechParamsBoilerService.getOneData(record);
            if (!ValidationUtil.isEmpty(boiler)) {
                Map<String, Object> boilerMap;
                if (!ValidationUtil.isEmpty(fieldType)) {
                    boilerMap = Bean.BeantoMap(boiler);
                    boilerMap.put("boilerSeq", boiler.getSequenceNbr());
                } else {
                    boilerMap = convertCamelToUnderscore(boiler, null);
                    boilerMap.put("BOILER_SEQ", boiler.getSequenceNbr());
                }
                if (!boilerMap.isEmpty()) {
                    Map<String, Object> filterMap = boilerMap.entrySet()
                            .stream()
                            .filter(e -> e.getValue() != null && e.getValue() != "")
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                    objMap.putAll(filterMap);
                }
            }
            // 安全附件
            List<Map<String, Object>> protectionDevicesMapsByRecord = this.getProtectionDevicesMapsByRecord(record, fieldType);
            objMap.put("subForm_1hh88r4m69", protectionDevicesMapsByRecord);
        } else if (EquipmentClassifityEnum.YLRQ.getCode().equals(equipCode)) {
            // 压力容器
            IdxBizJgTechParamsVessel vessel = iIdxBizJgTechParamsVesselService.getOneData(record);
            if (!ValidationUtil.isEmpty(vessel)) {
                Map<String, Object> vesselMap;
                if (!ValidationUtil.isEmpty(fieldType)) {
                    vesselMap = Bean.BeantoMap(vessel);
                    vesselMap.put("vesselSeq", vessel.getSequenceNbr());
                } else {
                    vesselMap = convertCamelToUnderscore(vessel, null);
                    vesselMap.put("VESSEL_SEQ", vessel.getSequenceNbr());
                }
                if (!vesselMap.isEmpty()) {
                    Map<String, Object> filterMap = vesselMap.entrySet()
                            .stream()
                            .filter(e -> e.getValue() != null && e.getValue() != "")
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                    objMap.putAll(filterMap);
                }
            }
            // 主要零部件和安全附件
            List<Map<String, Object>> mainPartsMapsByRecord = this.getMainPartsMapsByRecord(record, fieldType);
            List<Map<String, Object>> protectionDevicesMapsByRecord = this.getProtectionDevicesMapsByRecord(record, fieldType);
            objMap.put("subForm_fie04854f2", mainPartsMapsByRecord);
            objMap.put("subForm_d4xdzhsgdj", protectionDevicesMapsByRecord);
        } else if (EquipmentClassifityEnum.YLGD.getCode().equals(equipCode)) {
            // 压力管道
            IdxBizJgTechParamsPipeline pipeline = iIdxBizJgTechParamsPipelineService.getOneData(record);
            if (!ValidationUtil.isEmpty(pipeline)) {
                Map<String, Object> pipelineMap;
                if (!ValidationUtil.isEmpty(fieldType)) {
                    pipelineMap = Bean.BeantoMap(pipeline);
                    pipelineMap.put("pipelineSeq", pipeline.getSequenceNbr());
                } else {
                    pipelineMap = convertCamelToUnderscore(pipeline, null);
                    pipelineMap.put("PIPELINE_SEQ", pipeline.getSequenceNbr());
                    pipelineMap.put("STARTE_POSITION", JSONObject.parseObject(pipeline.getStartePosition()));
                }
                Map<String, Object> filterMap = pipelineMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
            // 主要零部件
            List<Map<String, Object>> mainPartsMapsByRecord = this.getMainPartsMapsByRecord(record, fieldType);
            objMap.put("subForm_9n7nu55z8r", mainPartsMapsByRecord);
        } else if (EquipmentClassifityEnum.QZJX.getCode().equals(equipCode)) {
            // 起重机械
            IdxBizJgTechParamsLifting lifting = iIdxBizJgTechParamsLiftingService.getOneData(record);
            if (!ValidationUtil.isEmpty(lifting)) {
                Map<String, Object> liftingMap;
                if (!ValidationUtil.isEmpty(fieldType)) {
                    liftingMap = Bean.BeantoMap(lifting);
                    liftingMap.put("liftingSeq", lifting.getSequenceNbr());
                } else {
                    liftingMap = convertCamelToUnderscore(lifting, null);
                    liftingMap.put("LIFTING_SEQ", lifting.getSequenceNbr());
                }
                if (!liftingMap.isEmpty()) {
                    Map<String, Object> filterMap = liftingMap.entrySet()
                            .stream()
                            .filter(e -> e.getValue() != null && e.getValue() != "")
                            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                    objMap.putAll(filterMap);
                }
            }

            // 主要零部件和安全附件
            List<Map<String, Object>> mainPartsMapsByRecord = this.getMainPartsMapsByRecord(record, fieldType);
            List<Map<String, Object>> protectionDevicesMapsByRecord = this.getProtectionDevicesMapsByRecord(record, fieldType);
            objMap.put("subForm_bqirdyvztt", mainPartsMapsByRecord);
            objMap.put("subForm_29yy3pdzhl", protectionDevicesMapsByRecord);
            objMap.put("subForm_h5h4x0zhur", protectionDevicesMapsByRecord);

        }

        return objMap;
    }

    /**
     * 查询指定设备的主要零部件【一对多，查出多条数据】
     *
     * @param record
     * @param fieldType
     * @return
     */
    private List<Map<String, Object>> getMainPartsMapsByRecord(String record, String fieldType) {
        List<Map<String, Object>> resultListMap = new ArrayList<>();
        List<IdxBizJgMainParts> mainParts = iIdxBizJgMainPartsService.queryListByRecord(record);
        if (!ValidationUtil.isEmpty(mainParts)) {
            if (!ValidationUtil.isEmpty(fieldType)) {
                for (IdxBizJgMainParts mainPart : mainParts) {
                    Map<String, Object> mainPartsMap = null;
                    mainPartsMap = Bean.BeantoMap(mainPart);
                    mainPartsMap.put("mainpartsSeq", mainPart.getSequenceNbr());
                    resultListMap.add(mainPartsMap);
                }
            } else {
                for (IdxBizJgMainParts mainPart : mainParts) {
                    Map<String, Object> mainPartsMap = null;
                    mainPartsMap = convertCamelToUnderscore(mainPart, null);
                    mainPartsMap.put("MAINPARTS_SEQ", mainPart.getSequenceNbr());
                    resultListMap.add(mainPartsMap);
                }
            }
        }
        return resultListMap;
    }

    /**
     * 查询指定设备的安全附件【一对多，查出多条数据】
     *
     * @param record
     * @param fieldType
     * @return
     */
    private List<Map<String, Object>> getProtectionDevicesMapsByRecord(String record, String fieldType) {
        List<Map<String, Object>> resultListMap = new ArrayList<>();
        List<IdxBizJgProtectionDevices> protectionDevices = iIdxBizJgProtectionDevicesService.queryListByRecord(record);
        if (!ValidationUtil.isEmpty(protectionDevices)) {
            if (!ValidationUtil.isEmpty(fieldType)) {
                for (IdxBizJgProtectionDevices protectionDevice : protectionDevices) {
                    Map<String, Object> protectionDeviceMap = null;
                    protectionDeviceMap = Bean.BeantoMap(protectionDevice);
                    protectionDeviceMap.put("protectiondevicesSeq", protectionDevice.getSequenceNbr());
                    resultListMap.add(protectionDeviceMap);
                }
            } else {
                for (IdxBizJgProtectionDevices protectionDevice : protectionDevices) {
                    Map<String, Object> protectionDeviceMap = null;
                    protectionDeviceMap = convertCamelToUnderscore(protectionDevice, null);
                    protectionDeviceMap.put("PROTECTIONDEVICES_SEQ", protectionDevice.getSequenceNbr());
                    resultListMap.add(protectionDeviceMap);
                }
            }
        }
        return resultListMap;
    }

    /**
     * 设备注册信息分页查询
     *
     * @param map
     * @return
     */
    public Page<JSONObject> queryForEquipmentRegisterPage(JSONObject map) {

        if (map.containsKey("flag") && !map.containsKey("USE_UNIT_CREDIT_CODE")) {
            return new Page<>();
        }

        Integer pageNumber = ObjectUtils.isEmpty(map.getInteger("number")) ? 1 : map.getInteger("number");
        Integer size = ObjectUtils.isEmpty(map.getInteger("size")) ? 20 : map.getInteger("size");
        Page<JSONObject> result = new Page<>(pageNumber, size);
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();

        // 获取当前登录人单位类型
        JSONObject company = getCompanyType();
        if (ValidationUtil.isEmpty(company)) {
            result.setRecords(new ArrayList<>());
            result.setTotal(0);
            return result;
        }
        String companyCode = company.getString("companyCode").contains("_") ?
                company.getString("companyCode").split("_")[1] : company.getString("companyCode");
        String type = company.getString("companyType");


        // 根据当前登录人查询
        if (!ValidationUtil.isEmpty(map.get(EQUSTATE))) {
            map.put(EQUSTATE, EquimentEnum.getCode.get(map.get(EQUSTATE).toString()).toString());
        }

        // 根据当前登录用户类型及管辖机构筛选条件添加对应参数
        if (ObjectUtils.isEmpty(map.getString(SEQUENCE_NBR)) && ObjectUtils.isEmpty(map.getString("useUnitCreditCode"))) {
            if (!ValidationUtil.isEmpty(type) && type.contains("使用单位")) {
                if (ValidationUtil.isEmpty(map.getString("USE_UNIT_CREDIT_CODE"))) {
                    map.put("USE_UNIT_CREDIT_CODE", companyCode);
                }
            }
            if (!ValidationUtil.isEmpty(type) && type.contains("安装改造维修单位")) {
                map.put("USC_UNIT_CREDIT_CODE", companyCode);
            }
            if (!ValidationUtil.isEmpty(type) && type.contains("个人主体")) {
                map.put("USE_UNIT_CREDIT_CODE", companyCode);
            }
        }

        // 默认条件【STATUS==="" || null】
        BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
        meBuilder.should(QueryBuilders.matchQuery("STATUS", "已认领"));
        meBuilder.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("STATUS")));
        meBuilder.should(QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery("STATUS", "")));
        meBuilder.minimumShouldMatch(1);
        boolMust.must(meBuilder);

        // DATA_SOURCE 为“jg”开头的数据（从监管新加或复制的设备）
        // 20240314 提出的监管业务不要让企业用户选到之前一码通认领或补录的设备，让从监管业务中去新增
        BoolQueryBuilder dBuilder = QueryBuilders.boolQuery();

        if (map.containsKey("DATA_SOURCE") && !ObjectUtils.isEmpty(map.get("DATA_SOURCE"))) {
            if ("jg_his".equals(map.get("DATA_SOURCE"))) {// 只查历史，前缀jg_his
                dBuilder.must(QueryBuilders.prefixQuery("DATA_SOURCE", "jg_his"));
            } else if (!"jg_his".equals(map.getString("DATA_SOURCE"))) {// 只查新增，前缀为jg且前缀不为jg_his
                dBuilder.must(QueryBuilders.prefixQuery("DATA_SOURCE", "jg"));
                dBuilder.mustNot(QueryBuilders.prefixQuery("DATA_SOURCE", "jg_his"));
            }
        } else {
            // 查所有，前缀jg
            dBuilder.must(QueryBuilders.prefixQuery("DATA_SOURCE", "jg"));
        }
        boolMust.must(dBuilder);

        String queryType = map.getString("QUERY_TYPE");
        if (!ObjectUtils.isEmpty(queryType)) {
            // 查询 安装告知【可告知设备列表】【USE_UNIT_CREDIT_CODE=== null ||  ""】
            if (ValidationUtil.equals(queryType, "AZ")) {// 安装
                BoolQueryBuilder nullOrEmptyQuery = QueryBuilders.boolQuery()
                        .mustNot(QueryBuilders.wildcardQuery("USE_UNIT_CREDIT_CODE", "*"));
                boolMust.must(nullOrEmptyQuery);
                this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "installNotice");
                // 安装告知设备选择 - 业务限制
                // 根据设备类别（EQU_CATEGORY）、安装单位过滤设备（USC_UNIT_CREDIT_CODE）  下面过滤条件已有
            } else if (ValidationUtil.equals(queryType, "WB")) {// 维保
                // 查询 维保备案【可绑定设备列表】【(EQU_STATE=== null ||  ""）】
                BoolQueryBuilder wbBuilder = QueryBuilders.boolQuery();
                wbBuilder.mustNot(QueryBuilders.existsQuery("EQU_STATE"));
                boolMust.must(wbBuilder);
            } else if (ValidationUtil.equals(queryType, "SY")) {// 使用
                // 查询 使用登记【可选设备列表】【(EQU_STATUS=== null || "" ) && (USE_ORG_CODE（使用登记证编号） ==="" || null)】
                BoolQueryBuilder syBuilder = QueryBuilders.boolQuery();
                syBuilder.mustNot(QueryBuilders.existsQuery("EQU_STATE"));
                syBuilder.mustNot(QueryBuilders.wildcardQuery("USE_ORG_CODE", "*"));
                boolMust.must(syBuilder);
                this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "useRegister");
            } else if (ValidationUtil.equals(queryType, "FINISH_SY")) {
                // 注意：上面条件是过滤出【未做过】某个业务的设备，下面部分是过滤出【做过】某个业务的设备
                // 查询 已经做过【使用登记】 的设备 【(EQU_STATUS != 空 ) && (USE_ORG_CODE（使用登记证编号） != 空)】
                BoolQueryBuilder syBuilder = QueryBuilders.boolQuery();
                syBuilder.must(QueryBuilders.existsQuery("EQU_STATE"))
                        .must(QueryBuilders.wildcardQuery("USE_ORG_CODE", "*"));
                boolMust.must(syBuilder);
            } else if (ValidationUtil.equals(queryType, "GZ_GZ") || ValidationUtil.equals(queryType, "GZ_WX") || ValidationUtil.equals(queryType, "GZ_YZ")) {
                BoolQueryBuilder syBuilder = QueryBuilders.boolQuery();
                syBuilder.must(QueryBuilders.existsQuery("EQU_STATE"));
                syBuilder.must(QueryBuilders.wildcardQuery("USE_ORG_CODE", "*"));
                boolMust.must(syBuilder);
                if (ValidationUtil.equals(queryType, "GZ_GZ")) {// 改造告知设备选择 - 业务限制
                    // 设备类别（EQU_CATEGORY）、安装单位（USC_UNIT_CREDIT_CODE）、选择的使用单位（USE_UNIT_CREDIT_CODE）、选择的区县（USE_PLACE_CODE）过滤数据
                    if (ValidationUtil.isEmpty(map.get("useUnitCreditCode")) || ValidationUtil.isEmpty(map.get("county"))) {
                        throw new BadRequest("请先选择使用单位，施工区县等信息");
                    }
                    map.put("USE_UNIT_CREDIT_CODE", map.get("useUnitCreditCode"));
                    map.put(USE_PLACE_CODE, String.valueOf(map.get("county")).split("_")[0]);
                } else if (ValidationUtil.equals(queryType, "GZ_WX")) {// 维修告知设备选择 - 业务限制
                    // 设备类别（EQU_CATEGORY）、安装单位（USC_UNIT_CREDIT_CODE）、选择的使用单位（USE_UNIT_CREDIT_CODE）、选择的区县（USE_PLACE_CODE）过滤数据
                    if (ValidationUtil.isEmpty(map.get("useUnitCreditCode")) || ValidationUtil.isEmpty(map.get("county"))) {
                        throw new BadRequest("请先选择使用单位，施工区县等信息");
                    }
                    map.put("USE_UNIT_CREDIT_CODE", map.get("useUnitCreditCode"));
                    map.put(USE_PLACE_CODE, String.valueOf(map.get("county")).split("_")[0]);
                } else if (ValidationUtil.equals(queryType, "GZ_YZ")) {// 移装告知设备选择 - 业务限制
                    // 设备类别（EQU_CATEGORY）、安装单位（USC_UNIT_CREDIT_CODE）、选择的使用单位（USE_UNIT_CREDIT_CODE）、（区内移装（transferType=区内移装）根据区县(USE_PLACE_CODE)）过滤数据
                    if (ValidationUtil.isEmpty(map.get("useUnitCreditCode"))) {
                        throw new BadRequest("请先选择使用单位等信息");
                    }
                    if (!ValidationUtil.isEmpty(map.get("transferType")) && ValidationUtil.equals(map.get("transferType"), "区内移装")
                            && ValidationUtil.isEmpty(map.get("county"))) {
                        throw new BadRequest("请先选择施工区域等信息");
                    }
                    map.put("USE_UNIT_CREDIT_CODE", map.get("useUnitCreditCode"));
                    map.put(USE_PLACE_CODE, ValidationUtil.equals(map.get("transferType"), "区内移装") ? String.valueOf(map.get("county")).split("_")[0] : null);
                }
            }
//            this.setRepeatUsedCheckFilterByType(boolMust,companyCode,queryType);
        }

        // 通用匹配规则，其他条件构建
        if (!ObjectUtils.isEmpty(map.getString(SEQUENCE_NBR))) {
            BoolQueryBuilder seqBuilder = QueryBuilders.boolQuery();
            String param = map.getString(SEQUENCE_NBR);
            List<String> strings = Arrays.asList(param.split(","));
            seqBuilder.must(QueryBuilders.termsQuery("SEQUENCE_NBR.keyword", strings));
            boolMust.must(seqBuilder);
        }

        if (!ObjectUtils.isEmpty(map.getString(IS_INTO_MANAGEMENT))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String param = QueryParser.escape(map.getString(IS_INTO_MANAGEMENT));
            pBuilder.must(QueryBuilders.matchQuery(IS_INTO_MANAGEMENT, param));
            boolMust.must(pBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString(EQU_CATEGORY))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String param = QueryParser.escape(map.getString(EQU_CATEGORY));
            pBuilder.must(QueryBuilders.matchPhraseQuery(EQU_CATEGORY, "*" + param + "*"));
            boolMust.must(pBuilder);

        }
        if (!ObjectUtils.isEmpty(map.getString("USE_PLACE"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String param = QueryParser.escape(map.getString("USE_PLACE"));
            pBuilder.must(QueryBuilders.matchPhraseQuery("USE_PLACE", "*" + param + "*"));
            boolMust.must(pBuilder);
        }
        // 设备状态
        if (!ObjectUtils.isEmpty(map.getString("EQU_STATE"))) {
            BoolQueryBuilder esBuilder = QueryBuilders.boolQuery();
            String param = QueryParser.escape(map.getLong("EQU_STATE").toString());
            esBuilder.must(QueryBuilders.matchQuery("EQU_STATE", param));
            boolMust.must(esBuilder);
        }

        // 使用单位 //安装改造维修单位
        if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_CREDIT_CODE")) && !ObjectUtils.isEmpty(map.getString("USC_UNIT_CREDIT_CODE"))) {
            BoolQueryBuilder ubuilder = QueryBuilders.boolQuery();
            String useCode = QueryParser.escape(map.getString("USE_UNIT_CREDIT_CODE"));
            useCode = useCode.contains("_") ? useCode.split("_")[0] : useCode;
            ubuilder.must(QueryBuilders.matchQuery("USE_UNIT_CREDIT_CODE", useCode));

            String uscCode = QueryParser.escape(map.getString("USC_UNIT_CREDIT_CODE")).toLowerCase();
            ubuilder.must(QueryBuilders.wildcardQuery("USC_UNIT_CREDIT_CODE", "*" + QueryParser.escape(uscCode) + "*"));
            boolMust.must(ubuilder);
        } else {
            if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_CREDIT_CODE")) || !ObjectUtils.isEmpty(map.getString("useUnitCreditCode"))) {
                BoolQueryBuilder uuccBuilder = QueryBuilders.boolQuery();
                String uucc = !ValidationUtil.isEmpty(map.getString("USE_UNIT_CREDIT_CODE")) ? map.getString("USE_UNIT_CREDIT_CODE") : map.getString("useUnitCreditCode");
                String param = QueryParser.escape(uucc);
                param = param.contains("_") ? param.split("_")[0] : param;
                uuccBuilder.must(QueryBuilders.matchQuery("USE_UNIT_CREDIT_CODE", param));
                boolMust.must(uuccBuilder);
            }
            if (!ObjectUtils.isEmpty(map.getString("USC_UNIT_CREDIT_CODE"))) {
                BoolQueryBuilder uuccBuilder = QueryBuilders.boolQuery();
                String uscCode = QueryParser.escape(map.getString("USC_UNIT_CREDIT_CODE")).toLowerCase();
                uuccBuilder.must(QueryBuilders.wildcardQuery("USC_UNIT_CREDIT_CODE", "*" + QueryParser.escape(uscCode) + "*"));
                boolMust.must(uuccBuilder);
            }
        }

        // 监管码
        if (!ObjectUtils.isEmpty(map.getString("SUPERVISORY_CODE"))) {
            BoolQueryBuilder scBuilder = QueryBuilders.boolQuery();
            String param = map.getString("SUPERVISORY_CODE");
            List<String> strings = Arrays.asList(param.split(","));
            scBuilder.must(QueryBuilders.termsQuery("SUPERVISORY_CODE", strings));
            boolMust.must(scBuilder);
        }
        // 设备种类编码
        if (!ObjectUtils.isEmpty(map.getString("EQU_LIST_CODE"))) {
            BoolQueryBuilder elcBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_LIST_CODE"));
            elcBuilder.must(QueryBuilders.matchPhraseQuery("EQU_LIST_CODE", test));
            boolMust.must(elcBuilder);
        }
        // 设备类别编码
        if (!ObjectUtils.isEmpty(map.getString("EQU_DEFINE_CODE"))) {
            BoolQueryBuilder elcBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_DEFINE_CODE"));
            elcBuilder.must(QueryBuilders.matchPhraseQuery("EQU_DEFINE_CODE", test));
            boolMust.must(elcBuilder);
        }
        // 设备种类名称
        if (!ObjectUtils.isEmpty(map.getString(EQU_LIST))) {
            BoolQueryBuilder elBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(EQU_LIST));
            elBuilder.must(QueryBuilders.matchPhraseQuery(EQU_LIST, "*" + test + "*"));
            boolMust.must(elBuilder);
        }

        // 设备类别
        if (!ObjectUtils.isEmpty(map.getString("EQU_CATEGORY_CODE"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_CATEGORY_CODE"));
            pBuilder.must(QueryBuilders.termQuery("EQU_CATEGORY_CODE", test));
            boolMust.must(pBuilder);
        }
        // 是否车用气瓶
        if (!ObjectUtils.isEmpty(map.getString(WHETHER_VEHICLE_CYLINDER))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(WHETHER_VEHICLE_CYLINDER));
            pBuilder.must(QueryBuilders.termQuery(WHETHER_VEHICLE_CYLINDER, test));
            boolMust.must(pBuilder);
        }
        // 是否撬装式压力容器
        if (!ObjectUtils.isEmpty(map.getString(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL)) && !"0".equals(map.getString(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL));
            pBuilder.must(QueryBuilders.termQuery(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL, test));
            boolMust.must(pBuilder);
        }
        // 设备代码模糊查询
        if (!ObjectUtils.isEmpty(map.getString(EQU_CODE))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(EQU_CODE));
            pBuilder.must(QueryBuilders.wildcardQuery(EQU_CODE, "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 单位内部编号模糊查询
        if (!ObjectUtils.isEmpty(map.getString("USE_INNER_CODE"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_INNER_CODE"));
            pBuilder.must(QueryBuilders.wildcardQuery("USE_INNER_CODE", "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 出厂编号/产品编码模糊查询
        if (!ObjectUtils.isEmpty(map.getString(FACTORY_NUM))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(FACTORY_NUM));
            pBuilder.must(QueryBuilders.wildcardQuery(FACTORY_NUM, "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 制造单位（生产单位）名称模糊查询
        if (!ObjectUtils.isEmpty(map.getString("PRODUCE_UNIT_NAME"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("PRODUCE_UNIT_NAME"));
            pBuilder.must(QueryBuilders.wildcardQuery("PRODUCE_UNIT_NAME", "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 模糊查询
        if (!ObjectUtils.isEmpty(map.getString(USE_PLACE_CODE))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(USE_PLACE_CODE));
            pBuilder.must(QueryBuilders.wildcardQuery(USE_PLACE_CODE, "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        builder.query(boolMust);
        builder.sort("REC_DATE", SortOrder.DESC);
        builder.from((pageNumber - 1) * size);
        builder.size(size);
        request.source(builder);
        List<JSONObject> list = new LinkedList<>();
        long totle = 0;
        if (log.isDebugEnabled()) {
            log.debug("查询es 的查询条件: {}", request);
        }
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (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(CONSTRUCTIONTYPE))) {
                    // 转化施工类型
                    String constructionType = dto2.get(CONSTRUCTIONTYPE).toString();
                    if (!ValidationUtil.isEmpty(constructionType)) {
                        List<String> constructionTypeList = Arrays.asList(constructionType.split(","));
                        List<String> statusList = new ArrayList<>();
                        for (String cType : constructionTypeList) {
                            Integer integer = Integer.valueOf(cType);
                            String status = ConstructionEnum.getName.get(integer);
                            statusList.add(status);
                        }
                        dto2.put(CONSTRUCTIONTYPE, Joiner.on(",").join(statusList));
                    }
                }
                if (!ValidationUtil.isEmpty(dto2.get(EQUSTATE))) {
                    Integer integer = Integer.valueOf(dto2.get(EQUSTATE).toString());
                    String status = EquimentEnum.getName.get(integer);
                    dto2.put(EQUSTATE, status);
                }
                if (!ValidationUtil.isEmpty(dto2.get(DATA_SOURCE))) {
                    String s = dto2.get(DATA_SOURCE).toString();
                    dto2.put(DATA_SOURCE, s);
                    dto2.put(DATA_SOURCE_NAME, Arrays.stream(EquipSourceEnum.values())
                            .filter(e -> s.startsWith(e.getCode()))
                            .map(EquipSourceEnum::getName)
                            .findFirst()
                            .orElse(EquipSourceEnum.jg.getName()));
                }
                dto2.put("record", dto2.get(SEQUENCE_NBR));
                list.add(dto2);
            }
            // 获取所有设备的Id
            List<String> equIds = null;
            if (!ValidationUtil.isEmpty(list)) {
                equIds = list.stream().map(item -> item.get(SEQUENCE_NBR).toString()).collect(Collectors.toList());
            }
            if (!ValidationUtil.isEmpty(equIds)) {
                // 查询设备地址
                List<IdxBizJgUseInfo> useInfoListByEquIds = idxBizJgUseInfoService.getUseInfoListByEquIds(equIds);
                Map<String, String> equAddressMap = new HashMap<>();
                if (!ValidationUtil.isEmpty(useInfoListByEquIds)) {
                    equAddressMap = useInfoListByEquIds.stream().collect(Collectors.toMap(IdxBizJgUseInfo::getRecord,
                                    useInfo -> {
                                        String fulladdress = "";
                                        if (!ValidationUtil.isEmpty(useInfo.getProvinceName())) {
                                            fulladdress += useInfo.getProvinceName();
                                        }
                                        if (!ValidationUtil.isEmpty(useInfo.getCityName())) {
                                            fulladdress += useInfo.getCityName();
                                        }
                                        if (!ValidationUtil.isEmpty(useInfo.getCountyName())) {
                                            fulladdress += useInfo.getCountyName();
                                        }
                                        if (!ValidationUtil.isEmpty(useInfo.getStreetName())) {
                                            fulladdress += useInfo.getStreetName();
                                        }
                                        if (!ValidationUtil.isEmpty(useInfo.getAddress())) {
                                            fulladdress += useInfo.getAddress();
                                        }
                                        return fulladdress;
                                    }
                            )
                    );
                }
                // 更新设备使用情况和设备地址
                for (JSONObject item : list) {
                    String fullAddress = equAddressMap.get(item.getString(SEQUENCE_NBR));
                    item.put("ADDRESS", !ValidationUtil.isEmpty(fullAddress) ? fullAddress : "");
                    item.put("CAN_EDIT", this.checkEquipIsCanEdit(item.getString(SEQUENCE_NBR)));
                    item.put("CAN_DELETE", this.checkEquipIsCanDelete(item.getString(SEQUENCE_NBR)));
                }
            }
            totle = response.getInternalResponse().hits().getTotalHits().value;
            result.setRecords(list);
            result.setTotal(totle);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    private void setRepeatUsedCheckFilterByType(BoolQueryBuilder boolMust, String companyCode, String queryType) {
        if ("AZ".equals(queryType)) {// 安装告知
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "installNotice");
        } else if ("GZ_GZ".equals(queryType)) {// 改造告知
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "renovationNoticeNew");
        } else if ("GZ_WX".equals(queryType)) {// 维修告知
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "maintainInfo");
        } else if ("GZ_YZ".equals(queryType)) {// 移装告知
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "transferNotice");
        } else if ("SY".equals(queryType)) {// 使用登记
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "useRegister");
        } else if ("DJ_GZ".equals(queryType)) {// 改造变更登记
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "changeRegistration");
        } else if ("DJ_YZ".equals(queryType)) {// 移装变更登记
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "changeRegistrationTransfer");
        } else if ("DJ_DW".equals(queryType)) {// 单位变更登记
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "unitChange");
        } else if ("DJ_GM".equals(queryType)) {// 更名变更登记
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "changeName");
        } else if ("BF_YZ".equals(queryType)) {// 注销
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "");
        } else if ("BF_ZX".equals(queryType)) {// 报废
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "");
        } else if ("SB_QY".equals(queryType)) {// 启用
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "");
        } else if ("SB_TY".equals(queryType)) {// 停用
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "");
        } else if ("WB_BA".equals(queryType)) {// 维保备案
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "maintenanceFiling");
        } else if ("SB_YJ".equals(queryType)) {// 设备移交
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "equipmentHandover");
        } else if ("QP_BG".equals(queryType)) {// 车用气瓶变更
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "vehicleGasCylinderChange");
        } else if ("QP_DJ".equals(queryType)) {// 车用气瓶登记
            this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "vehicleInformation");
        }
    }

    /**
     * 设备注册信息分页查询
     *
     * @param map
     * @return
     */
    public Page<JSONObject> queryForEquipmentRegisterPageHistory(JSONObject map) {

        if (map.containsKey("flag") && !map.containsKey("USE_UNIT_CREDIT_CODE")) {
            return new Page<>();
        }


        Integer pageNumber = ObjectUtils.isEmpty(map.getInteger("number")) ? 1 : map.getInteger("number");
        Integer size = ObjectUtils.isEmpty(map.getInteger("size")) ? 20 : map.getInteger("size");
        Page<JSONObject> result = new Page<>(pageNumber, size);
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();

        // 获取当前登录人单位类型
        JSONObject company = getCompanyType();
        if (ValidationUtil.isEmpty(company)) {
            result.setRecords(new ArrayList<>());
            result.setTotal(0);
            return result;
        }
        String companyCode = company.getString("companyCode").contains("_") ?
                company.getString("companyCode").split("_")[1] : company.getString("companyCode");
        String type = company.getString("companyType");


        // 根据当前登录人查询
        if (!ValidationUtil.isEmpty(map.get(EQUSTATE))) {
            map.put(EQUSTATE, EquimentEnum.getCode.get(map.get(EQUSTATE).toString()).toString());
        }

        // 根据当前登录用户类型及管辖机构筛选条件添加对应参数
        if (ObjectUtils.isEmpty(map.getString(SEQUENCE_NBR)) && ObjectUtils.isEmpty(map.getString("useUnitCreditCode"))) {
            if (!ValidationUtil.isEmpty(type) && type.contains("使用单位")) {
                if (ValidationUtil.isEmpty(map.getString("USE_UNIT_CREDIT_CODE"))) {
                    map.put("USE_UNIT_CREDIT_CODE", companyCode);
                }
            }
            if (!ValidationUtil.isEmpty(type) && type.contains("安装改造维修单位")) {
                map.put("USC_UNIT_CREDIT_CODE", companyCode);
            }
            if (!ValidationUtil.isEmpty(type) && type.contains("个人主体")) {
                map.put("USE_UNIT_CREDIT_CODE", companyCode);
            }
        }

        // 默认条件【STATUS==="" || null】
        BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
        meBuilder.should(QueryBuilders.matchQuery("STATUS", "已认领"));
        meBuilder.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("STATUS")));
        meBuilder.should(QueryBuilders.boolQuery().must(QueryBuilders.matchPhraseQuery("STATUS", "")));
        meBuilder.minimumShouldMatch(1);
        boolMust.must(meBuilder);

        // DATA_SOURCE 为“jg”开头的数据（从监管新加或复制的设备）
        // 20240314 提出的监管业务不要让企业用户选到之前一码通认领或补录的设备，让从监管业务中去新增
        BoolQueryBuilder dBuilder = QueryBuilders.boolQuery();
        dBuilder.must(QueryBuilders.prefixQuery("DATA_SOURCE", "jg_his"));
        boolMust.must(dBuilder);

        String queryType = map.getString("QUERY_TYPE");
        if (!ObjectUtils.isEmpty(queryType)) {
            // 查询 安装告知【可告知设备列表】【USE_UNIT_CREDIT_CODE=== null ||  ""】
            if (ValidationUtil.equals(queryType, "AZ")) {
                BoolQueryBuilder nullOrEmptyQuery = QueryBuilders.boolQuery()
                        .mustNot(QueryBuilders.wildcardQuery("USE_UNIT_CREDIT_CODE", "*"));
                boolMust.must(nullOrEmptyQuery);
                this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "installNotice");
            } else if (ValidationUtil.equals(queryType, "WB")) {
                // 查询 维保备案【可绑定设备列表】【(EQU_STATE=== null ||  ""）】
                BoolQueryBuilder wbBuilder = QueryBuilders.boolQuery();
                wbBuilder.mustNot(QueryBuilders.existsQuery("EQU_STATE"));
                boolMust.must(wbBuilder);
            } else if (ValidationUtil.equals(queryType, "SY")) {
                // 查询 使用登记【可选设备列表】【(EQU_STATUS=== null || "" ) && (USE_ORG_CODE（使用登记证编号） ==="" || null)】
                BoolQueryBuilder syBuilder = QueryBuilders.boolQuery();
                syBuilder.mustNot(QueryBuilders.existsQuery("EQU_STATE"));
                syBuilder.mustNot(QueryBuilders.wildcardQuery("USE_ORG_CODE", "*"));
                boolMust.must(syBuilder);
                this.setRepeatUsedCheckFilterParam(boolMust, companyCode, "useRegister");
            } else if (ValidationUtil.equals(queryType, "FINISH_SY")) {
                // 注意：上面条件是过滤出【未做过】某个业务的设备，下面部分是过滤出【做过】某个业务的设备
                // 查询 已经做过【使用登记】 的设备 【(EQU_STATUS != 空 ) && (USE_ORG_CODE（使用登记证编号） != 空)】
                BoolQueryBuilder syBuilder = QueryBuilders.boolQuery();
                syBuilder.must(QueryBuilders.existsQuery("EQU_STATE"))
                        .must(QueryBuilders.wildcardQuery("USE_ORG_CODE", "*"));
                boolMust.must(syBuilder);
            } else if (ValidationUtil.equals(queryType, "GZ_GZ") || ValidationUtil.equals(queryType, "GZ_WX") || ValidationUtil.equals(queryType, "GZ_YZ")) {
                BoolQueryBuilder syBuilder = QueryBuilders.boolQuery();
                syBuilder.must(QueryBuilders.existsQuery("EQU_STATE"));
                syBuilder.must(QueryBuilders.wildcardQuery("USE_ORG_CODE", "*"));
                boolMust.must(syBuilder);
            }
        }

        // 通用匹配规则，其他条件构建
        if (!ObjectUtils.isEmpty(map.getString(SEQUENCE_NBR))) {
            BoolQueryBuilder seqBuilder = QueryBuilders.boolQuery();
            String param = map.getString(SEQUENCE_NBR);
            List<String> strings = Arrays.asList(param.split(","));
            seqBuilder.must(QueryBuilders.termsQuery("SEQUENCE_NBR.keyword", strings));
            boolMust.must(seqBuilder);
        }

        if (!ObjectUtils.isEmpty(map.getString(IS_INTO_MANAGEMENT))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String param = QueryParser.escape(map.getString(IS_INTO_MANAGEMENT));
            pBuilder.must(QueryBuilders.matchQuery(IS_INTO_MANAGEMENT, param));
            boolMust.must(pBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString(EQU_CATEGORY))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String param = QueryParser.escape(map.getString(EQU_CATEGORY));
            pBuilder.must(QueryBuilders.matchPhraseQuery(EQU_CATEGORY, "*" + param + "*"));
            boolMust.must(pBuilder);

        }
        if (!ObjectUtils.isEmpty(map.getString("USE_PLACE"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String param = QueryParser.escape(map.getString("USE_PLACE"));
            pBuilder.must(QueryBuilders.matchPhraseQuery("USE_PLACE", "*" + param + "*"));
            boolMust.must(pBuilder);
        }
        // 设备状态
        if (!ObjectUtils.isEmpty(map.getString("EQU_STATE"))) {
            BoolQueryBuilder esBuilder = QueryBuilders.boolQuery();
            String param = QueryParser.escape(map.getLong("EQU_STATE").toString());
            esBuilder.must(QueryBuilders.matchQuery("EQU_STATE", param));
            boolMust.must(esBuilder);
        }

        // 使用单位 //安装改造维修单位
        if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_CREDIT_CODE")) && !ObjectUtils.isEmpty(map.getString("USC_UNIT_CREDIT_CODE"))) {
            BoolQueryBuilder ubuilder = QueryBuilders.boolQuery();
            String useCode = QueryParser.escape(map.getString("USE_UNIT_CREDIT_CODE"));
            useCode = useCode.contains("_") ? useCode.split("_")[0] : useCode;
            ubuilder.should(QueryBuilders.matchQuery("USE_UNIT_CREDIT_CODE", useCode));

            String uscCode = QueryParser.escape(map.getString("USC_UNIT_CREDIT_CODE")).toLowerCase();
            ubuilder.should(QueryBuilders.wildcardQuery("USC_UNIT_CREDIT_CODE", "*" + uscCode + "*"));
            ubuilder.minimumShouldMatch(1);
            boolMust.must(ubuilder);
        } else {
            if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_CREDIT_CODE")) || !ObjectUtils.isEmpty(map.getString("useUnitCreditCode"))) {
                BoolQueryBuilder uuccBuilder = QueryBuilders.boolQuery();
                String uucc = !ValidationUtil.isEmpty(map.getString("USE_UNIT_CREDIT_CODE")) ? map.getString("USE_UNIT_CREDIT_CODE") : map.getString("useUnitCreditCode");
                String param = QueryParser.escape(uucc);
                param = param.contains("_") ? param.split("_")[0] : param;
                uuccBuilder.must(QueryBuilders.matchQuery("USE_UNIT_CREDIT_CODE", param));
                boolMust.must(uuccBuilder);
            }
            if (!ObjectUtils.isEmpty(map.getString("USC_UNIT_CREDIT_CODE"))) {
                BoolQueryBuilder uuccBuilder = QueryBuilders.boolQuery();
                String uscCode = QueryParser.escape(map.getString("USC_UNIT_CREDIT_CODE")).toLowerCase();
                uuccBuilder.must(QueryBuilders.wildcardQuery("USC_UNIT_CREDIT_CODE", "*" + uscCode + "*"));
                boolMust.must(uuccBuilder);
            }
        }

        // 监管码
        if (!ObjectUtils.isEmpty(map.getString("SUPERVISORY_CODE"))) {
            BoolQueryBuilder scBuilder = QueryBuilders.boolQuery();
            String param = map.getString("SUPERVISORY_CODE");
            List<String> strings = Arrays.asList(param.split(","));
            scBuilder.must(QueryBuilders.termsQuery("SUPERVISORY_CODE", strings));
            boolMust.must(scBuilder);
        }
        // 设备种类编码
        if (!ObjectUtils.isEmpty(map.getString("EQU_LIST_CODE"))) {
            BoolQueryBuilder elcBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_LIST_CODE"));
            elcBuilder.must(QueryBuilders.matchPhraseQuery("EQU_LIST_CODE", test));
            boolMust.must(elcBuilder);
        }
        // 设备类别编码
        if (!ObjectUtils.isEmpty(map.getString("EQU_DEFINE_CODE"))) {
            BoolQueryBuilder elcBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_DEFINE_CODE"));
            elcBuilder.must(QueryBuilders.matchPhraseQuery("EQU_DEFINE_CODE", test));
            boolMust.must(elcBuilder);
        }
        // 设备种类名称
        if (!ObjectUtils.isEmpty(map.getString(EQU_LIST))) {
            BoolQueryBuilder elBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(EQU_LIST));
            elBuilder.must(QueryBuilders.matchPhraseQuery(EQU_LIST, "*" + test + "*"));
            boolMust.must(elBuilder);
        }

        // 设备类别
        if (!ObjectUtils.isEmpty(map.getString("EQU_CATEGORY_CODE"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_CATEGORY_CODE"));
            pBuilder.must(QueryBuilders.termQuery("EQU_CATEGORY_CODE", test));
            boolMust.must(pBuilder);
        }
        // 是否车用气瓶
        if (!ObjectUtils.isEmpty(map.getString(WHETHER_VEHICLE_CYLINDER))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(WHETHER_VEHICLE_CYLINDER));
            pBuilder.must(QueryBuilders.termQuery(WHETHER_VEHICLE_CYLINDER, test));
            boolMust.must(pBuilder);
        }
        // 是否撬装式压力容器
        if (!ObjectUtils.isEmpty(map.getString(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL)) && !"0".equals(map.getString(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL));
            pBuilder.must(QueryBuilders.termQuery(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL, test));
            boolMust.must(pBuilder);
        }
        // 设备代码模糊查询
        if (!ObjectUtils.isEmpty(map.getString(EQU_CODE))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(EQU_CODE));
            pBuilder.must(QueryBuilders.wildcardQuery(EQU_CODE, "*" + test.toLowerCase() + "*"));
            boolMust.must(pBuilder);
        }
        // 单位内部编号模糊查询
        if (!ObjectUtils.isEmpty(map.getString("USE_INNER_CODE"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_INNER_CODE"));
            pBuilder.must(QueryBuilders.wildcardQuery("USE_INNER_CODE", "*" + test.toLowerCase() + "*"));
            boolMust.must(pBuilder);
        }
        // 出厂编号/产品编码模糊查询
        if (!ObjectUtils.isEmpty(map.getString(FACTORY_NUM))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(FACTORY_NUM));
            pBuilder.must(QueryBuilders.wildcardQuery(FACTORY_NUM, "*" + test.toLowerCase() + "*"));
            boolMust.must(pBuilder);
        }
        // 制造单位（生产单位）名称模糊查询
        if (!ObjectUtils.isEmpty(map.getString("PRODUCE_UNIT_NAME"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("PRODUCE_UNIT_NAME"));
            pBuilder.must(QueryBuilders.wildcardQuery("PRODUCE_UNIT_NAME", "*" + test.toLowerCase() + "*"));
            boolMust.must(pBuilder);
        }
        builder.query(boolMust);
        builder.sort("REC_DATE", SortOrder.DESC);
        builder.from((pageNumber - 1) * size);
        builder.size(size);
        request.source(builder);
        List<JSONObject> list = new LinkedList<>();
        long totle = 0;
        if (log.isDebugEnabled()) {
            log.debug("查询es 的查询条件: {}", request);
        }
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (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(CONSTRUCTIONTYPE))) {
                    // 转化施工类型
                    String constructionType = dto2.get(CONSTRUCTIONTYPE).toString();
                    if (!ValidationUtil.isEmpty(constructionType)) {
                        List<String> constructionTypeList = Arrays.asList(constructionType.split(","));
                        List<String> statusList = new ArrayList<>();
                        for (String cType : constructionTypeList) {
                            Integer integer = Integer.valueOf(cType);
                            String status = ConstructionEnum.getName.get(integer);
                            statusList.add(status);
                        }
                        dto2.put(CONSTRUCTIONTYPE, Joiner.on(",").join(statusList));
                    }
                }
                if (!ValidationUtil.isEmpty(dto2.get(EQUSTATE))) {
                    Integer integer = Integer.valueOf(dto2.get(EQUSTATE).toString());
                    String status = EquimentEnum.getName.get(integer);
                    dto2.put(EQUSTATE, status);
                }
                if (!ValidationUtil.isEmpty(dto2.get(DATA_SOURCE))) {
                    String s = dto2.get(DATA_SOURCE).toString();
                    dto2.put(DATA_SOURCE, s);
                    dto2.put(DATA_SOURCE_NAME, Arrays.stream(EquipSourceEnum.values())
                            .filter(e -> s.startsWith(e.getCode()))
                            .map(EquipSourceEnum::getName)
                            .findFirst()
                            .orElse(EquipSourceEnum.jg.getName()));
                }
                dto2.put("record", dto2.get(SEQUENCE_NBR));
                list.add(dto2);
            }
            // 获取所有设备的Id
            List<String> equIds = null;
            if (!ValidationUtil.isEmpty(list)) {
                equIds = list.stream().map(item -> item.get(SEQUENCE_NBR).toString()).collect(Collectors.toList());
            }
            if (!ValidationUtil.isEmpty(equIds)) {
                // 查询设备地址
                List<IdxBizJgUseInfo> useInfoListByEquIds = idxBizJgUseInfoService.getUseInfoListByEquIds(equIds);
                Map<String, String> equAddressMap = new HashMap<>();
                if (!ValidationUtil.isEmpty(useInfoListByEquIds)) {
                    equAddressMap = useInfoListByEquIds.stream().collect(Collectors.toMap(IdxBizJgUseInfo::getRecord,
                                    useInfo -> {
                                        String fulladdress = "";
                                        if (!ValidationUtil.isEmpty(useInfo.getProvinceName())) {
                                            fulladdress += useInfo.getProvinceName();
                                        }
                                        if (!ValidationUtil.isEmpty(useInfo.getCityName())) {
                                            fulladdress += useInfo.getCityName();
                                        }
                                        if (!ValidationUtil.isEmpty(useInfo.getCountyName())) {
                                            fulladdress += useInfo.getCountyName();
                                        }
                                        if (!ValidationUtil.isEmpty(useInfo.getStreetName())) {
                                            fulladdress += useInfo.getStreetName();
                                        }
                                        if (!ValidationUtil.isEmpty(useInfo.getAddress())) {
                                            fulladdress += useInfo.getAddress();
                                        }
                                        return fulladdress;
                                    }
                            )
                    );
                }
                // 更新设备使用情况和设备地址
                for (JSONObject item : list) {
                    String fullAddress = equAddressMap.get(item.getString(SEQUENCE_NBR));
                    item.put("ADDRESS", !ValidationUtil.isEmpty(fullAddress) ? fullAddress : "");
                    item.put("CAN_EDIT", this.checkEquipIsCanEdit(item.getString(SEQUENCE_NBR)));
                    item.put("CAN_DELETE", this.checkEquipIsCanDelete(item.getString(SEQUENCE_NBR)));
                }
            }
            totle = response.getInternalResponse().hits().getTotalHits().value;
            result.setRecords(list);
            result.setTotal(totle);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 设置安装告知使用的设备不能包括正在进行中的流程
     *
     * @param boolMust
     * @param companyCode
     */
    private void setRepeatUsedCheckFilterParam(BoolQueryBuilder boolMust, String companyCode, String bizType) {
        Set<String> records = EquipUsedCheckStrategyContext.getUsedStrategy(bizType).getEquipInFlow(companyCode);
        if (records != null && !records.isEmpty()) {
            boolMust.mustNot(QueryBuilders.termsQuery("SEQUENCE_NBR.keyword", records));
        }
    }

    /**
     * 获取当前登录人单位类型
     *
     * @return
     */
    public JSONObject getCompanyType() {

        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        CompanyBo company = reginParams.getCompany();

        JSONObject object = new JSONObject();
        if (!ValidationUtil.isEmpty(company)) {
            object.put("level", company.getLevel());
            object.put("orgCode", company.getOrgCode());
            object.put("companyName", company.getCompanyName());
            object.put("companyCode", company.getCompanyCode());
            object.put("companyType", company.getCompanyType());
        }
        return object;
    }

    /**
     * 获取类型为ZC的“未注册”的字典值
     *
     * @return code
     */
    public String getRegCode() {
        QueryWrapper<DataDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "ZC");
        queryWrapper.eq("name", "未注册");
        queryWrapper.eq("is_delete", false);
        List<DataDictionary> list = iDataDictionaryService.list(queryWrapper);
        if (!list.isEmpty() && list.get(0) != null) {
            DataDictionary dictionary = list.get(0);
            return Optional.ofNullable(dictionary).map(DataDictionary::getCode).orElse("");
        }
        return "";
    }

    private String batchSubmitOrUpdate(LinkedHashMap equipmentClassForm, LinkedHashMap equipmentInfoForm, LinkedHashMap equipmentParamsForm) {
        Date date = new Date();
        String record = null;

        // 设备种类
        String equList = String.valueOf(equipmentClassForm.get(EQU_LIST));
        // 设备类别
        String equCategory = String.valueOf(equipmentClassForm.get(EQU_CATEGORY));
        // 设备品种
        String equDefine = String.valueOf(equipmentClassForm.get(EQU_DEFINE));
        // 业务场景
        String businessScenarios = String.valueOf(equipmentClassForm.get(BUSINESS_SCENARIOS));
        // 数据来源 历史数据his 新数据new
        String equipSource = String.valueOf(equipmentClassForm.get(DATA_SOURCE));

        // 操作类型
        String operateType = ValidationUtil.isEmpty(equipmentInfoForm.get(SEQUENCE_NBR)) ? OPERATESAVE : OPERATEEDIT;
        // 设备是否复制而来，复制来的设备走新增
        boolean isCopy = !ValidationUtil.isEmpty(equipmentInfoForm.get(IS_COPY));
        operateType = isCopy ? OPERATESAVE : operateType;
        // 新增设备保存时 : 历史设备=》dataSource为"his" jg新录入设备dataSource为"jg"
        String dataSource = OPERATESAVE.equals(operateType) ? ("new".equals(equipSource) ? "jg" : "jg_his") : equipmentInfoForm.get("DATA_SOURCE").toString();
        if (isCopy) {
            String sourceRecord = equipmentClassForm.get(RECORD).toString();
//            dataSource = "new".equals(equipSource) ? ("jg_" + sourceRecord) : ("jg_his_" + sourceRecord);
            // bug-21203
            if (equipmentInfoForm.containsKey("DATA_SOURCE")) {
                String dataSourceCopy = equipmentInfoForm.get("DATA_SOURCE").toString();
                if (dataSourceCopy.startsWith("jg_his")) {
                    dataSource = "jg_his_" + sourceRecord;
                } else {
                    dataSource = "jg_" + sourceRecord;
                }
            } else {
                throw new BadRequest("数据异常,请联系管理员");
            }
        }
        record = OPERATESAVE.equals(operateType) ? UUID.randomUUID().toString() : equipmentInfoForm.get(RECORD).toString();

        // 单位类型
        Map<String, Object> companyInfoMap = jgInstallationNoticeService.getCompanyType();
        String companyTypeStr = companyInfoMap.get("companyType").toString();

        // 使用信息
        IdxBizJgUseInfo useInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgUseInfo.class);
        // 设计信息
        IdxBizJgDesignInfo designInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgDesignInfo.class);
        // 制造信息
        IdxBizJgFactoryInfo factoryInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgFactoryInfo.class);
        // 施工信息
        IdxBizJgConstructionInfo constructionInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgConstructionInfo.class);
        // 注册登记信息
        IdxBizJgRegisterInfo registerInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgRegisterInfo.class);
        // 维保备案
        IdxBizJgMaintenanceRecordInfo maintenanceRecordInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgMaintenanceRecordInfo.class);
        // 监督管理
        IdxBizJgSupervisionInfo supervisionInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgSupervisionInfo.class);
        // 其他信息
        IdxBizJgOtherInfo otherInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgOtherInfo.class);

        // 使用信息
        useInfo.setRecord(record);
        useInfo.setRecDate(date);
        useInfo.setDataSource(dataSource);
        useInfo.setIsIntoManagement(Boolean.FALSE);
        useInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("USEINFO_SEQ")));
        if (companyTypeStr.contains(CompanyTypeEnum.USE.getCode()) || companyTypeStr.contains(CompanyTypeEnum.INDIVIDUAL.getCode())) {
            useInfo.setUseUnitCreditCode(companyInfoMap.get("creditCode").toString());
            useInfo.setUseUnitName(companyInfoMap.get("companyName").toString());
        }

        if (isCopy) {
            // 设备状态置空
            useInfo.setEquState(null);
            // 如果为安改维单位复制设备，则将使用单位信息置空
            if (companyTypeStr.equals(CompanyTypeEnum.CONSTRUCTION.getCode())) {
                useInfo.setUseUnitCreditCode(null);
                useInfo.setUseUnitName(null);
            }
            // 如果既为安改维单位又是使用单位，则将厂车、起重机械-流动式起重机、压力容器-气瓶安改维单位信息置空
            if (companyTypeStr.contains(CompanyTypeEnum.CONSTRUCTION.getCode()) && companyTypeStr.contains(CompanyTypeEnum.USE.getCode())) {
                if (!registerInfo.getEquList().equals("5000") && !registerInfo.getEquCategory().equals("4400") && !registerInfo.getEquCategory().equals("2300")) {
                    constructionInfo.setUscUnitCreditCode(null);
                    constructionInfo.setUscUnitName(null);
                }
            }
        }

        idxBizJgUseInfoService.saveOrUpdateData(useInfo);

        // 设计信息
        designInfo.setRecord(record);
        designInfo.setRecDate(date);
        designInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("DESIGNINFO_SEQ")));
        iIdxBizJgDesignInfoService.saveOrUpdateData(designInfo);

        // 制造信息
        factoryInfo.setRecord(record);
        factoryInfo.setRecDate(date);
        factoryInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("FACTORYINFO_SEQ")));
        iIdxBizJgFactoryInfoService.saveOrUpdateData(factoryInfo);

        // 施工信息
        String companyName = companyInfoMap.get("companyName").toString();
        String companyCode = companyInfoMap.get("creditCode").toString();
        constructionInfo.setRecord(record);
        constructionInfo.setRecDate(date);

        if (companyTypeStr.contains(CompanyTypeEnum.CONSTRUCTION.getCode())) {
            constructionInfo.setUscUnitCreditCode(companyCode);
            constructionInfo.setUscUnitName(companyName);
        }

        if (isCopy) {
            if (companyTypeStr.equals(CompanyTypeEnum.USE.getCode()) || companyTypeStr.equals(CompanyTypeEnum.INDIVIDUAL.getCode())) {
                constructionInfo.setUscUnitCreditCode(null);
                constructionInfo.setUscUnitName(null);
            }
            // 如果既为安改维单位又是使用单位，则将厂车、起重机械-流动式起重机、压力容器-气瓶安改维单位信息置空
            if (companyTypeStr.contains(CompanyTypeEnum.CONSTRUCTION.getCode()) && companyTypeStr.contains(CompanyTypeEnum.USE.getCode())) {
                if (registerInfo.getEquList().equals("5000") || registerInfo.getEquCategory().equals("4400") || registerInfo.getEquCategory().equals("2300")) {
                    constructionInfo.setUscUnitCreditCode(null);
                    constructionInfo.setUscUnitName(null);
                }
            }
        }

        constructionInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("CONSTRUCTIONINFO_SEQ")));
        iIdxBizJgConstructionInfoService.saveOrUpdateData(constructionInfo);

        // 注册登记
        registerInfo.setRecord(record);
        registerInfo.setRecDate(date);
        registerInfo.setRegisterState(this.getRegCode());
        registerInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("REGISTERINFO_SEQ")));
        // 补丁：saveOrUpdate在update数据时不会更新字段为null的字段，但是编辑设备的代码时，从有改成无，equCode解析成null，但是此时需要将equcode删掉
        registerInfo.setEquCode(ObjectUtils.isEmpty(registerInfo.getEquCode()) ? "" : registerInfo.getEquCode());
        // copy设备 =》 使用登记证号置空
        registerInfo.setUseOrgCode(isCopy ? null : registerInfo.getUseOrgCode());
        this.saveOrUpdate(registerInfo);

        // 维保备案
        maintenanceRecordInfo.setRecord(record);
        maintenanceRecordInfo.setRecDate(date);
        maintenanceRecordInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("MAINTENANCERECORDINFO_SEQ")));
        iIdxBizJgMaintenanceRecordInfoService.saveOrUpdateData(maintenanceRecordInfo);

        // 监督管理
        supervisionInfo.setRecord(record);
        supervisionInfo.setRecDate(date);
        supervisionInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("SUPERVISIONINFO_SEQ")));
        iIdxBizJgSupervisionInfoService.saveOrUpdateData(supervisionInfo);

        // 其他信息
        otherInfo.setRecord(record);
        otherInfo.setRecDate(date);
        otherInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("OTHERINFO_SEQ")));
        if (isCopy) {
            // 96333码和监管码置空
            otherInfo.setCode96333(null);
            otherInfo.setSupervisoryCode(null);
        }
        iIdxBizJgOtherInfoService.saveOrUpdateData(otherInfo);

        if (CylinderTypeEnum.CYLINDER.getCode().equals(equCategory) || "2100".equals(equCategory)) {
            IdxBizJgInspectionDetectionInfo inspectionDetectionInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgInspectionDetectionInfo.class);
            List<Map<String, Object>> inspectionAndTestingInstitutions = commonMapper.getUnitListByType(INSPECTION_AND_TESTING_INSTITUTIONS);
            Optional<Map<String, Object>> optional = inspectionAndTestingInstitutions.stream().filter(x -> x.get("useCode").equals(inspectionDetectionInfo.getInspectOrgCode())).findFirst();
            Map<String, Object> mapOrDefault = optional.orElse(Collections.emptyMap());
            inspectionDetectionInfo.setInspectOrgName((String) mapOrDefault.getOrDefault("useUnit", inspectionDetectionInfo.getInspectOrgName()));
            inspectionDetectionInfo.setRecord(record);
            inspectionDetectionInfo.setRecDate(date);
            inspectionDetectionInfo.setInspectType("ZZJDJY");
            inspectionDetectionInfo.setInspectConclusion("6040");
            inspectionDetectionInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("INSPECTIONDETECTIONINFO_SEQ")));
            iIdxBizJgInspectionDetectionInfoService.saveOrUpdateData(inspectionDetectionInfo);
        }

        // 八大类技术参数和主要零部件和安全附件表
        List<IdxBizJgMainParts> mainPartsList = new ArrayList<>();
        List<IdxBizJgProtectionDevices> protectionDevicesList = new ArrayList<>();

        // 电梯
        if (EquipmentClassifityEnum.DT.getCode().equals(equList)) {
            IdxBizJgTechParamsElevator elevator = JSON.parseObject(JSON.toJSONString(equipmentParamsForm), IdxBizJgTechParamsElevator.class);
            if (!ValidationUtil.isEmpty(elevator)) {
                elevator.setRecord(record);
                elevator.setRecDate(date);
                elevator.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentParamsForm.get("ELEVATOR_SEQ")));
                iIdxBizJgTechParamsElevatorService.saveOrUpdateData(elevator);
            }
        }
        // 厂车
        else if (EquipmentClassifityEnum.CC.getCode().equals(equList)) {
            IdxBizJgTechParamsVehicle vehicle = JSON.parseObject(JSON.toJSONString(equipmentParamsForm), IdxBizJgTechParamsVehicle.class);
            if (!ValidationUtil.isEmpty(vehicle)) {
                vehicle.setRecord(record);
                vehicle.setRecDate(date);
                vehicle.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentParamsForm.get("VEHICLE_SEQ")));
                iIdxBizJgTechParamsVehicleService.saveOrUpdateData(vehicle);
            }

            // 主要零部件
            List<String> subFormMainPartsList = new ArrayList<>();
            subFormMainPartsList.add("subForm_sey164b51a");
            subFormMainPartsList.add("subForm_tef7yf5fbr");
            mainPartsList = this.getAccessoryEntity(equipmentParamsForm, subFormMainPartsList, EQUIP_MAINPARTS_FORM_ID, record, date, operateType);

        }
        // 索道
        else if (EquipmentClassifityEnum.KYSD.getCode().equals(equList)) {
            IdxBizJgTechParamsRopeway ropeway = JSON.parseObject(JSON.toJSONString(equipmentParamsForm), IdxBizJgTechParamsRopeway.class);
            if (!ValidationUtil.isEmpty(ropeway)) {
                ropeway.setRecord(record);
                ropeway.setRecDate(date);
                ropeway.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentParamsForm.get("ROPEWAY_SEQ")));
                iIdxBizJgTechParamsRopewayService.saveOrUpdateData(ropeway);
            }

            // 主要零部件
            List<String> subFormMainPartsList = new ArrayList<>();
            subFormMainPartsList.add("subForm_5fi0jewuyh");
            mainPartsList = this.getAccessoryEntity(equipmentParamsForm, subFormMainPartsList, EQUIP_MAINPARTS_FORM_ID, record, date, operateType);

        }
        // 游乐设施
        else if (EquipmentClassifityEnum.YLSS.getCode().equals(equList)) {
            IdxBizJgTechParamsRides rides = JSON.parseObject(JSON.toJSONString(equipmentParamsForm), IdxBizJgTechParamsRides.class);
            if (!ValidationUtil.isEmpty(rides)) {
                rides.setRecord(record);
                rides.setRecDate(date);
                rides.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentParamsForm.get("RIDES_SEQ")));
                iIdxBizJgTechParamsRidesService.saveOrUpdateData(rides);
            }
        }
        // 锅炉
        else if (EquipmentClassifityEnum.GL.getCode().equals(equList)) {
            IdxBizJgTechParamsBoiler boiler = JSON.parseObject(JSON.toJSONString(equipmentParamsForm), IdxBizJgTechParamsBoiler.class);
            if (!ValidationUtil.isEmpty(boiler)) {
                boiler.setRecord(record);
                boiler.setRecDate(date);
                boiler.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentParamsForm.get("BOILER_SEQ")));
                iIdxBizJgTechParamsBoilerService.saveOrUpdateData(boiler);
            }

            // 主要零部件
            List<String> subFormMainPartsList = new ArrayList<>();
            subFormMainPartsList.add("subForm_1hh88r4m69");
            mainPartsList = this.getAccessoryEntity(equipmentParamsForm, subFormMainPartsList, EQUIP_MAINPARTS_FORM_ID, record, date, operateType);
        }
        // 压力容器
        else if (EquipmentClassifityEnum.YLRQ.getCode().equals(equList)) {
            IdxBizJgTechParamsVessel vessel = JSON.parseObject(JSON.toJSONString(equipmentParamsForm), IdxBizJgTechParamsVessel.class);
            if (!ValidationUtil.isEmpty(vessel)) {
                vessel.setRecord(record);
                vessel.setRecDate(date);
                vessel.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentParamsForm.get("VESSEL_SEQ")));
                iIdxBizJgTechParamsVesselService.saveOrUpdateData(vessel);
            }

            // 主要零部件
            List<String> subFormMainPartsList = new ArrayList<>();
            subFormMainPartsList.add("subForm_fie04854f2");
            mainPartsList = this.getAccessoryEntity(equipmentParamsForm, subFormMainPartsList, EQUIP_MAINPARTS_FORM_ID, record, date, operateType);

            // 安全附件
            List<String> subFormProtectionDevicesList = new ArrayList<>();
            subFormProtectionDevicesList.add("subForm_d4xdzhsgdj");
            protectionDevicesList = this.getAccessoryEntity(equipmentParamsForm, subFormProtectionDevicesList, EQUIP_PROTECTIONDEVICES_FORM_ID, record, date, operateType);

        }
        // 压力管道
        else if (EquipmentClassifityEnum.YLGD.getCode().equals(equList)) {
            IdxBizJgTechParamsPipeline pipeline = JSON.parseObject(JSON.toJSONString(equipmentParamsForm), IdxBizJgTechParamsPipeline.class);
            if (!ValidationUtil.isEmpty(pipeline)) {
                pipeline.setRecord(record);
                pipeline.setRecDate(date);
                pipeline.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentParamsForm.get("PIPELINE_SEQ")));
                iIdxBizJgTechParamsPipelineService.saveOrUpdateData(pipeline);
            }

            // 主要零部件
            List<String> subFormMainPartsList = new ArrayList<>();
            subFormMainPartsList.add("subForm_9n7nu55z8r");
            mainPartsList = this.getAccessoryEntity(equipmentParamsForm, subFormMainPartsList, EQUIP_MAINPARTS_FORM_ID, record, date, operateType);

        }
        // 起重机械
        else if (EquipmentClassifityEnum.QZJX.getCode().equals(equList)) {
            IdxBizJgTechParamsLifting lifting = JSON.parseObject(JSON.toJSONString(equipmentParamsForm), IdxBizJgTechParamsLifting.class);
            if (!ValidationUtil.isEmpty(lifting)) {
                lifting.setRecord(record);
                lifting.setRecDate(date);
                lifting.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentParamsForm.get("LIFTING_SEQ")));
                iIdxBizJgTechParamsLiftingService.saveOrUpdateData(lifting);
            }

            // 主要零部件
            List<String> subFormMainPartsList = new ArrayList<>();
            subFormMainPartsList.add("subForm_bqirdyvztt");
            mainPartsList = this.getAccessoryEntity(equipmentParamsForm, subFormMainPartsList, EQUIP_MAINPARTS_FORM_ID, record, date, operateType);

            // 安全附件
            List<String> subFormProtectionDevicesList = new ArrayList<>();
            subFormProtectionDevicesList.add("subForm_29yy3pdzhl");
            subFormProtectionDevicesList.add("subForm_h5h4x0zhur");
            protectionDevicesList = this.getAccessoryEntity(equipmentParamsForm, subFormProtectionDevicesList, EQUIP_PROTECTIONDEVICES_FORM_ID, record, date, operateType);

        }

        // 八大类技术参数和主要零部件和安全附件表
        if (!ValidationUtil.isEmpty(mainPartsList)) {
            iIdxBizJgMainPartsService.saveOrUpdateBatchData(mainPartsList);
        }
        if (!ValidationUtil.isEmpty(protectionDevicesList)) {
            iIdxBizJgProtectionDevicesService.saveOrUpdateBatchData(protectionDevicesList);
        }
        return record;
    }

    public void checkEsData(String id) {
        Map<String, Object> map = categoryOtherInfoMapper.selectDataById(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);
        }
    }

    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 (EQUIP_MAINPARTS_FORM_ID.equals(subFormType) && !ValidationUtil.isEmpty(list)) {
            for (Object s : list) {
                List subFormMainPartsList = (ArrayList) map.get(s);
                if (!ObjectUtils.isEmpty(subFormMainPartsList)) {
                    for (Object obj : subFormMainPartsList) {
                        HashMap<String, Object> objMap = (HashMap<String, Object>) obj;
                        IdxBizJgMainParts mainParts = JSON.parseObject(JSON.toJSONString(objMap), IdxBizJgMainParts.class);
                        mainParts.setRecord(record);
                        mainParts.setRecDate(date);
                        mainParts.setSequenceNbr("save".equals(type) ? null : String.valueOf(objMap.get("MAINPARTS_SEQ")));
                        mainPartsList.add(mainParts);
                    }
                }
            }
            return mainPartsList;
        } else if (EQUIP_PROTECTIONDEVICES_FORM_ID.equals(subFormType) && !ValidationUtil.isEmpty(list)) {
            for (Object s : list) {
                List subFormProtectionDevicesList = (ArrayList) map.get(s);
                if (!ObjectUtils.isEmpty(subFormProtectionDevicesList)) {
                    for (Object obj : subFormProtectionDevicesList) {
                        HashMap<String, Object> objMap = (HashMap<String, Object>) obj;
                        IdxBizJgProtectionDevices protectionDevices = JSON.parseObject(JSON.toJSONString(objMap), IdxBizJgProtectionDevices.class);
                        protectionDevices.setRecord(record);
                        protectionDevices.setRecDate(date);
                        protectionDevices.setSequenceNbr("save".equals(type) ? null : String.valueOf(objMap.get("PROTECTIONDEVICES_SEQ")));
                        protectionDevicesList.add(protectionDevices);
                    }
                }
            }
            return protectionDevicesList;
        }
        return null;
    }

    @Override
    public Page<JSONObject> queryForUnitEquipmentPage(JSONObject jsonObject) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String useUnitCreditCode = reginParams.getCompany().getCompanyCode();
        // 使用单位为个人时候 特殊处理
        if (useUnitCreditCode.split("_").length > 1) {
            useUnitCreditCode = useUnitCreditCode.split("_")[1];
        }
        jsonObject.put("useUnitCreditCode", useUnitCreditCode);
        Page<JSONObject> page = new Page<>(jsonObject.getLong("number"), jsonObject.getLong("size"));
        Set<String> records = EquipUsedCheckStrategyContext.getUsedStrategy("useRegister").getEquipInFlow(useUnitCreditCode);
        if ("8300".equals(jsonObject.get("EQU_CATEGORY_CODE"))) {// 管道
            return jgUseRegistrationMapper.queryForUnitPipelineEquipmentPage(page, jsonObject, records);
        } else if ("2300".equals(jsonObject.get("EQU_CATEGORY_CODE"))) {// 气瓶
            List<DictionarieValueModel> fillingMedium = Systemctl.dictionarieClient.dictValues("FILLING_MEDIUM").getResult();
            Map<String, Object> fillingMediumMap = fillingMedium.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataValue));
            Page<JSONObject> result = jgUseRegistrationMapper.queryForUnitVesselEquipmentPage(page, jsonObject, records);
            result.getRecords().forEach(i -> {
                i.put("chargingMedium", fillingMediumMap.get(i.get("chargingMedium")));
            });
            return result;
        }
        return page;
    }

    @Override
    public Page<JSONObject> queryEquipCanUsedByVesselPage(JSONObject jsonObject) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String useUnitCreditCode = reginParams.getCompany().getCompanyCode();
        // 使用单位为个人时候 特殊处理
        if (useUnitCreditCode.split("_").length > 1) {
            useUnitCreditCode = useUnitCreditCode.split("_")[1];
        }
        jsonObject.put("useUnitCreditCode", useUnitCreditCode);
        Page<JSONObject> page = new Page<>(jsonObject.getLong("number"), jsonObject.getLong("size"));
        List<DictionarieValueModel> fillingMedium = Systemctl.dictionarieClient.dictValues("FILLING_MEDIUM").getResult();
        Map<String, Object> fillingMediumMap = fillingMedium.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataValue));
        Page<JSONObject> result = jgUseRegistrationMapper.queryForEquipUsedByVehiclePage(page, jsonObject);
        result.getRecords().forEach(i -> {
            i.put("chargingMedium", fillingMediumMap.get(i.get("chargingMedium")));
        });
        return result;
    }

    @Override
    public Page<JSONObject> queryEquipCanUsedByVesselPageHistory(JSONObject jsonObject) {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String useUnitCreditCode = reginParams.getCompany().getCompanyCode();
        // 使用单位为个人时候 特殊处理
        if (useUnitCreditCode.split("_").length > 1) {
            useUnitCreditCode = useUnitCreditCode.split("_")[1];
        }
        jsonObject.put("useUnitCreditCode", useUnitCreditCode);
        Page<JSONObject> page = new Page<>(jsonObject.getLong("number"), jsonObject.getLong("size"));
        List<DictionarieValueModel> fillingMedium = Systemctl.dictionarieClient.dictValues("FILLING_MEDIUM").getResult();
        Map<String, Object> fillingMediumMap = fillingMedium.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataValue));
        Page<JSONObject> result = jgUseRegistrationMapper.queryForEquipUsedByVehiclePageHistory(page, jsonObject);
        result.getRecords().forEach(i -> {
            i.put("chargingMedium", fillingMediumMap.get(i.get("chargingMedium")));
        });
        return result;
    }

    @Override
    public String importPressureVesselData(Map<String, Object> paramMap, MultipartFile multipartFile) {
        try {
            PressureVesselListener pressureVesselListener = new PressureVesselListener();
            LinkedHashMap equipmentInfoForm = (LinkedHashMap) checkAndCast(paramMap.get(EQUIP_INFO_FORM_ID));
            injectDependencies(pressureVesselListener, equipmentInfoForm);
            EasyExcel.read(multipartFile.getInputStream(), EquipInfoCylinderExcelDto.class, pressureVesselListener)
                    .headRowNumber(4)
                    .sheet()
                    .doRead();
            return pressureVesselListener.getResult();
        } catch (Exception e) {
            String err = (e.getCause() instanceof BadRequest) ? "模版数据填写有误：" + e.getCause().getMessage() : "导入时出现异常：请联系管理员！";
            throw new BadRequest(err);
        }
    }

    @Override
    public Object importPressureData(MultipartFile multipartFile) throws Exception {
        List<EquipInfoCylinderExcelDto> aircraftList = new ArrayList<>();
        resultError.clear();
        useInnerCodeList.clear();
        equCodeList.clear();
        factoryNumList.clear();
        try {
            EasyExcel.read(multipartFile.getInputStream(), EquipInfoCylinderExcelDto.class, new AnalysisEventListener<EquipInfoCylinderExcelDto>() {
                // 每读取一行就调用该方法
                @Override
                public void invoke(EquipInfoCylinderExcelDto data, AnalysisContext context) {
                    EquipInfoCylinderExcelDto fireExperts = new EquipInfoCylinderExcelDto();
                    BeanUtils.copyProperties(data, fireExperts);
                    resultError.add(checkExcelData(data, context).toString());
                    aircraftList.add(fireExperts);
                    useInnerCodeList.add(data.getUseInnerCode());
                    equCodeList.add(data.getEquCode());
                    factoryNumList.add("0".equals(data.getWhetherVehicleCylinder()) ? data.getFactoryNum() : null);
                }

                // 全部读取完成就调用该方法
                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    if (CollectionUtils.isEmpty(aircraftList)) {
                        log.info("你上传了一个空数据的Excel文档!");
                        resultError.add("你上传了一个空数据的Excel文档!");
                        throw new BadRequest("你上传了一个空数据的Excel文档!");
                    }
                }
            }).headRowNumber(4).sheet().doRead();
            if (resultError.stream().anyMatch(input -> !input.isEmpty())) {
                throw new BadRequest("上传失败！");
            }
            return aircraftList;
        } catch (Exception e) {
            throw new Exception(resultError.stream()
                    .filter(s -> !s.isEmpty())
                    .collect(Collectors.joining("<br/>")));
        }
    }

    private String getUrlByKey(List<Map<String, Object>> dataList, String key) {
        if (dataList == null || dataList.isEmpty()) {
            return null;
        }
        for (Map<String, Object> item : dataList) {
            if (key.equals(item.get("key"))) {
                return JSON.toJSONString(item.get("value"));
            }
        }
        return null;
    }

    @Override
    public Object savePressureVesselData(Map<String, Object> paramMap) {
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        CompanyBo company = reginParams.getCompany();
        List<IdxBizJgUseInfo> useInfoList = new ArrayList<>();
        List<IdxBizJgRegisterInfo> registerInfoList = new ArrayList<>();
        List<IdxBizJgDesignInfo> designInfoList = new ArrayList<>();
        List<IdxBizJgFactoryInfo> factoryInfoList = new ArrayList<>();
        List<IdxBizJgOtherInfo> otherInfoList = new ArrayList<>();
        List<IdxBizJgTechParamsVessel> paramsVesselList = new ArrayList<>();
        List<IdxBizJgInspectionDetectionInfo> inspectionDetectionInfoList = new ArrayList<>();
        List<ESEquipmentCategoryDto> esEquipmentCategoryList = new ArrayList<>();

        if (paramMap == null) {
            throw new IllegalArgumentException("参数Map不能为空");
        }
        LinkedHashMap equipmentInfoForm = (LinkedHashMap) checkAndCast(paramMap.get(EQUIP_INFO_FORM_ID));
        LinkedHashMap attachmentUpload = (LinkedHashMap) checkAndCast(paramMap.get(ATTACHMENT_UPLOAD));
        EquipmentInfoDto equipInfoDto = this.createEquipmentInfoDto(equipmentInfoForm, jgVehicleInformationMapper);
        // 登记证记录表主键
        Long changeRecordId = sequence.nextId();
        List<EquipInfoCylinderExcelDto> equipInfoCylinderExcelDtoList = JSON.parseArray(JSON.toJSONString(attachmentUpload.get(EQU_LISTS)), EquipInfoCylinderExcelDto.class);
        equipInfoCylinderExcelDtoList.forEach(data -> {
            if ("his".equals(equipInfoDto.getDataSource()) && "1".equals(data.getWhetherVehicleCylinder())) {
                throw new BadRequest("车用气瓶历史设备不能批量导入!");
            }
            String record = UUID.randomUUID().toString();
            List<Map<String, Object>> fileDataList = (List<Map<String, Object>>) (data.getFileData());
            String productPhoto = getUrlByKey(fileDataList, "PRODUCT_PHOTO");
            String otherAccessoriesReg = getUrlByKey(fileDataList, "OTHER_ACCESSORIES_REG");
            String designDoc = getUrlByKey(fileDataList, "DESIGN_DOC");
            String designStandard = getUrlByKey(fileDataList, "DESIGN_STANDARD");
            String otherAccessoriesDes = getUrlByKey(fileDataList, "OTHER_ACCESSORIES_DES");
            String productQualityYieldProve = getUrlByKey(fileDataList, "PRODUCT_QUALITY_YIELD_PROVE");
            String factoryStandard = getUrlByKey(fileDataList, "FACTORY_STANDARD");
            String insUseMaintainExplain = getUrlByKey(fileDataList, "INS_USE_MAINTAIN_EXPLAIN");
            String otherAccessoriesFact = getUrlByKey(fileDataList, "OTHER_ACCESSORIES_FACT");
            String factSupervisionInspectionReport = getUrlByKey(fileDataList, "FACT_SUPERVISION_INSPECTION_REPORT");
            // 使用信息
            IdxBizJgUseInfo useInfo = new IdxBizJgUseInfo();
            BeanUtils.copyProperties(data, useInfo);
            useInfo.setRecord(record);
            useInfo.setRecDate(new Date());
            useInfo.setDataSource("his".equals(equipInfoDto.getDataSource()) ? "jg_his" : "jg");// 区分历史设备和新增设备
            useInfo.setEquState(null);
            useInfo.setIsIntoManagement("his".equals(equipInfoDto.getDataSource()));// 历史气瓶导入为已纳管设备
            // 使用单位信息
            if ("个人主体".equals(company.getCompanyType())) {
                useInfo.setUseUnitCreditCode(company.getCompanyCode().split("_")[1]);
                useInfo.setUseUnitName(company.getCompanyName().split("_")[1]);
            } else {
                useInfo.setUseUnitCreditCode(company.getCompanyCode());
                useInfo.setUseUnitName(company.getCompanyName());
            }
            useInfoList.add(useInfo);

            // 设计信息
            IdxBizJgDesignInfo designInfo = new IdxBizJgDesignInfo();
            BeanUtils.copyProperties(data, designInfo);
            designInfo.setRecord(record);
            designInfo.setRecDate(new Date());
            if (data.getDesignDate() != null) {
                designInfo.setDesignDate(DateUtil.parse(data.getDesignDate(), "yyyy-MM-dd"));
            }
            designInfo.setDesignDoc(designDoc);
            designInfo.setDesignStandard(designStandard);
            designInfo.setOtherAccessoriesDes(otherAccessoriesDes);
            designInfoList.add(designInfo);

            // 制造信息
            IdxBizJgFactoryInfo factoryInfo = new IdxBizJgFactoryInfo();
            BeanUtils.copyProperties(data, factoryInfo);
            factoryInfo.setRecord(record);
            factoryInfo.setRecDate(new Date());
            factoryInfo.setProductQualityYieldProve(productQualityYieldProve);
            factoryInfo.setFactoryStandard(factoryStandard);
            factoryInfo.setInsUseMaintainExplain(insUseMaintainExplain);
            factoryInfo.setOtherAccessoriesFact(otherAccessoriesFact);
            factoryInfo.setFactSupervisionInspectionReport(factSupervisionInspectionReport);
            factoryInfo.setProduceDate(DateUtil.parse(data.getProduceDate(), "yyyy-MM-dd"));
            factoryInfo.setImported(Optional.ofNullable(data.getImported()).orElse("0"));
            factoryInfoList.add(factoryInfo);

            // 注册登记
            IdxBizJgRegisterInfo registerInfo = new IdxBizJgRegisterInfo();
            BeanUtils.copyProperties(data, registerInfo);
            registerInfo.setRecord(record);
            registerInfo.setRecDate(new Date());
            registerInfo.setEquCategory(equipInfoDto.getEquCategoryCode());
            registerInfo.setEquDefine(equipInfoDto.getEquDefineCode());
            registerInfo.setEquList(equipInfoDto.getEquListCode());
            registerInfo.setRegisterState(idxBizJgRegisterInfoService.getRegCode());
            registerInfo.setProductPhoto(productPhoto);
            registerInfo.setOtherAccessoriesReg(otherAccessoriesReg);
            registerInfo.setUseOrgCode(equipInfoDto.getUseOrgCode());
            if ("his".equals(equipInfoDto.getDataSource())) {
                registerInfo.setEquCode(this.getEquCode(registerInfo, factoryInfo, equipInfoDto.getReceiveOrgCode()));
            }
            registerInfoList.add(registerInfo);

            // 检验检测
            IdxBizJgInspectionDetectionInfo inspectionDetectionInfo = new IdxBizJgInspectionDetectionInfo();
            BeanUtils.copyProperties(data, inspectionDetectionInfo);
            inspectionDetectionInfo.setInspectOrgCode(data.getInspectOrgCode());
            inspectionDetectionInfo.setRecord(record);
            inspectionDetectionInfo.setRecDate(new Date());
            inspectionDetectionInfo.setInspectType("ZZJDJY");
            inspectionDetectionInfo.setInspectConclusion("6040");// 默认合格
            inspectionDetectionInfo.setInspectDate(DateUtil.parse(data.getInspectDate(), "yyyy-MM-dd"));
            // 根据条件确定增加的年数
            inspectionDetectionInfo.setNextInspectDate(Date.from(
                    LocalDate.parse(data.getInspectDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                            .plusYears(SPECIAL_CYLINDER.getCode().equals(equipInfoDto.getEquDefineCode()) ? 3 : 4)
                            .atStartOfDay(ZoneId.systemDefault())
                            .toInstant()));
            inspectionDetectionInfoList.add(inspectionDetectionInfo);

            // 其他信息
            IdxBizJgOtherInfo otherInfo = new IdxBizJgOtherInfo();
            BeanUtils.copyProperties(data, otherInfo);
            otherInfo.setRecord(record);
            otherInfo.setRecDate(new Date());
            if ("his".equals(equipInfoDto.getDataSource())) {
                otherInfo.setSupervisoryCode(this.getSupervisoryCode(equipInfoDto.getPossession(), registerInfo));
                otherInfo.setClaimStatus("已认领");
            }
            otherInfoList.add(otherInfo);

            // 技术参数
            IdxBizJgTechParamsVessel paramsVessel = new IdxBizJgTechParamsVessel();
            BeanUtils.copyProperties(data, paramsVessel);
            paramsVessel.setRecord(record);
            paramsVessel.setRecDate(new Date());
            paramsVesselList.add(paramsVessel);

            ESEquipmentCategoryDto esEquipmentDto = JSON.parseObject(toJSONString(data), ESEquipmentCategoryDto.class);
            esEquipmentDto.setDATA_SOURCE(useInfo.getDataSource());
            esEquipmentDto.setNEXT_INSPECT_DATE(inspectionDetectionInfo.getNextInspectDate() + "");
            esEquipmentDto.setREC_DATE(System.currentTimeMillis());
            esEquipmentDto.setSEQUENCE_NBR(record);
            esEquipmentDto.setFACTORY_NUM(factoryInfo.getFactoryNum());
            esEquipmentDto.setUSE_INNER_CODE(useInfo.getUseInnerCode());
            esEquipmentDto.setUSE_ORG_CODE(equipInfoDto.getUseOrgCode());
            esEquipmentDto.setIS_INTO_MANAGEMENT("his".equals(equipInfoDto.getDataSource()));
            if ("his".equals(equipInfoDto.getDataSource())) {
                esEquipmentDto.setEQU_CODE(registerInfo.getEquCode());
            }
            esEquipmentDto.setEQU_CATEGORY_CODE(equipInfoDto.getEquCategoryCode());
            esEquipmentDto.setEQU_CATEGORY(equipInfoDto.getEquCategory());
            esEquipmentDto.setEQU_LIST_CODE(equipInfoDto.getEquListCode());
            esEquipmentDto.setEQU_LIST(equipInfoDto.getEquList());
            esEquipmentDto.setEQU_DEFINE_CODE(equipInfoDto.getEquDefineCode());
            esEquipmentDto.setEQU_DEFINE(equipInfoDto.getEquDefine());

            // 使用单位信息
            if ("个人主体".equals(company.getCompanyType())) {
                esEquipmentDto.setUSE_UNIT_CREDIT_CODE(company.getCompanyCode().split("_")[1]);
                esEquipmentDto.setUSE_UNIT_NAME(company.getCompanyName().split("_")[1]);
            } else {
                esEquipmentDto.setUSE_UNIT_CREDIT_CODE(company.getCompanyCode());
                esEquipmentDto.setUSE_UNIT_NAME(company.getCompanyName());
            }
            esEquipmentCategoryList.add(esEquipmentDto);
            if ("his".equals(equipInfoDto.getDataSource())) {
                // 生成tzs_jg_certificate_change_record_eq记录
                JgCertificateChangeRecordEq changeRecordEq = new JgCertificateChangeRecordEq();
                changeRecordEq.setChangeRecordId(String.valueOf(changeRecordId));// 登记证记录主键
                changeRecordEq.setEquId(registerInfo.getRecord());// 设备主键
                changeRecordEq.setProductCode(factoryInfo.getFactoryNum());// 产品编号
                certificateChangeRecordEqService.save(changeRecordEq);
            }
        });
        Optional.of(useInfoList).filter(list -> !list.isEmpty()).ifPresent(idxBizJgUseInfoService::saveBatch);
        Optional.of(designInfoList).filter(list -> !list.isEmpty()).ifPresent(idxBizJgDesignInfoService::saveBatch);
        Optional.of(registerInfoList).filter(list -> !list.isEmpty()).ifPresent(idxBizJgRegisterInfoService::saveBatch);
        Optional.of(factoryInfoList).filter(list -> !list.isEmpty()).ifPresent(idxBizJgFactoryInfoService::saveBatch);
        Optional.of(otherInfoList).filter(list -> !list.isEmpty()).ifPresent(idxBizJgOtherInfoService::saveBatch);
        Optional.of(paramsVesselList).filter(list -> !list.isEmpty()).ifPresent(idxBizJgTechParamsVesselService::saveBatch);
        Optional.of(inspectionDetectionInfoList).filter(list -> !list.isEmpty()).ifPresent(idxBizJgInspectionDetectionInfoService::saveBatch);
        Optional.of(esEquipmentCategoryList).filter(list -> !list.isEmpty()).ifPresent(esEquipmentCategory::saveAll);
        if ("his".equals(equipInfoDto.getDataSource())) {
            // 生成证书管理表记录
            JgUseRegistrationManage registrationManage = this.saveRegistrationManage(equipInfoDto, company);
            // 生成一条tzs_jg_certificate_change_record记录
            generateCertificateChangeRecord(registrationManage, changeRecordId);
        }
        return String.format("导入完成，成功导入: %d 条数据！", useInfoList.size());
    }

    private EquipmentInfoDto createEquipmentInfoDto(Map<String, Object> equipmentInfoForm, JgVehicleInformationMapper jgVehicleInformationMapper) {
        EquipmentInfoDto dto = new EquipmentInfoDto();
        String equListCode = (String) equipmentInfoForm.get("EQU_LIST");
        String equCategoryCode = (String) equipmentInfoForm.get("EQU_CATEGORY");
        String equDefineCode = (String) equipmentInfoForm.get("EQU_DEFINE");
        dto.setEquListCode(equListCode);
        dto.setEquCategoryCode(equCategoryCode);
        dto.setEquDefineCode(equDefineCode);
        dto.setEquList(jgVehicleInformationMapper.getEquCategoryNameByCode(equListCode));
        dto.setEquCategory(jgVehicleInformationMapper.getEquCategoryNameByCode(equCategoryCode));
        dto.setEquDefine(jgVehicleInformationMapper.getEquCategoryNameByCode(equDefineCode));
        dto.setDataSource((String) equipmentInfoForm.get("DATA_SOURCE"));
        dto.setUseOrgCode((String) equipmentInfoForm.get("USE_ORG_CODE"));
        if ("his".equals(equipmentInfoForm.get("DATA_SOURCE"))) {
            dto.setReceiveOrgCode(((String) equipmentInfoForm.get("RECEIVE_ORG_CODE")).split("_")[0]);
            dto.setReceiveOrgName(((String) equipmentInfoForm.get("RECEIVE_ORG_CODE")).split("_")[1]);
        }
        dto.setPossession((String) equipmentInfoForm.get("VEHICLE_APANAGE"));
        return dto;
    }

    private JgUseRegistrationManage saveRegistrationManage(EquipmentInfoDto equipInfoDto, CompanyBo company) {
        JgUseRegistrationManage jgUseRegistrationManage = new JgUseRegistrationManage();
        jgUseRegistrationManage.setApplyNo(this.getApplicationNo());
        jgUseRegistrationManage.setCertificateStatus(CertificateStatusEnum.YIDENGJI.getName());
        jgUseRegistrationManage.setReceiveOrgName(equipInfoDto.getReceiveOrgName());
        jgUseRegistrationManage.setAuditPassDate(new Date());
        jgUseRegistrationManage.setRegType(BusinessTypeEnum.JG_USAGE_REGISTRATION.getName());
        jgUseRegistrationManage.setRegDate(new Date());
        jgUseRegistrationManage.setEquList(equipInfoDto.getEquList());
        jgUseRegistrationManage.setEquListCode(equipInfoDto.getEquListCode());
        jgUseRegistrationManage.setEquCategory(equipInfoDto.getEquCategory());
        jgUseRegistrationManage.setEquCategoryCode(equipInfoDto.getEquCategoryCode());
        jgUseRegistrationManage.setEquDefine(equipInfoDto.getEquDefine());
        jgUseRegistrationManage.setEquDefineCode(equipInfoDto.getEquDefineCode());
        jgUseRegistrationManage.setIsDelete(Boolean.FALSE);
        jgUseRegistrationManage.setEquUseAddress("");
        jgUseRegistrationManage.setManageType("unit");
        jgUseRegistrationManage.setUseUnitAddress(company.getAddress());
        jgUseRegistrationManage.setUseRegistrationCode(equipInfoDto.getUseOrgCode());
        jgUseRegistrationManage.setUseUnitCreditCode(company.getCompanyCode());
        jgUseRegistrationManage.setUseUnitName(company.getCompanyName());
        jgUseRegistrationManage.setReceiveCompanyCode(equipInfoDto.getReceiveOrgCode());
        jgUseRegistrationManage.setCertificateNo(generateCertificateNo(equipInfoDto, new Date(), equipInfoDto.getReceiveOrgCode()));
        jgUseRegistrationManageService.save(jgUseRegistrationManage);
        return jgUseRegistrationManage;
    }

    private void generateCertificateChangeRecord(JgUseRegistrationManage registrationManage, Long changeRecordId) {
        JgCertificateChangeRecord changeRecord = new JgCertificateChangeRecord();
        changeRecord.setApplyNo(registrationManage.getApplyNo());
        changeRecord.setReceiveOrgName(registrationManage.getReceiveOrgName());
        changeRecord.setAuditPassDate(new Date());
        changeRecord.setRegType(BusinessTypeEnum.JG_USAGE_REGISTRATION.getName());
        changeRecord.setRegDate(registrationManage.getCreateDate());
        changeRecord.setChangeContent(this.buildRecordContent(registrationManage));// 变更内容
        changeRecord.setUseRegistrationCode(registrationManage.getUseRegistrationCode());// 使用登记编号
        changeRecord.setReceiveCompanyCode(registrationManage.getReceiveCompanyCode());// 接收机构公司代码
        changeRecord.setCertificateNo(registrationManage.getCertificateNo());// 登记证书唯一码
        changeRecord.setUseUnitCreditCode(registrationManage.getUseUnitCreditCode());// 使用单位统一信用代码
        changeRecord.setUseUnitName(registrationManage.getUseUnitName());// 使用单位名称
        changeRecord.setEquCategory(registrationManage.getEquCategory());// 设备类别编码
        changeRecord.setRoutePath("");
        changeRecord.setCreateDate(new Date());
        changeRecord.setSequenceNbr(changeRecordId);
        certificateChangeRecordService.save(changeRecord);
    }

    private String buildRecordContent(JgUseRegistrationManage registrationManage) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        return registrationManage.getRecUserName() + "批量上传了【" + BusinessTypeEnum.JG_HISTORY_USAGE_REGISTRATION.getName() + "】，" +
                "单号【" + registrationManage.getApplyNo() + "】，上传日期" + simpleDateFormat.format(registrationManage.getRecDate());
    }

    /**
     * 生成使用登记证书唯一标识
     *
     * @param dto                包含有 设备种类 & 设备类别 & 设备品种 的map
     * @param date               生成证日期 （不传取当前时间）
     * @param receiveCompanyCode 接收机构统一信用代码
     * @return 使用登记证书唯一标识
     */
    private String generateCertificateNo(EquipmentInfoDto dto, Date date, String receiveCompanyCode) {
        String ym = "";
        try {
            ym = Optional.of(DateUtils.dateFormat(date, DateUtils.DATE_PATTERN_MM)).orElse(DateUtils.dateFormat(new Date(), DateUtils.DATE_PATTERN_MM));
        } catch (ParseException e) {
            log.error("日期转换失败：", e);
        }
        String equCode = Optional.ofNullable(dto.getEquCategoryCode()).orElse(dto.getEquDefineCode());
        String registrationCode = equCode + receiveCompanyCode + ym;
        ResponseModel<String> responseModel = tzsServiceFeignClient.deviceRegistrationCode(registrationCode);
        return responseModel.getResult();
    }

    private String getApplicationNo() {
        ResponseModel<List<String>> listResponseModel = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.SYDJ.getCode(), 1);
        if (!ObjectUtils.isEmpty(listResponseModel) && listResponseModel.getStatus() != HttpStatus.OK.value()) {
            log.error("车用气瓶使用登记申请单单号获取失败！");
            throw new BadRequest("车用气瓶使用登记申请单单号获取失败！");
        }
        return listResponseModel.getResult().get(0);
    }

    public StringBuilder checkExcelData(EquipInfoCylinderExcelDto data, AnalysisContext context) {
        StringBuilder result = new StringBuilder();
        ReadRowHolder readRowHolder = context.readRowHolder();
        int rowIndex = readRowHolder.getRowIndex() + 1;
        try {
            log.info("解析第{}行数据：{}", rowIndex, JSON.toJSONString(data));
            // 检查各字段是否为空，如果为空则追加错误信息
            checkNotBlank(data.getProductName(), "设备名称不能为空；", result);
            checkNotBlank(data.getBrandName(), "品牌名称不能为空；", result);
            checkNotBlank(data.getEquType(), "设备型号不能为空；", result);
            checkNotBlank(data.getUseInnerCode(), "单位内部编号不能为空；", result);
            if (useInnerCodeList.contains(data.getUseInnerCode())) {
                result.append("单位内部编号不能重复；");
            }
            checkNotBlank(data.getWhetherVehicleCylinder(), "是否车用气瓶不能为空；", result);
            checkNotBlank(data.getEquCodeType(), "是否有设备代码不能为空；", result);
            if ("1".equals(data.getEquCodeType())) {
                checkNotBlank(data.getEquCode(), "设备代码不能为空；", result);
                String equCode = data.getEquCode();
                if (equCode.matches("[a-zA-Z0-9]+")) {
                    if (equCode.length() <= 17) {
                        result.append("设备代码不能小于17位；");
                    }
                    if (equCode.length() >= 20) {
                        result.append("设备代码不能大于20位；");
                    }
                } else {
                    result.append("设备代码不能包含特殊字符；");
                }
                if (equCodeList.contains(data.getEquCode())) {
                    result.append("设备代码不能重复；");
                }
                this.checkEquCodeUniqueness(data.getEquCode(), result);
            } else {
                data.setEquCode("");
            }
            checkNotBlank(data.getDesignUnitCreditCode(), "设计单位统一社会信用代码不能为空；", result);
            checkNotBlank(data.getDesignUnitName(), "设计单位名称不能为空；", result);
            Optional.ofNullable(data.getDesignDate()).ifPresent(v -> checkDateFormatCorrect(v, "设计日期格式不正确；", result));
            Optional.ofNullable(data.getAppraisalDate()).ifPresent(v -> checkDateFormatCorrect(v, "设计文件鉴定日期格式不正确；", result));
            checkNotBlank(data.getProduceUnitCreditCode(), "制造单位统一社会信用代码不能为空；", result);
            checkNotBlank(data.getProduceUnitName(), "制造单位名称不能为空；", result);
            checkNotBlank(data.getProduceLicenseNum(), "制造许可编号不能为空；", result);
            checkNotBlank(data.getFactoryNum(), "出厂编号/产品编码不能为空；", result);
            if ("0".equals(data.getWhetherVehicleCylinder()) && factoryNumList.contains(data.getFactoryNum()))
                result.append("出厂编号/产品编码不能重复；");
            checkFactoryNumUniqueness(data.getFactoryNum(), null, result);
            checkNotBlank(data.getProduceDate(), "制造日期不能为空；", result);
            Optional.ofNullable(data.getProduceDate()).ifPresent(v -> checkDateFormatCorrect(v, "制造日期格式不正确；", result));
            checkNotBlank(data.getInspectOrgName(), "检测机构名称不能为空；", result);
            checkNotBlank(data.getInspectOrgCode(), "检测机构代码不能为空；", result);
            checkInspectOrg(data.getInspectOrgCode(), result);
            checkNotBlank(data.getInspectStaff(), "检测人员名称不能为空；", result);
            checkNotBlank(data.getInspectDate(), "检测日期不能为空；", result);
            checkDateFormatCorrect(data.getInspectDate(), "检测日期格式不正确；", result);
            checkNotBlank(data.getSingleBottleVolume(), "单瓶容积不能为空；", result);
            checkNotBlank(data.getChargingMedium(), "充装介质不能为空；", result);
            checkNotBlank(data.getNominalWorkingPressure(), "公称工作压力不能为空；", result);
            // 如果存在错误信息，则抛出 BadRequest 异常
            if (result.length() > 0) {
                result.insert(0, "Excel第[" + rowIndex + "]行 -> ");
            }

        } catch (Exception e) {
            log.error(String.format("行索引数: [%s] -> 失败的 Excel 数据: [%s]", rowIndex, JSON.toJSONString(data)), e);
            throw e;
        }
        return result;
    }

    private void checkEquCodeUniqueness(String equCode, StringBuilder result) {
        // 根据设备代码检查唯一性
        LambdaQueryWrapper<RegistrationInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RegistrationInfo::getEquCode, equCode);
        Integer count = tzsJgRegistrationInfoMapper.selectCount(wrapper);
        if (count > 0) {
            result.append("设备代码系统中已存在；");
        }
    }

    // 检查上传Excel中的日期格式是否正确
    private void checkDateFormatCorrect(String date, String errorMessage, StringBuilder result) {
        if (!date.matches("\\d{4}-\\d{2}-\\d{2}")) {
            result.append(errorMessage);
        }
    }

    private void checkInspectOrg(String inspectOrgCode, StringBuilder result) {
        List<Map<String, Object>> InspectOrgList = commonService.getAllInspectionInfo("inspection");
        if (findUseCode(InspectOrgList, inspectOrgCode) == null) {
            result.append("未查询到该检验机构；");
        }
    }

    // 检查字段是否为空，如果为空则追加错误信息到result
    private void checkNotBlank(String value, String errorMessage, StringBuilder result) {
        if (org.apache.commons.lang3.StringUtils.isBlank(value)) {
            result.append(errorMessage);
        }
    }

    private void checkFactoryNumUniqueness(String factoryNum, String sequenceNbr, StringBuilder result) {
        // 车用气瓶业务里面的 出厂编号/产品编码 校验唯一性（产品编号在车用气瓶范围内全局唯一）
        if (commonService.checkFactoryNumUniquenessForVehicleCylinder(factoryNum, sequenceNbr) > 0) {
            result.append("出厂编号/产品编码系统中已存在！");
        }
    }

    /**
     * 生成设备代码
     *
     * @param registerInfo       registerInfo
     * @param factoryInfo        factoryInfo
     * @param receiveCompanyCode 接收机构
     * @return 设备代码
     */
    private String getEquCode(IdxBizJgRegisterInfo registerInfo, IdxBizJgFactoryInfo factoryInfo, String receiveCompanyCode) {
        CodeGenerateDto codeGenerateDto = new CodeGenerateDto();
        codeGenerateDto.setEquList(registerInfo.getEquList());
        codeGenerateDto.setEquCategory(registerInfo.getEquCategory());
        codeGenerateDto.setEquDefine(registerInfo.getEquDefine());
        codeGenerateDto.setProduceDate(factoryInfo.getProduceDate());
        codeGenerateDto.setReceiveCompanyCode(receiveCompanyCode);
        return codeUtil.generateEquipmentCode(codeGenerateDto);
    }

    /**
     * 生成监管码
     */
    private String getSupervisoryCode(String possession, IdxBizJgRegisterInfo registerInfo) {
        Map<String, Object> map = new HashMap<>();
        boolean isXiXian = XI_XIAN.getCode().equals(possession);
        String cityOrCountyCode = isXiXian ? XIAN_YANG.getCode() : possession;
        map.put("cityCode", cityOrCountyCode);
        map.put("isXiXian", isXiXian ? 1 : 0);
        map.put("equCategory", registerInfo.getEquCategory());
        map.put("countyCode", cityOrCountyCode);
        return Optional.ofNullable(tzsServiceFeignClient.createCode(map).getResult())
                .filter(res -> !res.isEmpty())
                .map(res -> String.valueOf(res.get("superviseCode")))
                .orElse("");
    }

    // 注入依赖
    private void injectDependencies(PressureVesselListener listener, Map<String, Object> paramMap) {
        listener.setIdxBizJgRegisterInfoService(idxBizJgRegisterInfoService);
        listener.setJgInstallationNoticeService(jgInstallationNoticeService);
        listener.setIdxBizJgUseInfoService(idxBizJgUseInfoService);
        listener.setIdxBizJgDesignInfoService(idxBizJgDesignInfoService);
        listener.setIdxBizJgFactoryInfoService(idxBizJgFactoryInfoService);
        listener.setIdxBizJgOtherInfoService(iIdxBizJgOtherInfoService);
        listener.setIdxBizJgTechParamsVesselService(idxBizJgTechParamsVesselService);
        listener.setIdxBizJgInspectionDetectionInfoService(idxBizJgInspectionDetectionInfoService);
        listener.setCommonService(commonService);
        listener.setTzsJgRegistrationInfoMapper(tzsJgRegistrationInfoMapper);
        listener.setTzsJgRegistrationInfoMapper(tzsJgRegistrationInfoMapper);
        listener.setEsEquipmentCategory(esEquipmentCategory);
        listener.setCategoryOtherInfoMapper(categoryOtherInfoMapper);
        listener.setSuperviseInfoMapper(superviseInfoMapper);
        listener.setParamMap(paramMap);
        ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        CompanyBo company = reginParams.getCompany();
        listener.setCompany(company);
    }

    public String findUseCode(List<Map<String, Object>> unitList, String inspectOrgCode) {
        Optional<Map<String, Object>> optional = unitList.stream()
                .filter(map -> map.get("useCode").equals(inspectOrgCode))
                .findFirst();
        return optional.map(map -> (String) map.get("useCode")).orElse(null);
    }

    @Override
    public Object getProjectContraption(String uscUnitCreditCode) {
        return this.baseMapper.getProjectContraption(uscUnitCreditCode);
    }

    @Override
    public Boolean esSynchronousProjectContraption() {
        List<Map<String, Object>> list = this.baseMapper.esSynchronousProjectContraption();
        if (!ObjectUtils.isEmpty(list)) {
            HashMap<String, Map<String, Object>> objMap = new HashMap<>();
            list.forEach(item -> {
                HashMap<String, Object> param = new HashMap<>();
                param.put("PROJECT_CONTRAPTION", item.get("PROJECT_CONTRAPTION"));
                objMap.put(item.get("SEQUENCE_NBR").toString(), param);
            });
            // 更新es
            tzsServiceFeignClient.commonUpdateEsDataByIds(objMap);
        }
        return Boolean.TRUE;
    }
}