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

import com.alibaba.excel.EasyExcel;
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.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.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jg.api.dto.EquipInfoCylinderExcelDto;
import com.yeejoin.amos.boot.module.jg.api.enums.CompanyTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.ConstructionEnum;
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.biz.config.PressureVesselListener;
import com.yeejoin.amos.boot.module.jg.biz.context.EquipUsedCheckStrategyContext;
import com.yeejoin.amos.boot.module.jg.biz.dao.ESEquipmentCategory;
import com.yeejoin.amos.boot.module.jg.biz.service.*;
import com.yeejoin.amos.boot.module.ymt.api.dto.ESEquipmentCategoryDto;
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.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 io.minio.GetObjectArgs;
import io.minio.MinioClient;
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.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
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.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

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


/**
 * 注册登记信息表服务实现类
 *
 * @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_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 = "检验检测机构";
    // 需要转化成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;

    @Value("${minio.endpoint}")
    private String minioEndpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Autowired
    private IdxBizJgDesignInfoServiceImpl idxBizJgDesignInfoService;
    @Autowired
    private IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;
    @Autowired
    private IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoService;
    @Autowired
    private IdxBizJgTechParamsVesselServiceImpl idxBizJgTechParamsVesselService;
    @Autowired
    private IdxBizJgInspectionDetectionInfoServiceImpl idxBizJgInspectionDetectionInfoService;

    /**
     * 将对象的属性由驼峰转为纯大写下划线格式
     *
     * @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 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()));
                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;
    }

    /**
     * 查询设备基本信息
     *
     * @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 = "";
        // 使用信息
        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());
                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());
                }
            }
            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();
        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");
            } else if (ValidationUtil.equals(queryType, "WB")) {
                // 查询 维保备案【可绑定设备列表】【(EQU_STATE=== null ||  ""）】
                BoolQueryBuilder wbBuilder = QueryBuilders.boolQuery();
                wbBuilder.mustNot(QueryBuilders.existsQuery("EQU_STATE"));
                boolMust.must(wbBuilder);
            } else if (!ObjectUtils.isEmpty(queryType) && 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(!ObjectUtils.isEmpty(queryType) && 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);
            }
        }

        // 通用匹配规则，其他条件构建
        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(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);
                }
                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());
            CompanyModel result = Privilege.companyClient.queryByCompanyCode(company.getCompanyCode()).getResult();
            if (!ValidationUtil.isEmpty(result)) {
                object.put("companyType", result.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("businessScenarios"));

        // 操作类型
        String operateType = ValidationUtil.isEmpty(equipmentInfoForm.get(SEQUENCE_NBR)) ? OPERATESAVE : OPERATEEDIT;
        // 设备是否复制而来，复制来的设备走新增
        boolean isCopy = !ValidationUtil.isEmpty(equipmentInfoForm.get(IS_COPY));
        operateType = isCopy ? OPERATESAVE : operateType;

        String dataSource = OPERATESAVE.equals(operateType) ? "jg" : equipmentInfoForm.get("DATA_SOURCE").toString();
        if (isCopy) {
            String sourceRecord = equipmentClassForm.get(RECORD).toString();
            dataSource = "jg_" + sourceRecord;
        }
        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.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);

        // 检验检测
        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.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 String importPressureVesselData(Map<String, Object> paramMap) {
        try {
            PressureVesselListener pressureVesselListener = new PressureVesselListener();
            LinkedHashMap equipmentInfoForm = (LinkedHashMap) checkAndCast(paramMap.get(EQUIP_INFO_FORM_ID));
            injectDependencies(pressureVesselListener, equipmentInfoForm);

            // 初始化MinioClient对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioEndpoint)
                    .credentials(accessKey, secretKey)
                    .build();

            ArrayList<?> file = (ArrayList<?>) equipmentInfoForm.get("file");
            HashMap<?, ?> fileMap = (HashMap<?, ?>) file.get(0);
            String url = String.valueOf(fileMap.get("url")).replaceFirst("/", "");
            // /upload/tzs/amos_studio/9137475/xxx.xlsx
            // 中的upload为bucket，tzs/amos_studio/9137475/xxx.xlsx为objectName
            int index = url.indexOf("/");
            String bucket = url.substring(0, index);
            String objectName = url.substring(index + 1);

            // 入参
            GetObjectArgs args = GetObjectArgs.builder().bucket(bucket).object(objectName).build();
            // 获取文件对象的InputStream
            InputStream inputStream = minioClient.getObject(args);

            EasyExcel.read(inputStream, EquipInfoCylinderExcelDto.class, pressureVesselListener)
                    .headRowNumber(4)
                    .sheet()
                    .doRead();
            inputStream.close();
            return pressureVesselListener.getResult();
        } catch (Exception e) {
            String err = (e.getCause() instanceof BadRequest) ? "模版数据填写有误：" + e.getCause().getMessage() : "导入时出现异常：请联系管理员！" ;
            throw new BadRequest(err);
        }
    }

    // 注入依赖
    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);
    }
}