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

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.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.enums.CompanyTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.ConstructionEnum;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgUseRegistrationMapper;
import com.yeejoin.amos.boot.module.jg.biz.config.LocalBadRequest;
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 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.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.http.HttpStatus;
import org.springframework.stereotype.Service;
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.StringUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

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


/**
 * 注册登记信息表服务实现类
 *
 * @author system_generator
 * @date 2023-08-17
 */
@Service
public class IdxBizJgRegisterInfoServiceImpl extends BaseService<IdxBizJgRegisterInfoDto, IdxBizJgRegisterInfo, IdxBizJgRegisterInfoMapper> implements IIdxBizJgRegisterInfoService {
    // 设备分类表单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 EQUDEFINE = "EQU_DEFINE";
    private static final String EQUDEFINECODE = "EQU_DEFINE_CODE";

    // 新增修改标识
    private static final String OPERATESAVE = "save";
    private static final String OPERATEEDIT = "edit";

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    private RedisUtils redisUtils;

    @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
    DataDictionaryServiceImpl iDataDictionaryService;
    @Autowired
    private CategoryOtherInfoMapper categoryOtherInfoMapper;
    @Autowired
    private SuperviseInfoMapper superviseInfoMapper;
    @Autowired
    private JgUseRegistrationMapper jgUseRegistrationMapper;

    @Autowired
    private JgInstallationNoticeServiceImpl jgInstallationNoticeService;

    public final static String USE_TYPE_NAME =  "使用单位";

    public final static String INDIVIDUAL_TYPE_NAME =  "个人主体";

    public final static String MAINTENANCE_TYPE_NAME =  "安装改造维修单位";

    @Value("${add.equip.dict.code.suffix:CATEGORY_LIST_ADD}")
    private String equipAddDictCodeSuffix;

    public static String[] jsonFields = {"insOtherAccessories", "installContractAttachment", "installProxyStatementAttachment" };


