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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.biz.common.utils.SnowflakeIdUtil;
import com.yeejoin.amos.boot.module.jg.api.dto.JgResumeInfoDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgResumeInfo;
import com.yeejoin.amos.boot.module.jg.api.entity.JgUseRegistration;
import com.yeejoin.amos.boot.module.jg.api.entity.JgUseRegistrationEq;
import com.yeejoin.amos.boot.module.jg.api.enums.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.enums.CompanyTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgUseRegistrationEqMapper;
import com.yeejoin.amos.boot.module.jg.biz.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.jg.biz.service.*;
import com.yeejoin.amos.boot.module.ymt.api.entity.*;
import com.yeejoin.amos.boot.module.ymt.api.enums.ApplicationFormTypeEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquimentEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.boot.module.ymt.api.enums.FlowStatusEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.*;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import static com.alibaba.fastjson.JSON.toJSONString;
import static com.yeejoin.amos.boot.module.jg.biz.service.impl.IdxBizJgRegisterInfoServiceImpl.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class EquipClaimServiceImpl {

    private static final String JG_ALL_INDEX = "idx_biz_view_jg_all";

    private static final String NUMBER = "number";
    private static final String SIZE = "size";
    private static final String SEQUENCE_NBR = "SEQUENCE_NBR";
    private static final String EQU_STATE = "EQU_STATE";
    private static final String record = "record";
    private static final String RECORD = "RECORD";
    private static final String CREATE_DATE = "CREATE_DATE";
    private static final String DATA_SOURCE = "DATA_SOURCE";
    private static final String IS_INTO_MANAGEMENT = "IS_INTO_MANAGEMENT";
    private static final String EQU_LIST_CODE = "EQU_LIST_CODE";
    private static final String EQU_CATEGORY_CODE = "EQU_CATEGORY_CODE";
    private static final String EQU_DEFINE_CODE = "EQU_DEFINE_CODE";
    private static final String PRODUCT_NAME = "PRODUCT_NAME";
    private static final String EQU_CODE = "EQU_CODE";
    private static final String USE_UNIT_NAME = "USE_UNIT_NAME";
    private static final String ORG_BRANCH_CODE = "ORG_BRANCH_CODE";
    private static final String ADDRESS = "ADDRESS";
    private static final String data_source = "data_source";
    private static final String jg_his_xa = "jg_his_xa";
    private static final String is_into_management = "is_into_management";
    private static final String equ_list = "equ_list";
    private static final String create_date = "create_date";
    public static final String JG_HIS_XA_CLAIM = "jg_his_xa_claim";

    private final RedisUtils redisUtils;
    private final ICommonService commonService;
    private final RestHighLevelClient restHighLevelClient;
    private final JgResumeInfoServiceImpl jgResumeInfoService;
    private final IdxBizJgProjectContraptionServiceImplService projectContraptionServiceImplService;
    private final IdxBizJgRegisterInfoServiceImpl jgRegisterInfoService;
    private final IIdxBizJgConstructionInfoService iIdxBizJgConstructionInfoService;
    private final IIdxBizJgUseInfoService idxBizJgUseInfoService;
    private final IIdxBizJgDesignInfoService iIdxBizJgDesignInfoService;
    private final IIdxBizJgFactoryInfoService iIdxBizJgFactoryInfoService;
    private final IIdxBizJgOtherInfoService iIdxBizJgOtherInfoService;
    private final IIdxBizJgSupervisionInfoService iIdxBizJgSupervisionInfoService;
    private final IIdxBizJgInspectionDetectionInfoService iIdxBizJgInspectionDetectionInfoService;
    private final JgUseRegistrationServiceImpl useRegistrationService;
    private final JgUseRegistrationEqMapper jgRelationEquipMapper;
    private final TzsServiceFeignClient tzsServiceFeignClient;
    private final IdxBizJgSupervisionInfoMapper idxBizJgSupervisionInfoMapper;
    private final IdxBizJgRegisterInfoMapper idxBizJgRegisterInfoMapper;
    private final IdxBizJgDesignInfoServiceImpl idxBizJgDesignInfoService;
    private final IdxBizJgDesignInfoMapper idxBizJgDesignInfoMapper;
    private final IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;
    private final IdxBizJgFactoryInfoMapper idxBizJgFactoryInfoMapper;
    private final IdxBizJgUseInfoMapper useInfoMapper;
    private final IdxBizJgOtherInfoMapper otherInfoMapper;
    private final SnowflakeIdUtil sequence;


    /**
     * 当前登录人信息
     *
     * @return 当前登录人信息
     */
    protected ReginParams getSelectedOrgInfo() {
        return JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
    }

    /**
     * 待认领-台套设备分页
     *
     * @param params 筛选条件
     * @return result
     */
    public Page<JSONObject> setEquipPage(JSONObject params) {
        int number = Integer.parseInt((String) params.getOrDefault(NUMBER, "1"));
        int size = Integer.parseInt((String) params.getOrDefault(SIZE, "20"));
        long totle = 0;
        Page<JSONObject> result = new Page<>(number, size);

        SearchRequest request = new SearchRequest();
        request.indices(JG_ALL_INDEX);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();

        // 默认条件 DATA_SOURCE == jg_his_xa && IS_INTO_MANAGEMENT == false && EQU_LIST_CODE ！= 8000
        BoolQueryBuilder dBuilder = QueryBuilders.boolQuery();
        dBuilder.must(QueryBuilders.termQuery(DATA_SOURCE, jg_his_xa));
        dBuilder.mustNot(QueryBuilders.termQuery(EQU_LIST_CODE, EquipmentClassifityEnum.YLGD.getCode()));
        dBuilder.must(QueryBuilders.matchQuery(IS_INTO_MANAGEMENT, false));
        boolMust.must(dBuilder);

        // --------------------------------   参数过滤
        this.buildSetSearchParams(params, boolMust);

        // --------------------------------   字段排序
        builder.sort(CREATE_DATE, SortOrder.DESC);
        builder.query(boolMust);
        builder.from((number - 1) * size);
        builder.size(size);
        request.source(builder);
        List<JSONObject> list = new LinkedList<>();

        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (SearchHit hit : response.getHits().getHits()) {
                JSONObject sourceAsJSON = JSONObject.parseObject(toJSONString(hit.getSourceAsMap()));
                // 设备状态转化
                if (!ValidationUtil.isEmpty(sourceAsJSON.get(EQU_STATE))) {
                    sourceAsJSON.put(EQU_STATE, EquimentEnum.getName.get(Integer.valueOf(sourceAsJSON.get(EQU_STATE).toString())));
                }
                sourceAsJSON.put(record, sourceAsJSON.get(SEQUENCE_NBR));
                // 日期转化
                sourceAsJSON.put(CREATE_DATE, Instant.ofEpochMilli(Long.parseLong(sourceAsJSON.getString(CREATE_DATE))).atZone(ZoneId.systemDefault()).toLocalDate());
                list.add(sourceAsJSON);
            }
            if (response.getInternalResponse().hits().getTotalHits() != null) {
                totle = response.getInternalResponse().hits().getTotalHits().value;
            }
            result.setRecords(list);
            result.setTotal(totle);
        } catch (IOException e) {
            log.error("查询待认领台套设备，分页异常:{}", e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 台套查询条件组装
     *
     * @param params
     * @param boolMust
     */
    private void buildSetSearchParams(JSONObject params, BoolQueryBuilder boolMust) {
        // 设备种类编码
        if (!ObjectUtils.isEmpty(params.getString(EQU_LIST_CODE))) {
            BoolQueryBuilder elcBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(params.getString(EQU_LIST_CODE));
            elcBuilder.must(QueryBuilders.matchPhraseQuery(EQU_LIST_CODE, test));
            boolMust.must(elcBuilder);
        }
        // 设备类别编码
        if (!ObjectUtils.isEmpty(params.getString(EQU_CATEGORY_CODE))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(params.getString(EQU_CATEGORY_CODE));
            pBuilder.must(QueryBuilders.termQuery(EQU_CATEGORY_CODE, test));
            boolMust.must(pBuilder);
        }
        // 设备品种编码
        if (!ObjectUtils.isEmpty(params.getString(EQU_DEFINE_CODE))) {
            BoolQueryBuilder elcBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(params.getString(EQU_DEFINE_CODE));
            elcBuilder.must(QueryBuilders.matchPhraseQuery(EQU_DEFINE_CODE, test));
            boolMust.must(elcBuilder);
        }
        // 设备名称
        if (!ObjectUtils.isEmpty(params.getString(PRODUCT_NAME))) {
            BoolQueryBuilder elcBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(params.getString(PRODUCT_NAME));
            elcBuilder.must(QueryBuilders.matchPhraseQuery(PRODUCT_NAME, test));
            boolMust.must(elcBuilder);
        }
        // 设备代码模糊查询
        if (!ObjectUtils.isEmpty(params.getString(EQU_CODE))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(params.getString(EQU_CODE));
            pBuilder.must(QueryBuilders.wildcardQuery(EQU_CODE, "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 使用单位 名称模糊查询
        if (!ObjectUtils.isEmpty(params.getString(USE_UNIT_NAME))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String text = params.getString(USE_UNIT_NAME);
            pBuilder.must(QueryBuilders.matchQuery(USE_UNIT_NAME, text).operator(Operator.AND));
            boolMust.must(pBuilder);
        }
        // 属地监管部门
        if (!ObjectUtils.isEmpty(params.getString(ORG_BRANCH_CODE))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            pBuilder.must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(params.getString(ORG_BRANCH_CODE)) + "*"));
            boolMust.must(pBuilder);
        }
        // 设备使用地址 名称模糊查询
        if (!ObjectUtils.isEmpty(params.getString(ADDRESS))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            pBuilder.must(QueryBuilders.matchQuery(ADDRESS, params.getString(ADDRESS))
                    .operator(Operator.AND));
            boolMust.must(pBuilder);
        }
    }

    /**
     * 待认领-管道装置设备分页
     *
     * @param params
     * @return
     */
    public IPage<IdxBizJgProjectContraption> pipeEquipPage(JSONObject params) {
        int number = Integer.parseInt((String) params.getOrDefault(NUMBER, "1"));
        int size = Integer.parseInt((String) params.getOrDefault(SIZE, "20"));
        Page<IdxBizJgProjectContraption> page = new Page<>(number, size);
        QueryWrapper<IdxBizJgProjectContraption> queryWrapper = new QueryWrapper<IdxBizJgProjectContraption>();
        // 默认条件 DATA_SOURCE == jg_his_xa && IS_INTO_MANAGEMENT == false && EQU_LIST_CODE == 8000
        queryWrapper.eq(data_source, jg_his_xa);
        queryWrapper.eq(is_into_management, false);
        queryWrapper.eq(equ_list, EquipmentClassifityEnum.YLGD.getCode());
        // --------------------------------   参数过滤
        this.buildPipeSearchParams(params, queryWrapper);

        queryWrapper.orderByDesc(create_date);
        return projectContraptionServiceImplService.page(page, queryWrapper);
    }

    /**
     * 管道装置查询条件组装
     *
     * @param params
     * @param queryWrapper
     */
    private void buildPipeSearchParams(JSONObject params, QueryWrapper<IdxBizJgProjectContraption> queryWrapper) {
        queryWrapper.eq(!ObjectUtils.isEmpty(params.getString("equCategoryCode")), "equ_category", params.getString("equCategoryCode"));
        queryWrapper.eq(!ObjectUtils.isEmpty(params.getString("equDefineCode")), "equ_define", params.getString("equDefineCode"));
        queryWrapper.like(!ObjectUtils.isEmpty(params.getString("projectContraption")), "project_contraption", params.getString("projectContraption"));
        queryWrapper.like(!ObjectUtils.isEmpty(params.getString("projectContraptionNo")), "project_contraption_no", params.getString("projectContraptionNo"));
        queryWrapper.like(!ObjectUtils.isEmpty(params.getString("useUnitName")), "use_unit_name", params.getString("useUnitName"));
        queryWrapper.likeRight(!ObjectUtils.isEmpty(params.getString("orgBranchCode")), "org_code", params.getString("orgBranchCode"));
    }


    /**
     * 认领-台套设备
     *
     * @param json
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object setEquipClaim(JSONObject json) {
        JSONObject equipInfo = JSON.parseObject(toJSONString(json.get(EQUIP_INFO_FORM_ID)));
        JSONObject equipParams = JSON.parseObject(toJSONString(json.get(EQUIP_PARAMS_FORM_ID)));
        CompanyBo company = getSelectedOrgInfo().getCompany();
        String useRegistrationCode = Objects.toString(equipInfo.get("useRegistrationCode"), null);
        // 参数校验 - 同 设备录入的逻辑
        this.checkParams(new LinkedHashMap<>(equipInfo));

        if (StringUtils.isEmpty(useRegistrationCode)) {
            // 认领到自己单位下 -> 未纳管设备列表 ， dataSource 变为 -> jg_his_xa_claim

            // 认领 更新设备信息
            this.updateEquipInfoWithClaim(equipInfo, equipParams, false);
            // 添加设备的业务履历
            this.addEquipResume(equipInfo, new JgUseRegistration());
        } else {
            // 认领到自己单位下 -> 已纳管设备列表 ， + 历史设备登记

            // 认领 更新设备信息
            this.updateEquipInfoWithClaim(equipInfo, equipParams, true);
            // 历史设备登记
            JgUseRegistration useRegistration = this.addHistoryEquipRegistration(equipInfo);
            // 添加设备的业务履历
            this.addEquipResume(equipInfo, useRegistration);
        }
        // 添加es中的使用单位信息
        HashMap<String, Map<String, Object>> objMap = new HashMap<>();
        HashMap<String, Object> param = new HashMap<>();
        param.put("USE_UNIT_CREDIT_CODE", company.getCompanyCode());
        param.put("USE_UNIT_NAME", company.getCompanyName());
        objMap.put(equipInfo.get(RECORD).toString(), param);
        tzsServiceFeignClient.commonUpdateEsDataByIds(objMap);
        return Boolean.TRUE;
    }

    /**
     * 历史设备登记
     *
     * @param equipInfo
     * @return
     */
    public JgUseRegistration addHistoryEquipRegistration(JSONObject equipInfo) {
        String record = (String) equipInfo.get(RECORD);
        CompanyBo company = getSelectedOrgInfo().getCompany();
        AgencyUserModel userModel = getSelectedOrgInfo().getUserModel();

        equipInfo.put("useUnitCreditCode", company.getCompanyCode());
        equipInfo.put("useUnitName", company.getCompanyName());
        equipInfo.put("useInnerCode", equipInfo.get("USE_INNER_CODE"));
        // 历史使用登记信息
        JgUseRegistration jgUseRegistration = new JgUseRegistration();
        jgUseRegistration.setSequenceNbr(sequence.nextId());
        try {
            jgUseRegistration.setRegDate(ValidationUtil.isEmpty(equipInfo.get("oRegDate")) ? new Date() :
                    DateUtils.dateParse((String) equipInfo.get("oRegDate"), DateUtils.DATE_PATTERN));
        } catch (Exception e) {
            log.error("设备认领，历史使用登记信息转换日期失败：", e);
        }
        jgUseRegistration.setInputUnitNo(Objects.toString(equipInfo.get("oRegUnit"), null));
        if (!ObjectUtils.isEmpty(equipInfo.get("otherAccessories"))) {
            jgUseRegistration.setOtherAccessories(toJSONString(equipInfo.get("otherAccessories")));
        }
        if (equipInfo.containsKey("receiveOrgCode")) {
            // 接收单位信息
            String[] splitMaintenanceUnitCode = Objects.toString(equipInfo.getString("receiveOrgCode"), "").split("_");
            jgUseRegistration.setReceiveCompanyCode(splitMaintenanceUnitCode[0]);
            jgUseRegistration.setReceiveOrgName(splitMaintenanceUnitCode[1]);
            jgUseRegistration.setReceiveCompanyOrgCode(commonService.getOneCompany(jgUseRegistration.getReceiveCompanyCode()).getOrgCode());
        }
        if (equipInfo.containsKey("orgBranchCode") && !ObjectUtils.isEmpty(equipInfo.get("orgBranchCode"))) {
            // 监察处置机构代码
            String[] splitOrgBranchCode = Objects.toString(equipInfo.getString("orgBranchCode"), "").split("_");
            jgUseRegistration.setSupervisionOrgCode(splitOrgBranchCode[0]);
        }
        // 使用单位提交
        jgUseRegistration.setUseUnitName(CompanyTypeEnum.INDIVIDUAL.getName().equals(company.getCompanyType()) ? company.getCompanyName().split("_")[1] : company.getCompanyName());
        jgUseRegistration.setUseUnitCreditCode(CompanyTypeEnum.INDIVIDUAL.getName().equals(company.getCompanyType()) ? company.getCompanyCode().split("_")[1] : company.getCompanyCode());
        jgUseRegistration.setCreateUserId(userModel.getUserId());
        jgUseRegistration.setCreateUserName(userModel.getUserName());
        jgUseRegistration.setManageType("set");
        if (!ObjectUtils.isEmpty(equipInfo.get("inspectUnitCreditCode"))) {
            jgUseRegistration.setInspectUnitCreditCode(equipInfo.get("inspectUnitCreditCode").toString());
        }
        if (!ObjectUtils.isEmpty(equipInfo.get("inspectOrgName"))) {
            jgUseRegistration.setInspectUnitName(equipInfo.get("inspectOrgName").toString());
        }
        // 是否西咸
        if (!ObjectUtils.isEmpty(equipInfo.get("isXixian"))) {
            jgUseRegistration.setIsXixian(Objects.toString(equipInfo.get("isXixian"), null));
        }
        // 使用地点
        String useCityName = "";
        String useCountyName = "";
        String useStreetName = "";
        // 市
        List<LinkedHashMap> city = (List<LinkedHashMap>) redisUtils.get("CITY");
        // 区
        List<LinkedHashMap> region = (List<LinkedHashMap>) redisUtils.get("REGION");
        // 街道
        List<LinkedHashMap> street = (List<LinkedHashMap>) redisUtils.get("STREET");
        jgUseRegistration.setUseAddress("陕西省");
        // 城市
        if (!ObjectUtils.isEmpty(equipInfo.get("city")) && !ObjectUtils.isEmpty(city)) {
            AtomicReference<String> atomicUseCity = new AtomicReference<>(useCityName);
            city.forEach(item -> {
                if (Objects.toString(item.get("regionCode")).equals(Objects.toString(equipInfo.get("city")))) {
                    atomicUseCity.set("" + item.get("regionName"));
                    jgUseRegistration.setUseAddress(jgUseRegistration.getUseAddress() + item.get("regionName"));
                }
            });
            useCityName = atomicUseCity.get();
        }
        // 区县
        if (!ObjectUtils.isEmpty(equipInfo.get("county")) && !ObjectUtils.isEmpty(city)) {
            AtomicReference<String> atomicUseCounty = new AtomicReference<>(useCountyName);
            region.forEach(item -> {
                if (Objects.toString(item.get("regionCode")).equals(Objects.toString(equipInfo.get("county")))) {
                    atomicUseCounty.set("" + item.get("regionName"));
                    jgUseRegistration.setUseAddress(jgUseRegistration.getUseAddress() + item.get("regionName"));
                }
            });
            useCountyName = atomicUseCounty.get();
        }
        // 街道
        if (!ObjectUtils.isEmpty(equipInfo.get("factoryUseSiteStreet")) && !ObjectUtils.isEmpty(city)) {
            JSONObject finalMap2 = equipInfo;
            AtomicReference<String> atomicUseStreet = new AtomicReference<>(useStreetName);
            street.forEach(item -> {
                if (Objects.toString(item.get("regionCode")).equals(Objects.toString(finalMap2.get("factoryUseSiteStreet")))) {
                    atomicUseStreet.set("" + item.get("regionName"));
                    jgUseRegistration.setUseAddress(jgUseRegistration.getUseAddress() + item.get("regionName"));
                }
            });
            useStreetName = atomicUseStreet.get();
        }
        jgUseRegistration.setUseAddress(jgUseRegistration.getUseAddress() + equipInfo.get("address"));


        ResponseModel<List<String>> listResponseModel = tzsServiceFeignClient.applicationFormCode(ApplicationFormTypeEnum.SYDJ.getCode(), 1);
        if (!ObjectUtils.isEmpty(listResponseModel)) {
            jgUseRegistration.setApplyNo(listResponseModel.getResult().get(0));
        }
        jgUseRegistration.setAuditPassDate(new Date());
        jgUseRegistration.setAuditStatus(FlowStatusEnum.TO_BE_FINISHED.getName());
        jgUseRegistration.setStatus(FlowStatusEnum.TO_BE_FINISHED.getName());
        jgUseRegistration.setUseRegistrationCode(ValidationUtil.isEmpty(equipInfo.get("useRegistrationCode")) ? "" : Objects.toString(equipInfo.get("useRegistrationCode"), null));
        jgUseRegistration.setRegType("1");// 历史登记


        // 暂存历史表
        useRegistrationService.updateHistory(equipInfo, Objects.toString(record, null), Objects.toString(jgUseRegistration.getSequenceNbr(), null), jgUseRegistration.getSupervisoryCode());
        // 监督管理信息
        LambdaQueryWrapper<IdxBizJgSupervisionInfo> lambdaSup = new QueryWrapper<IdxBizJgSupervisionInfo>().lambda();
        lambdaSup.eq(IdxBizJgSupervisionInfo::getRecord, record);
        IdxBizJgSupervisionInfo supervisionInfo = idxBizJgSupervisionInfoMapper.selectOne(lambdaSup);
        if (supervisionInfo != null && !ObjectUtils.isEmpty(equipInfo.get("orgBranchCode"))) {
            supervisionInfo.setOrgBranchCode(Objects.toString(equipInfo.get("orgBranchCode"), "").split("_")[0]);
            supervisionInfo.setOrgBranchName(Objects.toString(equipInfo.get("orgBranchCode"), "").split("_")[1]);
            idxBizJgSupervisionInfoMapper.updateById(supervisionInfo);
        }
        // 注册信息
        LambdaQueryWrapper<IdxBizJgRegisterInfo> lambdaReg = new QueryWrapper<IdxBizJgRegisterInfo>().lambda();
        lambdaReg.eq(IdxBizJgRegisterInfo::getRecord, record);
        IdxBizJgRegisterInfo registerInfo = idxBizJgRegisterInfoMapper.selectOne(lambdaReg);
        String equCode = Objects.toString(equipInfo.get("equCode"), null);
        if (registerInfo != null) {
            registerInfo.setUseOrgCode(jgUseRegistration.getUseRegistrationCode());
            registerInfo.setEquCodeType(Objects.toString(equipInfo.get("equCodeType"), null));
            // 新提交或暂存后提交需生成设备代码
            equCode = ObjectUtils.isEmpty(equipInfo.get("equCode")) && !StringUtils.isEmpty(jgUseRegistration.getReceiveCompanyCode())
                    ? useRegistrationService.getEquCode(registerInfo, jgUseRegistration.getReceiveCompanyCode())
                    : Objects.toString(equipInfo.get("equCode"), null);
            registerInfo.setEquCode(equCode);// 设备代码
            registerInfo.setEquPrice(Objects.toString(equipInfo.get("equPrice"), null));
            registerInfo.setInstallationIsComplete(equipInfo.getOrDefault("installationIsComplete", "1").toString());
            if (EquipmentClassifityEnum.CC.getCode().equals(equipInfo.get("EQU_LIST_CODE"))) {
                registerInfo.setCarNumber((String) equipInfo.get("carNumber"));
            }
            idxBizJgRegisterInfoMapper.updateById(registerInfo);
        }
        // 设计信息
        LambdaQueryWrapper<IdxBizJgDesignInfo> lambdaDes = new QueryWrapper<IdxBizJgDesignInfo>().lambda();
        lambdaDes.eq(IdxBizJgDesignInfo::getRecord, record);
        IdxBizJgDesignInfo designInfo = idxBizJgDesignInfoService.getOne(lambdaDes);
        if (designInfo != null) {
            designInfo.setDesignUnitCreditCode(MapUtil.getStr(equipInfo, "designUnitCreditCode"));
            designInfo.setDesignUnitName(MapUtil.getStr(equipInfo, "designUnitName"));
            designInfo.setDesignLicenseNum(MapUtil.getStr(equipInfo, "designLicenseNum"));
            designInfo.setDesignUseDate(MapUtil.getStr(equipInfo, "designUseDate"));
            designInfo.setDesignDate(!StringUtils.isEmpty(equipInfo.get("designDate")) ? DateUtil.parse(Objects.toString(equipInfo.get("designDate"), null), "yyyy-MM-dd") : null);
            designInfo.setDrawingDo(ObjectUtils.isEmpty(equipInfo.get("drawingDo")) ? null : Objects.toString(equipInfo.get("drawingDo"), null));
            designInfo.setAppraisalUnit(ObjectUtils.isEmpty(equipInfo.get("appraisalUnit")) ? null : Objects.toString(equipInfo.get("appraisalUnit"), null));
            designInfo.setAppraisalDate(ObjectUtils.isEmpty(equipInfo.get("appraisalDate")) ? null : Objects.toString(equipInfo.get("appraisalDate"), null));
            designInfo.setDesignDoc(ObjectUtils.isEmpty(equipInfo.get("DESIGN_DOC")) ? null : toJSONString(equipInfo.get("DESIGN_DOC")));
            designInfo.setDesignStandard(ObjectUtils.isEmpty(equipInfo.get("designStandard")) ? null : toJSONString(equipInfo.get("designStandard")));
            designInfo.setOtherAccessoriesDes(ObjectUtils.isEmpty(equipInfo.get("otherAccessoriesDes")) ? null : toJSONString(equipInfo.get("otherAccessoriesDes")));
            idxBizJgDesignInfoMapper.updateById(designInfo);
        }
        // 制造信息
        LambdaQueryWrapper<IdxBizJgFactoryInfo> factoryInfoWrapper = new LambdaQueryWrapper<>();
        factoryInfoWrapper.eq(IdxBizJgFactoryInfo::getRecord, record);
        IdxBizJgFactoryInfo idxBizJgFactoryInfo = idxBizJgFactoryInfoService.getOne(factoryInfoWrapper);
        if (idxBizJgFactoryInfo != null) {
            idxBizJgFactoryInfo.setProduceUnitCreditCode(MapUtil.getStr(equipInfo, "produceUnitCreditCode"));
            idxBizJgFactoryInfo.setProduceUnitName(MapUtil.getStr(equipInfo, "produceUnitName"));
            idxBizJgFactoryInfo.setFactoryNum(MapUtil.getStr(equipInfo, "factoryNum"));
            idxBizJgFactoryInfo.setProduceLicenseNum(MapUtil.getStr(equipInfo, "produceLicenseNum"));
            idxBizJgFactoryInfo.setProduceDate(!StringUtils.isEmpty(equipInfo.get("produceDate")) ? DateUtil.parse(Objects.toString(equipInfo.get("produceDate"), null), "yyyy-MM-dd") : null);
            idxBizJgFactoryInfo.setImported(ObjectUtils.isEmpty(equipInfo.get("imported")) ? null : Objects.toString(equipInfo.get("imported"), null));
            idxBizJgFactoryInfo.setProduceCountry(ObjectUtils.isEmpty(equipInfo.get("produceCountry")) ? null : Objects.toString(equipInfo.get("produceCountry"), null));
            idxBizJgFactoryInfo.setOtherAccessoriesFact(ObjectUtils.isEmpty(equipInfo.get("otherAccessoriesFact")) ? null : toJSONString(equipInfo.get("otherAccessoriesFact")));
            idxBizJgFactoryInfo.setInsUseMaintainExplain(ObjectUtils.isEmpty(equipInfo.get("insUseMaintainExplain")) ? null : toJSONString(equipInfo.get("insUseMaintainExplain")));
            idxBizJgFactoryInfo.setFactoryStandard(ObjectUtils.isEmpty(equipInfo.get("factoryStandard")) ? null : toJSONString(equipInfo.get("factoryStandard")));
            idxBizJgFactoryInfo.setFactSupervisionInspectionReport(ObjectUtils.isEmpty(equipInfo.get("factSupervisionInspectionReport")) ? null : toJSONString(equipInfo.get("factSupervisionInspectionReport")));
            idxBizJgFactoryInfo.setBoilerEnergyEfficiencyCertificate(ObjectUtils.isEmpty(equipInfo.get("boilerEnergyEfficiencyCertificate")) ? null : toJSONString(equipInfo.get("boilerEnergyEfficiencyCertificate")));
            idxBizJgFactoryInfoMapper.updateById(idxBizJgFactoryInfo);
        }

        // 使用信息
        LambdaQueryWrapper<IdxBizJgUseInfo> lambda = new QueryWrapper<IdxBizJgUseInfo>().lambda();
        lambda.eq(IdxBizJgUseInfo::getRecord, record);
        IdxBizJgUseInfo useInfo = useInfoMapper.selectOne(lambda);
        String usePlace = "";
        if (useInfo != null) {
            useInfo.setIsIntoManagement(Boolean.TRUE);
            useInfo.setUseUnitCreditCode(Objects.toString(equipInfo.get("useUnitCreditCode"), null));
            useInfo.setUseUnitName(Objects.toString(equipInfo.get("useUnitName"), null));
            useInfo.setProvince("610000");
            useInfo.setProvinceName("陕西省");
            useInfo.setCity(Objects.toString(equipInfo.get("city"), null));
            useInfo.setUseInnerCode(Objects.toString(equipInfo.get("useInnerCode"), null));
            useInfo.setCityName(useCityName);
            useInfo.setCounty(Objects.toString(equipInfo.get("county"), null));
            useInfo.setCountyName(useCountyName);
            useInfo.setFactoryUseSiteStreet(Objects.toString(equipInfo.get("factoryUseSiteStreet"), null));
            useInfo.setStreetName(useStreetName);
            useInfo.setAddress(Objects.toString(equipInfo.get("address"), null));
            useInfo.setIsNotXiXian(Objects.toString(equipInfo.get("isXixian"), null));
            useInfo.setEstateUnitCreditCode(Optional.ofNullable(equipInfo.get("estateUnitName"))
                    .map(Object::toString)
                    .filter(s -> s.contains("_"))
                    .map(s -> s.split("_", 2))
                    .filter(parts -> parts.length == 2)
                    .map(parts -> parts[0])
                    .orElse(null));
            useInfo.setEstateUnitName(Optional.ofNullable(equipInfo.get("estateUnitName"))
                    .map(Object::toString)
                    .filter(s -> s.contains("_"))
                    .map(s -> s.split("_", 2))
                    .filter(parts -> parts.length == 2)
                    .map(parts -> parts[1])
                    .orElse(null));
            useInfo.setPhone(Objects.toString(equipInfo.get("phone"), null));
            useInfo.setSafetyManager(Objects.toString(Optional.ofNullable(equipInfo.get("safetyManager"))
                    .map(Object::toString)
                    .filter(s -> s.contains("_"))
                    .map(s -> s.split("_", 2))
                    .filter(parts -> parts.length == 2)
                    .map(parts -> parts[0])
                    .orElse(null), null));
            useInfo.setUseDate(Objects.toString(equipInfo.get("useDate"), null));
            useInfo.setLongitudeLatitude(toJSONString(equipInfo.get("longitudeLatitude")));
            useInfo.setUsePlace((String) equipInfo.get("usePlace"));
            useInfo.setOldUseRegistrationTable(toJSONString(equipInfo.get("oldUseRegistrationTable")));
            useInfo.setOldUseRegistrationCertificate(toJSONString(equipInfo.get("oldUseRegistrationCertificate")));
            useInfo.setORegDate(Objects.toString(equipInfo.get("oRegDate"), null));
            useInfo.setORegUnit(Objects.toString(equipInfo.get("oRegUnit"), null));
            // 历史平台登记，将设备状态改为在用
            if (useInfo.getEquState() == null) {
                useInfo.setEquState(EquimentEnum.ZAIYONG.getCode().toString());
            }
            usePlace = useInfo.getProvinceName() + "/" + useInfo.getCityName() + "/" + useInfo.getCountyName() + "/" + useInfo.getStreetName();
            useInfoMapper.updateById(useInfo);
        }

        LambdaQueryWrapper<IdxBizJgOtherInfo> otherLambda = new QueryWrapper<IdxBizJgOtherInfo>().lambda();
        otherLambda.eq(IdxBizJgOtherInfo::getRecord, record);
        IdxBizJgOtherInfo otherInfo = otherInfoMapper.selectOne(otherLambda);

        // 生成监管码 96333码
        useRegistrationService.createCode(equipInfo, jgUseRegistration, registerInfo, useInfo, otherInfo);
        equipInfo.put("equCode", equCode);
        // 更新es
        equipInfo.put("equipId", record);
        useRegistrationService.updateEsData2(usePlace, equipInfo, otherInfo, useInfo, jgUseRegistration, equipInfo);
        useRegistrationService.updateById(jgUseRegistration);
        useRegistrationService.historyEquGenManageRelated(equipInfo, jgUseRegistration, registerInfo, idxBizJgFactoryInfo);
        String routePath = useRegistrationService.buildTaskModel(jgUseRegistration, equipInfo, getSelectedOrgInfo());
        jgResumeInfoService.createWithModel(JgResumeInfoDto.builder()
                .applyNo(jgUseRegistration.getApplyNo())
                .businessType(BusinessTypeEnum.JG_HISTORY_USAGE_REGISTRATION.getName())
                .businessId(jgUseRegistration.getSequenceNbr() + "")
                .equId(Objects.toString(record, null))
                .approvalUnit(jgUseRegistration.getReceiveOrgName())
                .approvalUnitCode(jgUseRegistration.getReceiveOrgCode())
                .status("正常")
                .routePath(routePath)
                .changeContent(BusinessTypeEnum.JG_HISTORY_USAGE_REGISTRATION.getName() + "业务")
                .build());
        jgUseRegistration.setCreateDate(new Date());
        useRegistrationService.save(jgUseRegistration);
        // 业务管理设备信息保存
        JgUseRegistrationEq jgRelationEquip = new JgUseRegistrationEq();
        jgRelationEquip.setEquId(record);
        jgRelationEquip.setEquipTransferId(jgUseRegistration.getSequenceNbr().toString());
        jgRelationEquipMapper.insert(jgRelationEquip);
        return useRegistrationService.getBaseMapper().selectById(jgUseRegistration.getSequenceNbr());
    }

    /**
     * 添加设备的业务履历
     */
    public void addEquipResume(JSONObject equipInfo, JgUseRegistration useRegistration) {
        String record = (String) equipInfo.get(RECORD);
        JgResumeInfoDto resumeInfoDto = JgResumeInfoDto.builder()
                .applyNo(null)
                .businessType(BusinessTypeEnum.JG_EQUIP_CLAIM.getName())
                .businessId(record)
                .equId(record)
                .approvalUnit(useRegistration.getReceiveOrgName())
                .approvalUnitCode(useRegistration.getReceiveOrgName())
                .status("正常")
                .changeContent(BusinessTypeEnum.JG_EQUIP_CLAIM.getName() + "业务")
                .routePath(null)
                .build();
        JgResumeInfo resumeInfo = new JgResumeInfo();
        BeanUtils.copyProperties(resumeInfoDto, resumeInfo);
        jgResumeInfoService.save(resumeInfo);
    }

    /**
     * 参数校验 - 同 设备录入的逻辑
     */
    public void checkParams(LinkedHashMap equipInfo) {
        String dataSource = (String) equipInfo.get(DATA_SOURCE);
        String record = (String) equipInfo.get(RECORD);
        // 设备代码 字段的唯一性校验
        jgRegisterInfoService.checkEquCodeUniqueness(equipInfo);
        // 车用气瓶业务里面的 产品编号 校验唯一性（产品编号在车用气瓶范围内全局唯一）
        jgRegisterInfoService.checkFactoryNumUniqueness(equipInfo);
        // 96333码 字段的唯一性校验
        jgRegisterInfoService.check96333Code(equipInfo);
        // 气瓶 校验制造单位统一信用代码与出场编码唯一
        jgRegisterInfoService.checkFactoryNumUniqueWithGasCylinder(equipInfo, record);
        // 历史（车用气瓶）设备校验使用登记证编号 VIN 全库唯一
        jgRegisterInfoService.hisEquCheckUseRegCodeAndVINUniqueness(equipInfo, record);
        // 历史有使用登记证的场车设备校验车牌号的唯一性
        jgRegisterInfoService.checkCarNumberUniquenessWithHisCC(equipInfo, record, dataSource);
    }

    /**
     * 认领 更新设备信息
     *
     * @param equipInfo
     */
    public void updateEquipInfoWithClaim(JSONObject equipInfo, JSONObject equipParams, boolean isIntoManagement) {
        Date timestamp = new Date();
        AgencyUserModel userModel = getSelectedOrgInfo().getUserModel();
        CompanyBo company = getSelectedOrgInfo().getCompany();
        // 设备种类
        String equList = Objects.toString(equipInfo.get(EQU_LIST));
        String record = equipInfo.get(RECORD).toString();

        // 使用信息
        IdxBizJgUseInfo useInfo = JSON.parseObject(toJSONString(equipInfo), IdxBizJgUseInfo.class);
        useInfo.setRecord(record);
        useInfo.setRecDate(timestamp);
        useInfo.setCreateDate(timestamp);
        useInfo.setDataSource(JG_HIS_XA_CLAIM);
        useInfo.setIsIntoManagement(isIntoManagement);
        useInfo.setUseUnitCreditCode(company.getCompanyCode());
        useInfo.setUseUnitName(company.getCompanyName());
        useInfo.setSequenceNbr(Objects.toString(equipInfo.get("USEINFO_SEQ")));
        idxBizJgUseInfoService.saveOrUpdateData(useInfo);
        // 设计信息
        IdxBizJgDesignInfo designInfo = JSON.parseObject(toJSONString(equipInfo), IdxBizJgDesignInfo.class);
        designInfo.setRecord(record);
        designInfo.setRecDate(timestamp);
        designInfo.setSequenceNbr(Objects.toString(equipInfo.get("DESIGNINFO_SEQ")));
        iIdxBizJgDesignInfoService.saveOrUpdateData(designInfo);
        // 制造信息
        IdxBizJgFactoryInfo factoryInfo = JSON.parseObject(toJSONString(equipInfo), IdxBizJgFactoryInfo.class);
        factoryInfo.setRecord(record);
        factoryInfo.setRecDate(timestamp);
        factoryInfo.setProductQualityYieldProve(ValidationUtil.isEmpty(equipInfo.get("PRODUCT_QUALITY_YIELD_PROVE")) ? null : toJSONString(equipInfo.get("PRODUCT_QUALITY_YIELD_PROVE")));
        factoryInfo.setSequenceNbr(Objects.toString(equipInfo.get("FACTORYINFO_SEQ")));
        iIdxBizJgFactoryInfoService.saveOrUpdateData(factoryInfo);
        // 施工信息
        IdxBizJgConstructionInfo constructionInfo = JSON.parseObject(toJSONString(equipInfo), IdxBizJgConstructionInfo.class);
        constructionInfo.setRecord(record);
        constructionInfo.setRecDate(timestamp);
        constructionInfo.setSequenceNbr(Objects.toString(equipInfo.get("CONSTRUCTIONINFO_SEQ")));
        iIdxBizJgConstructionInfoService.saveOrUpdateData(constructionInfo);
        // 注册登记信息
        IdxBizJgRegisterInfo registerInfo = JSON.parseObject(toJSONString(equipInfo), IdxBizJgRegisterInfo.class);
        registerInfo.setRecord(record);
        registerInfo.setRecDate(timestamp);
        registerInfo.setRegisterState(jgRegisterInfoService.getRegCode());
        registerInfo.setUseOrgCode(Objects.toString(equipInfo.get("useRegistrationCode"), null));
        registerInfo.setProductPhoto(ValidationUtil.isEmpty(equipInfo.get("PRODUCT_PHOTO")) ? null : toJSONString(equipInfo.get("PRODUCT_PHOTO")));
        registerInfo.setOtherAccessoriesReg(ValidationUtil.isEmpty(equipInfo.get("OTHER_ACCESSORIES_REG")) ? null : toJSONString(equipInfo.get("OTHER_ACCESSORIES_REG")));
        registerInfo.setSequenceNbr(Objects.toString(equipInfo.get("REGISTERINFO_SEQ")));
        jgRegisterInfoService.saveOrUpdate(registerInfo);
        // 监督管理
        IdxBizJgSupervisionInfo supervisionInfo = JSON.parseObject(toJSONString(equipInfo), IdxBizJgSupervisionInfo.class);
        supervisionInfo.setRecord(record);
        supervisionInfo.setRecDate(timestamp);
        supervisionInfo.setSequenceNbr(Objects.toString(equipInfo.get("SUPERVISIONINFO_SEQ")));
        iIdxBizJgSupervisionInfoService.saveOrUpdateData(supervisionInfo);
        // 其他信息
        IdxBizJgOtherInfo otherInfo = JSON.parseObject(toJSONString(equipInfo), IdxBizJgOtherInfo.class);
        otherInfo.setRecord(record);
        otherInfo.setClaimStatus("已认领");
        otherInfo.setRecDate(timestamp);
        otherInfo.setSequenceNbr(Objects.toString(equipInfo.get("OTHERINFO_SEQ")));
        iIdxBizJgOtherInfoService.saveOrUpdateData(otherInfo);
        // 检验检测信息
        IdxBizJgInspectionDetectionInfo inspectionDetectionInfo = JSON.parseObject(toJSONString(equipInfo), IdxBizJgInspectionDetectionInfo.class);
        List<Map<String, Object>> inspectionAndTestingInstitutions = commonService.getUnitListByType("inspection", "gasCylindersForCars", false);
        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(timestamp);
        if (inspectionDetectionInfo.getNextInspectDate() != null) {
            inspectionDetectionInfo.setNextInspectDate(DateUtil.parse(DateUtil.format(inspectionDetectionInfo.getNextInspectDate(), DatePattern.NORM_DATE_PATTERN)));
        }
        inspectionDetectionInfo.setSequenceNbr(Objects.toString(equipInfo.get("INSPECTIONDETECTIONINFO_SEQ")));
        iIdxBizJgInspectionDetectionInfoService.saveOrUpdateData(inspectionDetectionInfo);
        // 技术参数
        jgRegisterInfoService.saveOrUpdateEquParams(new LinkedHashMap<>(equipInfo), new LinkedHashMap<>(equipParams), equList, record, timestamp, "edit");
        // 更新es
        jgRegisterInfoService.checkEsData(record);
    }
}