    /**
     * 设备注册信息
     *
     * @param paramMap
     * @return
     */
    public ResponseModel equipmentRegisterSubmit(Map<String, Object> paramMap) {
        String record = null;
        LinkedHashMap equipmentClassForm = (LinkedHashMap) paramMap.get(EQUIP_CLASS_FORM_ID);
        LinkedHashMap equipmentInfoForm = (LinkedHashMap) paramMap.get(EQUIP_INFO_FORM_ID);
        LinkedHashMap equipmentParamsForm = (LinkedHashMap) paramMap.get(EQUIP_PARAMS_FORM_ID);
        // 设备代码 字段的唯一性校验
        LambdaQueryWrapper<RegistrationInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RegistrationInfo::getEquCode, equipmentInfoForm.get("EQU_CODE"));
        wrapper.ne(!ValidationUtil.isEmpty(equipmentInfoForm.get("SEQUENCE_NBR")), RegistrationInfo::getSequenceNbr, equipmentInfoForm.get("SEQUENCE_NBR"));
        Integer count = tzsJgRegistrationInfoMapper.selectCount(wrapper);
        if (count > 0) {
            throw new LocalBadRequest("设备代码已存在，请重新输入！");
        }
        // 编辑校验
        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);
            //删除数据库数据和ES数据
            if (!ObjectUtils.isEmpty(record)) {
                List<String> records = new ArrayList<>();
                records.add(record);
                superviseInfoMapper.deleteDataAll(records);
                esEquipmentCategory.deleteById(record);
            }
            ResponseModel<Object> response = new ResponseModel<>();
            response.setDevMessage(e.getMessage());
            response.setResult(null);
            response.setMessage("操作失败，请检查数据输入后重新提交");
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            return response;
        }
        return ResponseHelper.buildResponse(record);
    }

    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) {
        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);
            }
        }

        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 companyType = selectedOrgInfo.getCompany().getCompanyType();
        String dictCodePrefix = getDictCodePrefix(companyType, equList);
        if(StringUtils.isEmpty(dictCodePrefix)){
            return new ArrayList<>();
        }
        String dictCode = String.format("%s_%s",dictCodePrefix, equipAddDictCodeSuffix);
        return FeignUtil.remoteCall(()->Systemctl.dictionarieClient.dictValues(dictCode));
    }

    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));
        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.termQuery("DATA_SOURCE",QueryParser.escape("jg")));
        boolMust.must(dBuilder);

        String queryType = map.getString("QUERY_TYPE");
        if (!ObjectUtils.isEmpty(queryType)) {
            //查询 安装告知【可告知设备列表】【EQU_STATE=== null】
            if (ValidationUtil.equals(queryType, "AZ")) {
                BoolQueryBuilder azBuilder = QueryBuilders.boolQuery();
                azBuilder.mustNot(QueryBuilders.existsQuery("EQU_STATE"));
                boolMust.must(azBuilder);
            } else if (ValidationUtil.equals(queryType, "WB")) {
                // 查询 维保备案【可绑定设备列表】【(EQU_STATE=== null） && (INSPECT_REPORT！==""  && !null)】
                BoolQueryBuilder wbBuilder = QueryBuilders.boolQuery();
                wbBuilder.mustNot(QueryBuilders.existsQuery("EQU_STATE"));
                wbBuilder.must(QueryBuilders.existsQuery("INSPECT_REPORT"));
                wbBuilder.mustNot(QueryBuilders.matchPhraseQuery("INSPECT_REPORT", ""));
                boolMust.must(wbBuilder);
            } else if (!ObjectUtils.isEmpty(queryType) && ValidationUtil.equals(queryType, "SY")) {
                //查询 使用登记【可选设备列表】【EQU_STATUS=== null && (INSPECT_REPORT！=="" && !null) && (USE_ORG_CODE!=="" && !null)】
                BoolQueryBuilder syBuilder = QueryBuilders.boolQuery();
                syBuilder.mustNot(QueryBuilders.existsQuery("EQU_STATE"));
                syBuilder.must(QueryBuilders.existsQuery("INSPECT_REPORT"));
                syBuilder.mustNot(QueryBuilders.matchPhraseQuery("INSPECT_REPORT", ""));
                syBuilder.must(QueryBuilders.existsQuery("USE_ORG_CODE"));
                syBuilder.mustNot(QueryBuilders.matchPhraseQuery("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);
        }


        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;

        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (org.elasticsearch.search.SearchHit hit : response.getHits().getHits()) {
                System.out.println(hit);
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hit);
                JSONObject dto2 = jsonObject.getJSONObject("sourceAsMap");
                if (!ValidationUtil.isEmpty(dto2.get(CONSTRUCTIONTYPE))) {
                    //转化施工类型
                    Integer integer = Integer.valueOf(dto2.get(CONSTRUCTIONTYPE).toString());
                    String status = ConstructionEnum.getName.get(integer);
                    dto2.put(CONSTRUCTIONTYPE, status);
                }
                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;
    }

    /**
     * 获取当前登录人单位类型
     *
     * @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
     */
    private 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 operateType = ValidationUtil.isEmpty(equipmentInfoForm.get("SEQUENCE_NBR")) ? OPERATESAVE : OPERATEEDIT;
        record = OPERATESAVE.equals(operateType) ? UUID.randomUUID().toString() : equipmentInfoForm.get("RECORD").toString();

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

        //使用信息
        IdxBizJgUseInfo useInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgUseInfo.class);
        useInfo.setRecord(record);
        useInfo.setRecDate(date);
        useInfo.setDataSource("jg");
        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(companyType.get("creditCode").toString());
            useInfo.setUseUnitName(companyType.get("companyTypeName").toString());
        }

        idxBizJgUseInfoService.saveOrUpdateData(useInfo);

        //设计制造
        IdxBizJgDesignInfo designInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgDesignInfo.class);
        designInfo.setRecord(record);
        designInfo.setRecDate(date);
        designInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("DESIGNINFO_SEQ")));
        iIdxBizJgDesignInfoService.saveOrUpdateData(designInfo);

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

        //施工信息
        JSONObject company = getCompanyType();
        String companyName = company.getString("companyName");
        String companyCode = company.getString("companyCode").contains("_") ?
                company.getString("companyCode").split("_")[1] : company.getString("companyCode");
        IdxBizJgConstructionInfo constructionInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgConstructionInfo.class);
        constructionInfo.setRecord(record);
        constructionInfo.setRecDate(date);

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

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

        //注册登记
        // IdxBizJgRegisterInfo equipmentClassRegisterInfo = JSON.parseObject(JSON.toJSONString(equipmentClassForm), IdxBizJgRegisterInfo.class);
        IdxBizJgRegisterInfo registerInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgRegisterInfo.class);
        // Bean.copyExistPropertis(equipmentClassRegisterInfo, registerInfo);
        registerInfo.setRecord(record);
        registerInfo.setRecDate(date);
        registerInfo.setRegisterState(this.getRegCode());
        registerInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("REGISTERINFO_SEQ")));
        this.saveOrUpdate(registerInfo);

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

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

        //其他信息
        IdxBizJgOtherInfo otherInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgOtherInfo.class);
        otherInfo.setRecord(record);
        otherInfo.setRecDate(date);
        otherInfo.setSequenceNbr(OPERATESAVE.equals(operateType) ? null : String.valueOf(equipmentInfoForm.get("OTHERINFO_SEQ")));
        iIdxBizJgOtherInfoService.saveOrUpdateData(otherInfo);

        //检验检测
        IdxBizJgInspectionDetectionInfo inspectionDetectionInfo = JSON.parseObject(JSON.toJSONString(equipmentInfoForm), IdxBizJgInspectionDetectionInfo.class);
        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<>();
        // 设备种类
        String equList = equipmentClassForm.get("EQU_LIST").toString();
        // 电梯
        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;
    }

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