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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
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.dto.CountDto;
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.common.api.dto.DPFilterParamDto;
import com.yeejoin.amos.boot.module.common.api.dto.DPFilterParamForDetailDto;
import com.yeejoin.amos.boot.module.common.api.dto.FormValue;
import com.yeejoin.amos.boot.module.common.api.dto.LegendDataDto;
import com.yeejoin.amos.boot.module.common.api.enums.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.common.api.enums.*;
import com.yeejoin.amos.boot.module.jg.api.dto.EquipBizCountDto;
import com.yeejoin.amos.boot.module.jg.api.dto.FourColorCountDataDto;
import com.yeejoin.amos.boot.module.jg.api.dto.JgUseRegistrationManageDto;
import com.yeejoin.amos.boot.module.jg.api.dto.SafetyProblemTracingDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgCertificateChangeRecord;
import com.yeejoin.amos.boot.module.jg.api.entity.JgUseRegistrationManage;
import com.yeejoin.amos.boot.module.jg.api.entity.SafetyProblemTracing;
import com.yeejoin.amos.boot.module.jg.api.enums.*;
import com.yeejoin.amos.boot.module.jg.api.mapper.*;
import com.yeejoin.amos.boot.module.statistcs.biz.utils.JsonUtils;
import com.yeejoin.amos.boot.module.statistics.api.dto.*;
import com.yeejoin.amos.boot.module.statistics.api.enums.RegulatoryUnitLevelEnum;
import com.yeejoin.amos.boot.module.statistics.api.mapper.CylinderBusinessStatisticsMapper;
import com.yeejoin.amos.boot.module.statistics.api.mapper.JGStatisticsMapper;
import com.yeejoin.amos.boot.module.statistics.api.mapper.ZLStatisticsMapper;
import com.yeejoin.amos.boot.module.ymt.api.dto.EquipmentCategoryDto;
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.*;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
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.ValidationUtil;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.stream.Collectors;

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

/**
 * 大屏统计实现类
 *
 * @author Administrator
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class JGDPStatisticsServiceImpl {

    /**
     * 压力容器设备种类
     */
    private final static String EQU_LIST_CYLINDER = "2000";

    /**
     * 气瓶设备类别
     */
    private final static String EQU_CATEGORY_CYLINDER = "2300";

    /**
     * 单位类型-使用单位
     */
    private final static String COMPANY_TYPE_USE = "使用单位";
    private final static String COMPANY_TYPE_PERSON = "个人主体";

    /**
     * 单位类型-安装改造维修单位
     */
    private final static String COMPANY_TYPE_MAINTENANCE = "安装改造维修单位";

    /**
     * 单位类型-制造单位
     */
    private final static String COMPANY_TYPE_MANUFACTURE = "制造单位";

    /**
     * 单位类型-充装单位
     */
    private final static String COMPANY_TYPE_FILLING = "充装单位";

    /**
     * 单位类型-充装单位
     */
    private final static String COMPANY_TYPE_DESIGN = "设计单位";


    /**
     * 检验检测机构-检验检测机构
     */
    private final static String COMPANY_TYPE_JYJC = "检验检测机构";


    /**
     * 监管-中屏-地图行政区划code
     */
    private final static String REGION_CODE = "regionCode";

    /**
     * 监管-中屏-地图行政区划code
     */
    private final static String REGION_NAME = "regionName";

    // 设备分类表单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 EQUSTATE = "EQU_STATE";
    private static final String CONSTRUCTIONTYPE = "CONSTRUCTION_TYPE";
    // 设备代码
    private static final String EQU_CODE = "EQU_CODE";
    // 96333识别码
    private static final String SEQUENCE_NBR = "SEQUENCE_NBR";
    private static final String FACTORY_NUM = "FACTORY_NUM";
    // 设备种类
    public static final String EQU_LIST = "EQU_LIST";
    // 设备类别
    public static final String EQU_CATEGORY = "EQU_CATEGORY";
    // 设备品种
    public static final String EQU_DEFINE = "EQU_DEFINE";
    // 是否车用气瓶
    public static final String WHETHER_VEHICLE_CYLINDER = "WHETHER_VEHICLE_CYLINDER";
    // 是否撬装式压力容器
    public static final String WHETHER_SKID_MOUNTED_PRESSURE_VESSEL = "WHETHER_SKID_MOUNTED_PRESSURE_VESSEL";
    // 设备纳管  纳管：true 未纳管：false
    public static final String IS_INTO_MANAGEMENT = "IS_INTO_MANAGEMENT";
    // 设备来源 jg：新设备录入  jg_his：历史数据录入
    public static final String DATA_SOURCE = "DATA_SOURCE";
    // 设备来源名称 jg：新设备  jg_his：历史数据
    public static final String DATA_SOURCE_NAME = "DATA_SOURCE_NAME";
    public static final String USE_PLACE_CODE = "USE_PLACE_CODE";
    public static final String EQU_CATEGORY_CODE = "EQU_CATEGORY_CODE";
    public static final String PROJECT_CONTRAPTION = "PROJECT_CONTRAPTION";// 工程装置名称
    // 管辖机构redis缓存key
    private static final String REGULATOR_UNIT_TREE = "REGULATOR_UNIT_TREE";

    @Value("classpath:/json/registrationBasic.json")
    private Resource registrationBasicJson;

    @Value("classpath:/json/jgdp_businessType.json")
    private Resource allBusinessType;

    private final JgUseRegistrationMapper useRegistrationMapper;

    private final CylinderBusinessStatisticsMapper businessStatisticsMapper;

    private final JgEnableDisableMapper enableDisableMapper;

    private final JgScrapCancelMapper scrapCancelMapper;

    private final RestHighLevelClient restHighLevelClient;

    private final TzBaseEnterpriseInfoMapper enterpriseInfoMapper;

    private final CommonMapper commonMapper;

    private final TzsUserInfoMapper userInfoMapper;

    private final ZLStatisticsMapper zlStatisticsMapper;

    private final JGStatisticsMapper jgStatisticsMapper;

    private final JgUseRegistrationManageMapper jgUseRegistrationManageMapper;

    private final StCommonServiceImpl stCommonService;

    private final RedisUtils redisUtils;

    private final SafetyProblemTracingMapper safetyProblemTracingMapper;

    private final JgCertificateChangeRecordMapper jgCertificateChangeRecordMapper;

    private final IdxBizJgRegisterInfoMapper idxBizJgRegisterInfoMapper;

    private final EquipmentCategoryMapper equipmentCategoryMapper;

    private final IdxBizJgUseInfoMapper idxBizJgUseInfoMapper;

    private final IdxBizJgFactoryInfoMapper idxBizJgFactoryInfoMapper;

    private final IdxBizJgDesignInfoMapper idxBizJgDesignInfoMapper;

    private final IdxBizJgSupervisionInfoMapper idxBizJgSupervisionInfoMapper;

    private final IdxBizJgTechParamsRopewayMapper idxBizJgTechParamsRopewayMapper;

    private final IdxBizJgTechParamsBoilerMapper idxBizJgTechParamsBoilerMapper;

    private final IdxBizJgConstructionInfoMapper idxBizJgConstructionInfoMapper;

    private final IdxBizJgOtherInfoMapper idxBizJgOtherInfoMapper;

    private final IdxBizJgMaintenanceRecordInfoMapper idxBizJgMaintenanceRecordInfoMapper;

    private final IdxBizJgInspectionDetectionInfoMapper idxBizJgInspectionDetectionInfoMapper;

    private final IdxBizJgMainPartsMapper idxBizJgMainPartsMapper;

    private final IdxBizJgProtectionDevicesMapper idxBizJgProtectionDevicesMapper;

    private final IdxBizJgTechParamsElevatorMapper idxBizJgTechParamsElevatorMapper;

    private final IdxBizJgTechParamsVehicleMapper idxBizJgTechParamsVehicleMapper;

    private final IdxBizJgTechParamsRidesMapper idxBizJgTechParamsRidesMapper;

    private final IdxBizJgTechParamsVesselMapper idxBizJgTechParamsVesselMapper;

    private final IdxBizJgTechParamsPipelineMapper idxBizJgTechParamsPipelineMapper;

    private final IdxBizJgTechParamsLiftingMapper idxBizJgTechParamsLiftingMapper;

    private final DataDictionaryServiceImpl iDataDictionaryService;


    private List<LegendDataDto> buildLegendDataList() {
        List<LegendDataDto> legendDataDtos = new ArrayList<>();
        legendDataDtos.add(LegendDataDto.builder().dataKey("newDevice").value("新增登记设备").build());
        legendDataDtos.add(LegendDataDto.builder().dataKey("stoppedDevice").value("报停设备").build());
        legendDataDtos.add(LegendDataDto.builder().dataKey("scrappedDevice").value("报废设备").build());
        return legendDataDtos;
    }

    public Map<String, Object> useRegisterCountByEquList(DPFilterParamDto dpFilterParamDto) {
        // 1.查询条件构造未上送时间时，默认查询数据为近一个月数据
        this.setDefaultFilter(dpFilterParamDto);
        // 2.按照前端约定格式返回数据
        Map<String, Object> result = new HashMap<>();
        List<LegendDataDto> legendDataDtos = this.buildLegendDataList();
        //2.1 图列数据构造
        result.put("legendData", legendDataDtos);
        //2.2 x轴数据构造
        result.put("xdata", this.getXData(StCommonServiceImpl.getEquipmentCategory()));
        //2.3 y轴数据构造
        this.buildYData(result, dpFilterParamDto, StCommonServiceImpl.getEquipmentCategory());
        return result;
    }

    private void buildYData(Map<String, Object> result, DPFilterParamDto dpFilterParamDto, List<EquipmentCategoryDto> equipmentCategoryDtos) {
        // 待统计的数据本来sql可以单独统计，但是要求气瓶单独从压力容器里拎出来，与八大类同级，故java处理
        // 1.新增登记统计
        result.put("newDevice", this.getNewDeviceCountData(dpFilterParamDto, equipmentCategoryDtos));
        // 2.新增报停设备统计
        result.put("stoppedDevice", this.getStoppedDeviceCountData(dpFilterParamDto, equipmentCategoryDtos));
        // 3.新增报废设备统计
        result.put("scrappedDevice", this.getScrappedDeviceCountData(dpFilterParamDto, equipmentCategoryDtos));
    }

    private List<Integer> getNewDeviceCountData(DPFilterParamDto dpFilterParamDto, List<EquipmentCategoryDto> equipmentCategoryDtos) {
        List<EquipBizCountDto> staticsData = useRegistrationMapper.queryNewDeviceStaticListData(dpFilterParamDto);
        return countNumByEquList(equipmentCategoryDtos, staticsData);
    }

    private List<Integer> getStoppedDeviceCountData(DPFilterParamDto dpFilterParamDto, List<EquipmentCategoryDto> equipmentCategoryDtos) {
        List<EquipBizCountDto> staticsData = enableDisableMapper.queryStoppedDeviceStaticListData(dpFilterParamDto);
        return countNumByEquList(equipmentCategoryDtos, staticsData);
    }

    private List<Integer> getScrappedDeviceCountData(DPFilterParamDto dpFilterParamDto, List<EquipmentCategoryDto> equipmentCategoryDtos) {
        List<EquipBizCountDto> staticsData = scrapCancelMapper.queryScrappedDeviceStaticListData(dpFilterParamDto);
        return countNumByEquList(equipmentCategoryDtos, staticsData);
    }


    private List<Integer> countNumByEquList(List<EquipmentCategoryDto> equipmentCategoryDtos, List<EquipBizCountDto> bizCountDtos) {
        List<Integer> lineData = new ArrayList<>();
        // 8大类数据统计数量
        equipmentCategoryDtos.forEach(equipmentCategoryDto -> {
            int num = 0;
            // 压力容器要去掉气瓶2300，气瓶单独统计
            if (EQU_LIST_CYLINDER.equals(equipmentCategoryDto.getCode())) {
                num = bizCountDtos.stream().filter(c -> c.getEquList().equals(equipmentCategoryDto.getCode()) && !EQU_CATEGORY_CYLINDER.equals(c.getEquCategory())).mapToInt(EquipBizCountDto::getNum).sum();
            } else {
                num = bizCountDtos.stream().filter(c -> c.getEquList().equals(equipmentCategoryDto.getCode())).mapToInt(EquipBizCountDto::getNum).sum();
            }
            lineData.add(num);
        });
        // 再增加气瓶(设备类别2300)专项
        int num = bizCountDtos.stream().filter(c -> EQU_CATEGORY_CYLINDER.equals(c.getEquCategory())).mapToInt(EquipBizCountDto::getNum).sum();
        lineData.add(num);
        return lineData;
    }

    private List<String> getXData(List<EquipmentCategoryDto> equipmentCategoryDtos) {
        // 8大类  + 气瓶 注意数据顺序和要和这个x轴一致
        List<String> names = equipmentCategoryDtos.stream().map(EquipmentCategoryDto::getName).collect(Collectors.toList());
        names.add("气瓶");
        return names;
    }


    private void setDefaultFilter(DPFilterParamDto dpFilterParamDto) {
        if (StringUtils.isEmpty(dpFilterParamDto.getBeginDate())) {
            dpFilterParamDto.setBeginDate(cn.hutool.core.date.DateUtil.offsetDay(new Date(), -30).toDateStr());
        }
        if (StringUtils.isEmpty(dpFilterParamDto.getEndDate())) {
            dpFilterParamDto.setEndDate(DateUtil.today());
        }
    }

    private void setDefaultFilter30(DPFilterParamDto dpFilterParamDto) {
        if (StringUtils.isEmpty(dpFilterParamDto.getBeginDate())) {
            dpFilterParamDto.setBeginDate(cn.hutool.core.date.DateUtil.offsetDay(new Date(), -29).toDateStr());
        }
        if (StringUtils.isEmpty(dpFilterParamDto.getEndDate())) {
            dpFilterParamDto.setEndDate(DateUtil.today());
        }
    }


    public Map<String, Object> getCenterMapCountDataForGlobal(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> result = new HashMap<>();
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (StringUtils.isEmpty(orgCode)) {
            return setDefaultCount(result);
        }
        // 1.气瓶数量统计
        long cylinderNum = stCommonService.staticsCenterMapCountDataForCylinder(result, orgCode, true, true, false);
        //1.8大类设备数量统计,压力容器里包括气瓶所以需要特殊处理，在统计压力容器时去掉气瓶的数量
        stCommonService.staticsCenterMapCountDataForEquip(result, cylinderNum, orgCode, true, true, false);
        //2.压力管道长度统计
        stCommonService.staticsCenterMapCountDataForPipeline(result, orgCode, true, false);
        //3.单位数量统计
        this.staticsCenterMapCountDataForCompany(result, orgCode, dpFilterParamDto.getCityCode());
        //4.人员数量统计
        this.staticsCenterMapCountDataForPerson(result, dpFilterParamDto, orgCode);
        return result;
    }

    public Map<String, Object> centerMapCountForGlobalNoSupervisoryCode(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> result = new HashMap<>();
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (StringUtils.isEmpty(orgCode)) {
            return setDefaultCount(result);
        }
        // 1.气瓶数量统计
        long cylinderNum = stCommonService.staticsCenterMapCountDataForCylinder(result, orgCode, false, true, false);
        //1.8大类设备数量统计,压力容器里包括气瓶所以需要特殊处理，在统计压力容器时去掉气瓶的数量
        stCommonService.staticsCenterMapCountDataForEquip(result, cylinderNum, orgCode, false, true, false);
        //2.压力管道长度统计
        stCommonService.staticsCenterMapCountDataForPipeline(result, orgCode, false, false);
        return result;
    }

    private Map<String, Object> getCenterMapOverviewData(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> result = new HashMap<>();
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (StringUtils.isEmpty(orgCode)) {
            return setDefaultCount(result);
        }
        // 0. 气瓶数量统计
        long cylinderNum = stCommonService.staticsCenterMapCountDataForCylinder(result, orgCode, true, true, false);
        // 1. 8大类设备数量统计,压力容器里包括气瓶所以需要特殊处理，在统计压力容器时去掉气瓶的数量
        stCommonService.staticsCenterMapCountDataForEquip(result, cylinderNum, orgCode, true, true, false);
        // 2. 压力管道长度统计
        stCommonService.staticsCenterMapCountDataForPipeline(result, orgCode, true, false);
        // 3. 人员数量统计
        this.staticsCenterMapCountDataForPerson(result, dpFilterParamDto, orgCode);
        return result;
    }

    private Map<String, Object> setDefaultCount(Map<String, Object> result) {
        result.put(DPMapStatisticsItemEnum.LIFTING_MACHINERY.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.PRESSURE_VESSELS.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.GAS_UNITS.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.PRESSURE_PIPELINES.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.PASSENGER_ROPEWAYS.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.MANUFACTURING_UNITS.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.BOILERS.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.TOTAL.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.OPERATORS.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.CONSTRUCTION_UNITS.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.GAS.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.ON_SITE_MOTOR_VEHICLES.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.ELEVATORS.getCode(), 0);
        result.put(DPMapStatisticsItemEnum.LARGE_AMUSEMENT_FACILITIES.getCode(), 0);
        return result;
    }

    private void staticsCenterMapCountDataForPerson(Map<String, Object> result, DPFilterParamDto dpFilterParamDto, String orgCode) {
        if (orgCode == null) {
            result.put(DPMapStatisticsItemEnum.OPERATORS.getCode(), 0);
            return;
        }
        Long num = userInfoMapper.countUserByPostAndAreaCode(orgCode, "6552", dpFilterParamDto.getCityCode());
        result.put(DPMapStatisticsItemEnum.OPERATORS.getCode(), num);
    }

    private void staticsCenterMapCountDataForCompany(Map<String, Object> result, String orgCode, String cityCode) {
        if (orgCode == null) {
            setDefaultCompanyCountData(result);
            return;
        }
        List<CountDto> countDtos = enterpriseInfoMapper.countByUnitTypeAndOrgCode(orgCode, cityCode, false);
        result.put(DPMapStatisticsItemEnum.USERS_UNITS.getCode(), countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_USE) || c.getKeyStr().contains(COMPANY_TYPE_PERSON)).mapToInt(CountDto::getIntValue).sum());
        result.put(DPMapStatisticsItemEnum.CONSTRUCTION_UNITS.getCode(), countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_MAINTENANCE)).mapToInt(CountDto::getIntValue).sum());
        result.put(DPMapStatisticsItemEnum.MANUFACTURING_UNITS.getCode(), countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_MANUFACTURE)).mapToInt(CountDto::getIntValue).sum());
        result.put(DPMapStatisticsItemEnum.GAS_UNITS.getCode(), countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_FILLING)).mapToInt(CountDto::getIntValue).sum());
        result.put(DPMapStatisticsItemEnum.DESIGN_UNITS.getCode(), countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_DESIGN)).mapToInt(CountDto::getIntValue).sum());
    }

    private void staticsCompanyForSkjs(SkjsCountItemDto countItemDto, String orgCode, String cityCode) {
        List<CountDto> countDtos = enterpriseInfoMapper.countByUnitTypeAndOrgCode(orgCode, cityCode, false);
        int u1 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_USE) || c.getKeyStr().contains(COMPANY_TYPE_PERSON)).mapToInt(CountDto::getIntValue).sum();
        int u2 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_MAINTENANCE)).mapToInt(CountDto::getIntValue).sum();
        int u3 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_MANUFACTURE)).mapToInt(CountDto::getIntValue).sum();
        int u4 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_FILLING)).mapToInt(CountDto::getIntValue).sum();
        int u5 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_DESIGN)).mapToInt(CountDto::getIntValue).sum();
        int u6 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_JYJC)).mapToInt(CountDto::getIntValue).sum();
        countItemDto.setCompany(String.valueOf(u1 + u2 + u3 + u4 + u5 + u6));
    }

    private void staticsUserForSkjs(SkjsCountItemDto countItemDto, String regionCode, String orgCode) {
        Long num = userInfoMapper.countUserByPostAndAreaCode(orgCode, null, regionCode);
        countItemDto.setUser(String.valueOf(num));
    }


    public Map<String, Object> useRegisterCount(DPFilterParamDto dpFilterParamDto) {
        // 2.按照前端约定格式返回数据
        Map<String, Object> result = new HashMap<>();

        List legendDataList = new ArrayList();
        Map<String, Object> newDeviceMap = new HashMap<>();
        newDeviceMap.put("dataKey", "newDevice");
        newDeviceMap.put("value", "新增登记设备");
        legendDataList.add(newDeviceMap);
        Map<String, Object> scrappedDeviceMap = new HashMap<>();
        scrappedDeviceMap.put("dataKey", "scrappedDevice");
        scrappedDeviceMap.put("value", "报废设备");
        legendDataList.add(scrappedDeviceMap);
        result.put("legendData", legendDataList);
        LocalDate today = LocalDate.now();
        List xDataList = new ArrayList();
        List<Object> newDeviceList = new ArrayList();
        List<Object> scrappedDeviceList = new ArrayList();
        DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyy-MM");
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        List<Map<String, Object>> useRegisterCountList = businessStatisticsMapper.getUseRegisterCount(orgCode);
        List<Map<String, Object>> scrappedDeviceCountList = scrapCancelMapper.getScrappedDeviceCount(dpFilterParamDto);
        Map<String, Object> useRegisterCount = new HashMap<>();
        Map<String, Object> scrappedDeviceCount = new HashMap<>();
        if (CollectionUtils.isNotEmpty(useRegisterCountList)) {
            useRegisterCountList.forEach(item -> {
                useRegisterCount.put(item.get("time") + "", item.get("num"));
            });
        }
        if (CollectionUtils.isNotEmpty(scrappedDeviceCountList)) {
            scrappedDeviceCountList.forEach(item -> {
                scrappedDeviceCount.put(item.get("time") + "", item.get("num"));
            });
        }
        for (int i = 2; i >= 0; i--) {
            xDataList.add(today.minusMonths(i).format(sdf));
            newDeviceList.add(null == useRegisterCount.get(today.minusMonths(i).format(sdf)) ? 0 : Integer.valueOf(useRegisterCount.get(today.minusMonths(i).format(sdf)) + ""));
            scrappedDeviceList.add(null == scrappedDeviceCount.get(today.minusMonths(i).format(sdf)) ? 0 : Integer.valueOf(scrappedDeviceCount.get(today.minusMonths(i).format(sdf)) + ""));
        }
        result.put("xdata", xDataList);
        result.put("newDevice", newDeviceList);
        result.put("scrappedDevice", scrappedDeviceList);
        return result;

    }

    public List<Map<String, Object>> getCenterMapCountDataForOverview(DPFilterParamDto dpFilterParamDto) {
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParent(dpFilterParamDto);
        List<Map<String, Object>> result = regionModels.parallelStream().map(r -> {
            DPFilterParamDto filterParamDto = new DPFilterParamDto();
            filterParamDto.setCityCode(r.getRegionCode().toString());
            Map<String, Object> itemResult = getCenterMapOverviewData(filterParamDto);
            itemResult.put("cityCode", r.getRegionCode());
            itemResult.put("cityName", r.getRegionName());
            return itemResult;
        }).collect(Collectors.toList());
        this.setCompanyDataBatch(result);
        return result;
    }

    private void setCompanyDataBatch(List<Map<String, Object>> result) {
        List<CountDto> countDtos = enterpriseInfoMapper.countByUnitTypeAndOrgCodeNoParam();
        result.forEach(m -> {
            String cityCode = m.get("cityCode").toString();
            String orgCode = StCommonServiceImpl.getRegionCodeOrgCodeMap().get(cityCode);
            if (StringUtils.isNotEmpty(orgCode)) {
                m.put(DPMapStatisticsItemEnum.USERS_UNITS.getCode(), countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_USE) && c.getLabel().contains(orgCode)).mapToInt(CountDto::getIntValue).sum());
                m.put(DPMapStatisticsItemEnum.CONSTRUCTION_UNITS.getCode(), countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_MAINTENANCE) && c.getLabel().contains(orgCode)).mapToInt(CountDto::getIntValue).sum());
                m.put(DPMapStatisticsItemEnum.MANUFACTURING_UNITS.getCode(), countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_MANUFACTURE) && c.getLabel().contains(orgCode)).mapToInt(CountDto::getIntValue).sum());
                m.put(DPMapStatisticsItemEnum.GAS_UNITS.getCode(), countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_FILLING) && c.getLabel().contains(orgCode)).mapToInt(CountDto::getIntValue).sum());
            } else {
                setDefaultCompanyCountData(m);
            }
        });
    }

    private void setDefaultCompanyCountData(Map<String, Object> m) {
        m.put(DPMapStatisticsItemEnum.USERS_UNITS.getCode(), 0);
        m.put(DPMapStatisticsItemEnum.CONSTRUCTION_UNITS.getCode(), 0);
        m.put(DPMapStatisticsItemEnum.MANUFACTURING_UNITS.getCode(), 0);
        m.put(DPMapStatisticsItemEnum.GAS_UNITS.getCode(), 0);
        m.put(DPMapStatisticsItemEnum.DESIGN_UNITS.getCode(), 0);

    }


    public Map<String, Object> querySafetyIndex(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> result = new HashMap<>();
        int riskScore = ThreadLocalRandom.current().nextInt(88, 93);
        result.put("riskScore", riskScore);
        return result;
    }

    public List<FourColorCountDataDto> queryFourColorManagerSafetyData(DPFilterParamDto dpFilterParamDto) {
        this.setDefaultFilter(dpFilterParamDto);
        Map<String, Map<String, CountDto>> dataMap = this.getAllDataMap(dpFilterParamDto);
        return Arrays.stream(FourColorCountItemEnum.values()).map(e -> {
            FourColorCountDataDto dataDto = new FourColorCountDataDto();
            dataDto.setKey(e.getKey());
            dataDto.setLabel(e.getLabel());
            dataDto.setChildren(this.buildFourColorItemData(dataMap.get(e.getKey())));
            return dataDto;
        }).collect(Collectors.toList());
    }

    private List<FourColorCountDataDto> buildFourColorItemData(Map<String, CountDto> colorCountDataMap) {
        return Arrays.stream(FourColorEnum.values()).filter(e -> colorCountDataMap.get(e.getCode()) != null).map(c -> {
            FourColorCountDataDto dataDto = new FourColorCountDataDto();
            dataDto.setKey(c.getCode());
            dataDto.setValue(colorCountDataMap.get(c.getCode()).getLongValue());
            dataDto.setLabel(colorCountDataMap.get(c.getCode()).getLabel());
            return dataDto;
        }).collect(Collectors.toList());
    }

    private Map<String, CountDto> countEquipNum(DPFilterParamDto dpFilterParamDto) {
        Map<String, CountDto> countMap = new HashMap<>();
        countMap.put(FourColorEnum.GREEN.getCode(), this.getGreenStatusEquip(dpFilterParamDto));
        countMap.put(FourColorEnum.RED.getCode(), this.getRedStatusEquip(dpFilterParamDto));
        countMap.put(FourColorEnum.YELLOW.getCode(), this.getYellowStatusEquip(dpFilterParamDto));
        countMap.put(FourColorEnum.GREY.getCode(), this.getGreyStatusEquip(dpFilterParamDto));
        return countMap;
    }

    private CountDto getGreenStatusEquip(DPFilterParamDto dpFilterParamDto) {
        CountDto countDto = new CountDto();
        countDto.setLongValue(this.countEquipNumFromES(dpFilterParamDto, EquimentEnum.ZAIYONG.getCode()));
        countDto.setLabel("正常在用");
        return countDto;
    }

    private long countEquipNumFromES(DPFilterParamDto dpFilterParamDto, Integer... states) {
        long num;
        CountRequest request = new CountRequest();
        request.indices("idx_biz_view_jg_all");
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return 0L;
        }
        // 按照管辖机构区域信息模糊查询
        boolMust.must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(orgCode) + "*"));
        //已赋码
        boolMust.must(QueryBuilders.existsQuery("SUPERVISORY_CODE"));
        boolMust.mustNot(QueryBuilders.termQuery("SUPERVISORY_CODE", "null"));
        //状态为已认领
        String[] status = {"草稿", "已拒领", "待认领"};
        boolMust.mustNot(QueryBuilders.termsQuery("STATUS", Arrays.asList(status)));
        // 设备状态过滤
        boolMust.must(QueryBuilders.termsQuery("EQU_STATE", Arrays.asList(states)));
        // 且8大类，目的去掉脏数据
        boolMust.must(QueryBuilders.termsQuery("EQU_LIST_CODE", StCommonServiceImpl.getEquipmentCategory().stream().map(EquipmentCategoryDto::getCode).collect(Collectors.toList())));
        request.query(boolMust);
        try {
            CountResponse response = restHighLevelClient.count(request, RequestOptions.DEFAULT);
            num = response.getCount();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return num;
    }

    private CountDto getRedStatusEquip(DPFilterParamDto dpFilterParamDto) {
        CountDto countDto = new CountDto();
        countDto.setLongValue(this.staticsCenterMapCountDateOverdueNew(dpFilterParamDto));
        countDto.setLabel("超期未检");
        return countDto;
    }

    private Long staticsCenterMapCountDateOverdueNew(DPFilterParamDto dpFilterParamDto) {
        Long num = 0L;
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        List<String> typeList = new ArrayList<>();
        typeList.add("维保超期");
        typeList.add("检验超期");
        num = safetyProblemTracingMapper.countByTypeListAndOrgCode(typeList, orgCode, IssueMainBodyEnum.EQUIPMENT.getCode());
        return num;
    }

    private Map<String, Map<String, CountDto>> getAllDataMap(DPFilterParamDto dpFilterParamDto) {
        Map<String, Map<String, CountDto>> countMap = new HashMap<>();
        countMap.put(FourColorCountItemEnum.EQUIP.getKey(), this.countEquipNum(dpFilterParamDto));
        countMap.put(FourColorCountItemEnum.COMPANY.getKey(), this.countCompanyNum(dpFilterParamDto));
        countMap.put(FourColorCountItemEnum.USER.getKey(), this.countUserNum(dpFilterParamDto));
        return countMap;
    }

    private CountDto getYellowStatusEquip(DPFilterParamDto dpFilterParamDto) {
        CountDto countDto = new CountDto();
        countDto.setLongValue(this.staticsCenterMapCountDateTemporary(dpFilterParamDto));
        countDto.setLabel("临期告警");
        return countDto;
    }

    /**
     * 临期检验设备数统计
     *
     * @param dpFilterParamDto 过滤条件
     * @return 临期设备的数量
     */
    private Long staticsCenterMapCountDateTemporary(DPFilterParamDto dpFilterParamDto) {
        long num;
        CountRequest request = new CountRequest();
        request.indices("idx_biz_view_jg_all");
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return 0L;
        }
        // 按照管辖机构区域信息模糊查询
        boolMust.must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(orgCode) + "*"));
        //已赋码
        boolMust.must(QueryBuilders.existsQuery("SUPERVISORY_CODE"));
        boolMust.mustNot(QueryBuilders.termQuery("SUPERVISORY_CODE", "null"));
        //状态为已认领
        String[] status = {"草稿", "已拒领", "待认领"};
        boolMust.mustNot(QueryBuilders.termsQuery("STATUS", Arrays.asList(status)));
        // 且下次检验日期大于等于当天
        long currentDayTime = DateUtil.parse(DateUtil.today(), "yyy-MM-dd").getTime();
        // 且查询 下次检验日期 <= 当前天+30天 极为临期
        long currentDayAfter30DayTime = DateUtil.offsetDay(DateUtil.parse(DateUtil.today(), "yyy-MM-dd"), 30).getTime();
        boolMust.must(QueryBuilders.rangeQuery("NEXT_INSPECT_DATE").gte(currentDayTime).lte(currentDayAfter30DayTime));
        // 且8大类，目的去掉脏数据
        boolMust.must(QueryBuilders.termsQuery("EQU_LIST_CODE", StCommonServiceImpl.getEquipmentCategory().stream().map(EquipmentCategoryDto::getCode).collect(Collectors.toList())));
        request.query(boolMust);
        try {
            CountResponse response = restHighLevelClient.count(request, RequestOptions.DEFAULT);
            num = response.getCount();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return num;
    }


    /**
     * 超期检验设备数统计
     *
     * @param dpFilterParamDto 过滤条件
     * @return 超期设备的数量
     */
    private Long staticsCenterMapCountDateOverdue(DPFilterParamDto dpFilterParamDto) {
        long num = 0;
        CountRequest request = new CountRequest();
        request.indices("idx_biz_view_jg_all");
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return 0L;
        }
        // 按照管辖机构区域信息模糊查询
        boolMust.must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(orgCode) + "*"));
        //已赋码
        boolMust.must(QueryBuilders.existsQuery("SUPERVISORY_CODE"));
        boolMust.mustNot(QueryBuilders.termQuery("SUPERVISORY_CODE", "null"));
        //状态为已认领
        String[] status = {"草稿", "已拒领", "待认领"};
        boolMust.mustNot(QueryBuilders.termsQuery("STATUS", Arrays.asList(status)));
        // 查询下次检验日期小于当前天的设备，即为超期检验超期设备
        long currentDayTime = DateUtil.parse(DateUtil.now(), "yyy-MM-dd").getTime();
        boolMust.must(QueryBuilders.rangeQuery("NEXT_INSPECT_DATE").lt(currentDayTime));
        // 且8大类，目的去掉脏数据
        boolMust.must(QueryBuilders.termsQuery("EQU_LIST_CODE", StCommonServiceImpl.getEquipmentCategory().stream().map(EquipmentCategoryDto::getCode).collect(Collectors.toList())));
        request.query(boolMust);
        try {
            CountResponse response = restHighLevelClient.count(request, RequestOptions.DEFAULT);
            num = response.getCount();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return num;
    }

    private CountDto getGreyStatusEquip(DPFilterParamDto dpFilterParamDto) {
        CountDto countDto = new CountDto();
        countDto.setLongValue(this.countEquipNumFromES(dpFilterParamDto, EquimentEnum.BAOFEI.getCode(), EquimentEnum.ZHUXIAO.getCode(), EquimentEnum.TINGYONG.getCode()));
        countDto.setLabel("停用、报废及注销");
        return countDto;
    }

    private Map<String, CountDto> countCompanyNum(DPFilterParamDto dpFilterParamDto) {
        Map<String, CountDto> countMap = new HashMap<>();
        countMap.put(FourColorEnum.GREEN.getCode(), this.getGreenStatusCompany(dpFilterParamDto));
        countMap.put(FourColorEnum.RED.getCode(), this.getRedStatusCompany(dpFilterParamDto));
        countMap.put(FourColorEnum.YELLOW.getCode(), this.getYellowStatusCompany(dpFilterParamDto));
        countMap.put(FourColorEnum.GREY.getCode(), this.getGreyStatusCompany(dpFilterParamDto));
        return countMap;
    }

    private CountDto getGreyStatusCompany(DPFilterParamDto dpFilterParamDto) {
        CountDto countDto = new CountDto();
        countDto.setLongValue(this.countCompanyByOperatingStatus(dpFilterParamDto, "停业"));
        countDto.setLabel("停业");
        return countDto;
    }


    private CountDto getRedStatusCompany(DPFilterParamDto dpFilterParamDto) {
        CountDto countDto = new CountDto();
        countDto.setLongValue(this.countCompanyForCertDateTimeOutNew(dpFilterParamDto));
        countDto.setLabel("许可超期");
        return countDto;
    }

    private Long countCompanyForCertDateTimeOutNew(DPFilterParamDto dpFilterParamDto) {
        Long num = 0L;
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        List<String> typeList = new ArrayList<>();
        typeList.add("许可超期");
        num = safetyProblemTracingMapper.countByTypeListAndOrgCode(typeList, orgCode, IssueMainBodyEnum.COMPANY.getCode());
        return num;
    }

    private CountDto getYellowStatusCompany(DPFilterParamDto dpFilterParamDto) {
        CountDto countDto = new CountDto();
        countDto.setLongValue(this.countCompanyForCertDateTemporary(dpFilterParamDto));
        countDto.setLabel("许可临期");
        return countDto;
    }

    private long countCompanyForCertDateTemporary(DPFilterParamDto dpFilterParamDto) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return 0L;
        }
        // 临期6个月
        String limitDate = DateUtil.offset(DateUtil.date(), DateField.DAY_OF_MONTH, 6).toDateStr();
        return zlStatisticsMapper.countCompanyForCertDateTemporary(dpFilterParamDto, orgCode, limitDate);
    }

    private long countCompanyForCertDateTimeOut(DPFilterParamDto dpFilterParamDto) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return 0L;
        }
        String limitDate = DateUtil.today();
        return zlStatisticsMapper.countCompanyForCertDateTimeOut(dpFilterParamDto, orgCode, limitDate);
    }


    private CountDto getGreenStatusCompany(DPFilterParamDto dpFilterParamDto) {
        CountDto countDto = new CountDto();
        countDto.setLongValue(this.countCompanyByOperatingStatus(dpFilterParamDto, "在业", "开业", "迁入"));
        countDto.setLabel("正常在业、开业、迁入");
        return countDto;
    }

    private long countCompanyByOperatingStatus(DPFilterParamDto dpFilterParamDto, String... operatingStatus) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return 0L;
        }
        return enterpriseInfoMapper.countByOperatingStatusAndOrgCode(orgCode, Arrays.stream(operatingStatus).collect(Collectors.toList()), dpFilterParamDto.getCityCode());
    }

    private Map<String, CountDto> countUserNum(DPFilterParamDto dpFilterParamDto) {
        Map<String, CountDto> countMap = new HashMap<>();
        countMap.put(FourColorEnum.GREEN.getCode(), this.getGreenStatusUser(dpFilterParamDto));
        countMap.put(FourColorEnum.RED.getCode(), this.getRedStatusUser(dpFilterParamDto));
        countMap.put(FourColorEnum.YELLOW.getCode(), this.getYellowStatusUser(dpFilterParamDto));
        return countMap;
    }

    private CountDto getYellowStatusUser(DPFilterParamDto dpFilterParamDto) {
        // TODO 需求不明确
        CountDto countDto = new CountDto();
        countDto.setLongValue(0L);
        countDto.setLabel("许可临期");
        return countDto;
    }

    private CountDto getRedStatusUser(DPFilterParamDto dpFilterParamDto) {
        CountDto countDto = new CountDto();
        countDto.setLabel("资质超期");
        Long num = 0L;
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        List<String> typeList = new ArrayList<>();
        typeList.add("资质超期");
        num = safetyProblemTracingMapper.countByTypeListAndOrgCode(typeList, orgCode, IssueMainBodyEnum.PERSON.getCode());
        countDto.setLongValue(num);
        return countDto;
    }

    private CountDto getGreenStatusUser(DPFilterParamDto dpFilterParamDto) {
        // TODO 需求不明确
        CountDto countDto = new CountDto();
        countDto.setLongValue(0L);
        countDto.setLabel("许可正常");
        return countDto;
    }

    public Map<String, Object> queryBizCycleData(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> result = new HashMap<>();
        // 近30天
        this.setDefaultFilter30(dpFilterParamDto);
        result.put("xdata", Arrays.asList("安装告知", "监督检验", "使用登记", "定期检验", "变更登记", "注销报废"));
        // 进行中
        List<Long> everyFlowingNum = this.countBizDataInFlowing(dpFilterParamDto);
        // 已完成
        List<Long> everyFinishedNum = this.countBizFinishedNum(dpFilterParamDto);
        result.put("ydata", this.calEveryFinishAndFlowNum(everyFinishedNum, everyFlowingNum));
        // 进行中 + 已完成的业务单据总数
        result.put("allCount", this.calAll(everyFinishedNum, everyFlowingNum));
        // 每项业务办结率统计
        result.put("percentData", this.calEveryPercent(everyFlowingNum, everyFinishedNum));
        // 总的业务办结率统计
        result.put("completionRate", this.calPercentForBizCycleData(everyFlowingNum, everyFinishedNum));
        return result;
    }

    private Long calAll(List<Long> everyFinishedNum, List<Long> everyFlowingNum) {
        return everyFlowingNum.stream().mapToLong(e -> e).sum() + everyFinishedNum.stream().mapToLong(e -> e).sum();
    }

    private List<Long> calEveryFinishAndFlowNum(List<Long> everyFinished, List<Long> everyFlowingCount) {
        List<Long> all = new ArrayList<>();
        for (int i = 0; i < everyFinished.size(); i++) {
            all.add(everyFinished.get(i) + everyFlowingCount.get(i));
        }
        return all;
    }


    private List<String> calEveryPercent(List<Long> everyInFlow, List<Long> everyFinished) {
        List<String> percentArray = new ArrayList<>();
        for (int i = 0; i < everyInFlow.size(); i++) {
            Long flowIng = everyInFlow.get(i);
            Long finished = everyFinished.get(i);
            BigDecimal finishedBig = new BigDecimal(finished.toString());
            BigDecimal flowIngBig = new BigDecimal(flowIng.toString());
            BigDecimal all = flowIngBig.add(finishedBig);
            if (all.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal percent = finishedBig.divide(all, 2, RoundingMode.HALF_UP);
                percentArray.add(percent.toPlainString());
            } else {
                percentArray.add("0");
            }
        }
        return percentArray;
    }

    private String calPercentForBizCycleData(List<Long> everyFlowingNum, List<Long> everyFinishedNum) {
        Long allBizDataInFlowingCount = everyFlowingNum.stream().mapToLong(e -> e).sum();
        Long allFinishedCount = everyFinishedNum.stream().mapToLong(e -> e).sum();
        BigDecimal flowing = new BigDecimal(String.valueOf(allBizDataInFlowingCount));
        BigDecimal finish = new BigDecimal(String.valueOf(allFinishedCount));
        BigDecimal total = finish.add(flowing);
        if (total.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal result = finish.divide(total, 2, RoundingMode.HALF_UP);
            BigDecimal percentage = result.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP);
            return percentage.toPlainString();
        } else {
            return "0";
        }
    }

    private Long countAllBizDataInFlowing(DPFilterParamDto dpFilterParamDto) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return 0L;
        }
        List<Long> inFlowingForDP = commonMapper.countAllInFlowingForDPNoFinishedBizData(orgCode, dpFilterParamDto);
        return inFlowingForDP.stream().mapToLong(e -> e).sum();
    }

    private List<Long> countBizDataInFlowing(DPFilterParamDto dpFilterParamDto) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return Arrays.asList(0L, 0L, 0L, 0L, 0L, 0L);
        }
        return commonMapper.countAllInFlowingForDPNoFinishedBizData(orgCode, dpFilterParamDto);
    }

    private List<Long> countBizFinishedNum(DPFilterParamDto dpFilterParamDto) {
        // 1.统计各业务办理量注意要和x轴顺序一致
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        // 省、市、区县为按照行政区划进行编码的，公司的code为行政区划编码
        if (orgCode == null) {
            return Arrays.asList(0L, 0L, 0L, 0L, 0L, 0L);
        }
        return commonMapper.countBizFinishedNumForDP(orgCode, dpFilterParamDto);
    }

    public List<Map<String, Object>> equStateCount(DPFilterParamDto dpFilterParamDto) {
        List<Map<String, Object>> resultList;
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return this.setDefaultEquStateCount();
        }
        // 按照管辖机构区域信息模糊查询
        boolMust.must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(orgCode) + "*"));
        //已赋码
        boolMust.must(QueryBuilders.existsQuery("SUPERVISORY_CODE"));
        boolMust.mustNot(QueryBuilders.termQuery("SUPERVISORY_CODE", "null"));
        //状态为已认领
        String[] status = {"草稿", "已拒领", "待认领"};
        boolMust.mustNot(QueryBuilders.termsQuery("STATUS", Arrays.asList(status)));
        // 且8大类，目的去掉脏数据
        boolMust.must(QueryBuilders.termsQuery("EQU_LIST_CODE", StCommonServiceImpl.getEquipmentCategory().stream().map(EquipmentCategoryDto::getCode).collect(Collectors.toList())));
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(boolMust);
        TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("EQU_STATE_COUNT").field("EQU_STATE").size(20).missing(EquimentEnum.WEIDENGJI.getCode());
        builder.aggregation(aggregationBuilder);
        builder.size(0);
        request.source(builder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            Terms terms = response.getAggregations().get("EQU_STATE_COUNT");
            Map<String, Long> dataMap = new HashMap<>();
            for (Terms.Bucket bucket : terms.getBuckets()) {
                String category = bucket.getKeyAsString();
                long docCount = bucket.getDocCount();
                dataMap.put(category, docCount);
            }
            resultList = Arrays.stream(EquimentEnum.values()).map(e -> {
                Map<String, Object> map = new HashMap<>();
                map.put("name", e.getName());
                map.put("value", dataMap.getOrDefault(e.getCode().toString(), 0L));
                return map;
            }).collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return resultList;
    }

    private List<Map<String, Object>> setDefaultEquStateCount() {
        return Arrays.stream(EquimentEnum.values()).filter(e -> e.getCode() > 0).map(e -> {
            Map<String, Object> map = new HashMap<>();
            map.put("name", e.getName());
            map.put("value", 0L);
            return map;
        }).collect(Collectors.toList());
    }

    public Map<String, Object> equStopStateCount(DPFilterParamDto dpFilterParamDto) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        //停用
        List<Map> stopList = useRegistrationMapper.stopStateCount(orgCode);
        //注销
        List<Map> cancelList = useRegistrationMapper.cancelStateCount(orgCode, 1);
        //报废
        List<Map> scrapList = useRegistrationMapper.cancelStateCount(orgCode, 2);

        Map<String, Long> stopMap = new HashMap<>();
        Map<String, Long> cancelMap = new HashMap<>();
        Map<String, Long> scrapMap = new HashMap<>();

        for (int i = 0; i < stopList.size(); i++) {
            if ("2000".equals(stopList.get(i).get("equList")) && "2300".equals(stopList.get(i).get("equCategory"))) {
                stopMap.put(stopList.get(i).get("equCategory") + "", stopMap.getOrDefault("equCategory", 0L) + (Long) stopList.get(i).get("count"));
            } else {
                stopMap.put(stopList.get(i).get("equList") + "", stopMap.getOrDefault("equList", 0L) + (Long) stopList.get(i).get("count"));
            }
        }

        for (int i = 0; i < cancelList.size(); i++) {
            if ("2000".equals(cancelList.get(i).get("equList")) && "2300".equals(cancelList.get(i).get("equCategory"))) {
                cancelMap.put(cancelList.get(i).get("equCategory") + "", cancelMap.getOrDefault("equCategory", 0L) + (Long) cancelList.get(i).get("count"));
            } else {
                cancelMap.put(cancelList.get(i).get("equList") + "", cancelMap.getOrDefault("equCategory", 0L) + (Long) cancelList.get(i).get("count"));
            }
        }

        for (int i = 0; i < scrapList.size(); i++) {
            if ("2000".equals(scrapList.get(i).get("equList")) && "2300".equals(scrapList.get(i).get("equCategory"))) {
                scrapMap.put(scrapList.get(i).get("equCategory") + "", scrapMap.getOrDefault("equCategory", 0L) + (Long) scrapList.get(i).get("count"));
            } else {
                scrapMap.put(scrapList.get(i).get("equList") + "", scrapMap.getOrDefault("equCategory", 0L) + (Long) scrapList.get(i).get("count"));
            }
        }

        List<Map<String, Object>> legendDataList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<String, Object> map = new HashMap();
            if (i == 0) {
                map.put("dataKey", "stop");
                map.put("value", "停用");
            } else if (i == 1) {
                map.put("dataKey", "logout");
                map.put("value", "注销");
            } else {
                map.put("dataKey", "scrap");
                map.put("value", "报废");
            }
            legendDataList.add(map);
        }
        List<String> xDataList = Arrays.asList("气瓶", "电梯", "压力容器", "锅炉", "起重机械", "场(厂)内专用", "大型游乐设施", "压力管道", "客运索道");
        List<Object> stop = new ArrayList<>();
        List<Object> logout = new ArrayList<>();
        List<Object> scrap = new ArrayList<>();
        for (int i = 0; i < 9; i++) {
            if (i == 0) {
                stop.add(stopMap.getOrDefault("2300", 0L));
                logout.add(cancelMap.getOrDefault("2300", 0L));
                scrap.add(scrapMap.getOrDefault("2300", 0L));
            } else if (i == 1) {
                stop.add(stopMap.getOrDefault("3000", 0L));
                logout.add(cancelMap.getOrDefault("3000", 0L));
                scrap.add(scrapMap.getOrDefault("3000", 0L));
            } else if (i == 2) {
                stop.add(stopMap.getOrDefault("2000", 0L));
                logout.add(cancelMap.getOrDefault("2000", 0L));
                scrap.add(scrapMap.getOrDefault("2000", 0L));
            } else if (i == 3) {
                stop.add(stopMap.getOrDefault("1000", 0L));
                logout.add(cancelMap.getOrDefault("1000", 0L));
                scrap.add(scrapMap.getOrDefault("1000", 0L));
            } else if (i == 4) {
                stop.add(stopMap.getOrDefault("4000", 0L));
                logout.add(cancelMap.getOrDefault("4000", 0L));
                scrap.add(scrapMap.getOrDefault("4000", 0L));
            } else if (i == 5) {
                stop.add(stopMap.getOrDefault("5000", 0L));
                logout.add(cancelMap.getOrDefault("5000", 0L));
                scrap.add(scrapMap.getOrDefault("5000", 0L));
            } else if (i == 6) {
                stop.add(stopMap.getOrDefault("6000", 0L));
                logout.add(cancelMap.getOrDefault("6000", 0L));
                scrap.add(scrapMap.getOrDefault("6000", 0L));
            } else if (i == 7) {
                stop.add(stopMap.getOrDefault("8000", 0L));
                logout.add(cancelMap.getOrDefault("8000", 0L));
                scrap.add(scrapMap.getOrDefault("8000", 0L));
            } else {
                stop.add(stopMap.getOrDefault("9000", 0L));
                logout.add(cancelMap.getOrDefault("9000", 0L));
                scrap.add(scrapMap.getOrDefault("9000", 0L));
            }
        }
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("legendData", legendDataList);
        returnMap.put("xdata", xDataList);
        returnMap.put("stop", stop);
        returnMap.put("logout", logout);
        returnMap.put("scrap", scrap);
        return returnMap;
    }

    public List<Map<String, Object>> maintenanceCountTopTen(DPFilterParamDto dpFilterParamDto) {
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParent(dpFilterParamDto);
        List<Integer> regionCodeList = regionModels.stream().map(m -> m.getRegionCode()).collect(Collectors.toList());
        Map<Integer, RegionModel> regionMap = regionModels.stream().collect(Collectors.toMap(RegionModel::getRegionCode, Function.identity()));
        List<Map<String, Object>> list = jgStatisticsMapper.maintenanceCountTopTen(dpFilterParamDto, regionCodeList);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> result = new HashMap<>();
            result.put("key", i);
            result.put("city", regionMap.get(Integer.valueOf(list.get(i).get("companyCode") + "")).getRegionName());
            result.put("count", list.get(i).get("count"));
            result.put("name", list.get(i).get("companyName"));
            resultList.add(result);
        }
        return resultList;
    }

    public Map<String, Object> maintenanceCount(DPFilterParamDto dpFilterParamDto) {
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParent(dpFilterParamDto);
        List<Integer> regionCodeList = regionModels.stream().map(m -> m.getRegionCode()).collect(Collectors.toList());
        Map<Integer, RegionModel> regionMap = regionModels.stream().collect(Collectors.toMap(RegionModel::getRegionCode, Function.identity()));
        List<Map<String, Object>> list = jgStatisticsMapper.maintenanceCount(dpFilterParamDto, regionCodeList);
        Map<String, Object> resultMap = new HashMap<>();
        List xList = new ArrayList();
        List yList = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            xList.add(regionMap.get(Integer.valueOf(list.get(i).get("companyCode") + "")).getRegionName());
            yList.add(list.get(i).get("count"));
        }
        resultMap.put("xdata", xList);
        resultMap.put("ydata", yList);
        return resultMap;
    }

    public Map<String, Object> cityBusinessCount(DPFilterParamDto dpFilterParamDto) {
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParentAndNoAccessIf3Level(dpFilterParamDto);
        Map<String, Object> resultMap = new HashMap<>();
        String orgCodeP = stCommonService.getAndSetOrgCode(dpFilterParamDto);
        if (orgCodeP == null) {
            return new HashMap<>();
        }
        List<CountDto> countDtos = getDealDayAvgList(dpFilterParamDto, orgCodeP);
        List<String> xData = new ArrayList<>();
        List<String> yData = new ArrayList<>();
        regionModels.forEach(r -> {
            xData.add(r.getRegionName());
            String orgCode = stCommonService.getAndSetOrgCode(r.getRegionCode().toString());
            if (!ValidationUtil.isEmpty(orgCode)) {
                yData.add(this.avgAndSumDealDate(countDtos.stream().filter(c -> c.getKeyStr().contains(orgCode)).collect(Collectors.toList())));
            } else {
                yData.add("0");
            }
        });
        resultMap.put("xdata", xData);
        resultMap.put("ydata", yData);
        resultMap.put("unit", "天");
        return resultMap;
    }

    private String avgAndSumDealDate(List<CountDto> collect) {
        BigDecimal sum = collect.stream().map(c -> new BigDecimal(c.getStrValue())).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (collect.isEmpty()) {
            return "0";
        }
        return sum.divide(BigDecimal.valueOf(collect.size()), 1, RoundingMode.HALF_UP).toPlainString();
    }

    private List<CountDto> getDealDayAvgList(DPFilterParamDto dpFilterParamDto, String orgCode) {
        List<CountDto> countDtos = new ArrayList<>();
        // 业务类型0告知管理，1使用登记，2变更登记，3停用启用，4注销报废
        if ("0".equals(dpFilterParamDto.getBusinessKey())) {
            countDtos = noticeCount(dpFilterParamDto, orgCode);
        } else if ("1".equals(dpFilterParamDto.getBusinessKey())) {
            countDtos = useCount(dpFilterParamDto, orgCode);
        } else if ("2".equals(dpFilterParamDto.getBusinessKey())) {
            countDtos = changeCount(dpFilterParamDto, orgCode);
        } else if ("3".equals(dpFilterParamDto.getBusinessKey())) {
            countDtos = disableCount(dpFilterParamDto, orgCode);
        } else if ("4".equals(dpFilterParamDto.getBusinessKey())) {
            countDtos = cancelCount(dpFilterParamDto, orgCode);
        }
        return countDtos;
    }

    private List<CountDto> cancelCount(DPFilterParamDto dpFilterParamDto, String orgCode) {
        //注销报废
        return jgStatisticsMapper.queryCancelAvgDayByReceiveCompany(dpFilterParamDto, orgCode);
    }

    private List<CountDto> disableCount(DPFilterParamDto dpFilterParamDto, String orgCode) {
        //启用停用
        return jgStatisticsMapper.queryDisableAvgDayByReceiveCompany(dpFilterParamDto, orgCode);
    }

    private List<CountDto> changeCount(DPFilterParamDto dpFilterParamDto, String orgCode) {
        //更名变更登记、改造变更登记、移装变更登记、单位变更登记、气瓶单位变更登记
        return jgStatisticsMapper.queryChangeAvgDayByReceiveCompany(dpFilterParamDto, orgCode);
    }

    private List<CountDto> useCount(DPFilterParamDto dpFilterParamDto, String orgCode) {
        //使用登记、车用气瓶使用登记
        return jgStatisticsMapper.queryUseAvgDayByReceiveCompany(dpFilterParamDto, orgCode);
    }

    private List<CountDto> noticeCount(DPFilterParamDto dpFilterParamDto, String orgCode) {
        //安装告知、维修告知、改造告知、移装告知
        return jgStatisticsMapper.queryNoticeAvgDayByReceiveCompany(dpFilterParamDto, orgCode);
    }

    public List<Map<String, Object>> getBusinessKey(DPFilterParamDto dpFilterParamDto) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        /**
         * 告知管理、使用登记、变更登记、停用启用、注销报废
         */
        for (int i = 0; i < 5; i++) {
            Map<String, Object> result = new HashMap<>();
            if (i == 0) {
                result.put("key", i + "");
                result.put("name", "告知管理");
            } else if (i == 1) {
                result.put("key", i + "");
                result.put("name", "使用登记");
            } else if (i == 2) {
                result.put("key", i + "");
                result.put("name", "变更登记");
            } else if (i == 3) {
                result.put("key", i + "");
                result.put("name", "停用启用");
            } else if (i == 4) {
                result.put("key", i + "");
                result.put("name", "注销报废");
            }
            resultList.add(result);

        }

        return resultList;
    }

    public Map<String, Object> getNoticeEquCount(DPFilterParamDto dpFilterParamDto) {
        String startTime = LocalDate.now().minusDays(29).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //安装告知
        List<Map<String, Object>> installlist = jgStatisticsMapper.installEquCount(dpFilterParamDto.getCityCode(), startTime);
        Map<String, Integer> installCountMap = new HashMap<>();
        countNoticEquList(installCountMap, installlist);
        //维修告知
        List<Map<String, Object>> maintenancelist = jgStatisticsMapper.maintenanceEquCount(dpFilterParamDto.getCityCode(), startTime);
        Map<String, Integer> maintenanceCountMap = new HashMap<>();
        countNoticEquList(maintenanceCountMap, maintenancelist);
        //改造告知
        List<Map<String, Object>> reformlist = jgStatisticsMapper.reformEquCount(dpFilterParamDto.getCityCode(), startTime);
        Map<String, Integer> reformCountMap = new HashMap<>();
        countNoticEquList(reformCountMap, reformlist);
        //移装告知
        List<Map<String, Object>> transferlist = jgStatisticsMapper.transferEquCount(dpFilterParamDto.getCityCode(), startTime);
        Map<String, Integer> transferCountMap = new HashMap<>();
        countNoticEquList(transferCountMap, transferlist);

        Map<String, Object> resultMap = new HashMap<>();
        List legendData = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Map<String, String> map = new HashMap<>();
            if (i == 0) {
                map.put("dataKey", "installNotify");
                map.put("value", "安装告知");
            } else if (i == 1) {
                map.put("dataKey", "transformNotify");
                map.put("value", "改造告知");
            } else if (i == 2) {
                map.put("dataKey", "maintainNotify");
                map.put("value", "维修告知");
            } else if (i == 3) {
                map.put("dataKey", "transloadingNotify");
                map.put("value", "移装告知");
            }
            legendData.add(map);
        }
        resultMap.put("legendData", legendData);
        List<String> xDataList = Arrays.asList("电梯", "压力容器", "锅炉", "起重机械", "场(厂)内专用", "大型游乐设施", "压力管道", "客运索道");
        resultMap.put("xdata", xDataList);
        List installNotify = new ArrayList<>();
        List transformNotify = new ArrayList<>();
        List maintainNotify = new ArrayList<>();
        List transloadingNotify = new ArrayList<>();
        /**
         * 2300 气瓶
         * 3000	电梯
         * 2000	压力容器
         * 1000	锅炉
         * 4000	起重机械
         * 5000	场（厂）内专用机动车辆
         * 6000	大型游乐设施
         * 8000	压力管道
         * 9000	客运索道
         */
        for (int i = 0; i < xDataList.size(); i++) {
            if (i == 0) {
                installNotify.add(installCountMap.getOrDefault("3000", 0));
                transformNotify.add(reformCountMap.getOrDefault("3000", 0));
                maintainNotify.add(maintenanceCountMap.getOrDefault("3000", 0));
                transloadingNotify.add(transferCountMap.getOrDefault("3000", 0));
            } else if (i == 1) {
                installNotify.add(installCountMap.getOrDefault("2000", 0));
                transformNotify.add(reformCountMap.getOrDefault("2000", 0));
                maintainNotify.add(maintenanceCountMap.getOrDefault("2000", 0));
                transloadingNotify.add(transferCountMap.getOrDefault("2000", 0));
            } else if (i == 2) {
                installNotify.add(installCountMap.getOrDefault("1000", 0));
                transformNotify.add(reformCountMap.getOrDefault("1000", 0));
                maintainNotify.add(maintenanceCountMap.getOrDefault("1000", 0));
                transloadingNotify.add(transferCountMap.getOrDefault("1000", 0));
            } else if (i == 3) {
                installNotify.add(installCountMap.getOrDefault("4000", 0));
                transformNotify.add(reformCountMap.getOrDefault("4000", 0));
                maintainNotify.add(maintenanceCountMap.getOrDefault("4000", 0));
                transloadingNotify.add(transferCountMap.getOrDefault("4000", 0));
            } else if (i == 4) {
                installNotify.add(installCountMap.getOrDefault("5000", 0));
                transformNotify.add(reformCountMap.getOrDefault("5000", 0));
                maintainNotify.add(maintenanceCountMap.getOrDefault("5000", 0));
                transloadingNotify.add(transferCountMap.getOrDefault("5000", 0));
            } else if (i == 5) {
                installNotify.add(installCountMap.getOrDefault("6000", 0));
                transformNotify.add(reformCountMap.getOrDefault("6000", 0));
                maintainNotify.add(maintenanceCountMap.getOrDefault("6000", 0));
                transloadingNotify.add(transferCountMap.getOrDefault("6000", 0));
            } else if (i == 6) {
                installNotify.add(installCountMap.getOrDefault("8000", 0));
                transformNotify.add(reformCountMap.getOrDefault("8000", 0));
                maintainNotify.add(maintenanceCountMap.getOrDefault("8000", 0));
                transloadingNotify.add(transferCountMap.getOrDefault("8000", 0));
            } else if (i == 7) {
                installNotify.add(installCountMap.getOrDefault("9000", 0));
                transformNotify.add(reformCountMap.getOrDefault("9000", 0));
                maintainNotify.add(maintenanceCountMap.getOrDefault("9000", 0));
                transloadingNotify.add(transferCountMap.getOrDefault("9000", 0));
            }
        }
        resultMap.put("installNotify", installNotify);
        resultMap.put("transformNotify", transformNotify);
        resultMap.put("maintainNotify", maintainNotify);
        resultMap.put("transloadingNotify", transloadingNotify);
        return resultMap;
    }

    private void countNoticEquList(Map<String, Integer> countMap, List<Map<String, Object>> list) {
        for (int i = 0; i < list.size(); i++) {
            if ("2300".equals(list.get(i).get("equCategory"))) {
                if (null == countMap.get("2300")) {
                    countMap.put("2300", Integer.valueOf(list.get(i).get("count") + ""));
                } else {
                    countMap.put("2300", countMap.get("2300") + Integer.valueOf(list.get(i).get("count") + ""));
                }
            } else {
                if (null == countMap.get(list.get(i).get("equList").toString())) {
                    countMap.put(list.get(i).get("equList").toString(), Integer.valueOf(list.get(i).get("count") + ""));
                } else {
                    countMap.put(list.get(i).get("equList").toString(), countMap.get(list.get(i).get("equList").toString()) + Integer.valueOf(list.get(i).get("count") + ""));
                }
            }
        }
    }

    public Map<String, Object> getRegEquCount(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> resultMap = new HashMap<>();
        String startTime = LocalDate.now().minusDays(29).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //使用登记
        List<Map<String, Object>> uselist = jgStatisticsMapper.useEquCount(dpFilterParamDto.getCityCode(), startTime);
        Map<String, Integer> useCountMap = new HashMap<>();
        countNoticEquList(useCountMap, uselist);
        //车用气瓶使用登记-
//        List<Map<String, Object>> vehicleList = dpStatisticsMapper.vehicleEquCount(dpFilterParamDto.getCityCode(), startTime);
//        Map<String, Integer> vehicleCountMap = new HashMap<>();
//        countNoticEquList(vehicleCountMap, vehicleList);
        //改造变更登记
        List<Map<String, Object>> changeReformList = jgStatisticsMapper.changeReformEquCount(dpFilterParamDto.getCityCode(), startTime);
        Map<String, Integer> changeReformCountMap = new HashMap<>();
        countNoticEquList(changeReformCountMap, changeReformList);
        //移装变更登记
        List<Map<String, Object>> changeTransferList = jgStatisticsMapper.changeTransferEquCount(dpFilterParamDto.getCityCode(), startTime);
        Map<String, Integer> changeTransferCountMap = new HashMap<>();
        countNoticEquList(changeTransferCountMap, changeTransferList);
        //单位变更登记
        List<Map<String, Object>> changeUnitList = jgStatisticsMapper.changeUnitEquCount(dpFilterParamDto.getCityCode(), startTime);
        Map<String, Integer> changeUnitCountMap = new HashMap<>();
        countNoticEquList(changeUnitCountMap, changeUnitList);

        List legendData = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Map<String, String> map = new HashMap<>();
            if (i == 0) {
                map.put("dataKey", "useRegistration");
                map.put("value", "使用登记");
            } else if (i == 1) {
                map.put("dataKey", "modificateModifyRegistration");
                map.put("value", "改造变更登记");
            } else if (i == 2) {
                map.put("dataKey", "transloadingModifyRegistration");
                map.put("value", "移装变更登记");
            } else if (i == 3) {
                map.put("dataKey", "unitModifyRegistration");
                map.put("value", "单位变更登记");
            }
            legendData.add(map);
        }
        resultMap.put("legendData", legendData);
        List<String> xDataList = Arrays.asList("气瓶", "电梯", "压力容器", "锅炉", "起重机械", "场(厂)内专用", "大型游乐设施", "压力管道", "客运索道");
        resultMap.put("xdata", xDataList);
        List useRegistration = new ArrayList<>();
        List modificateModifyRegistration = new ArrayList<>();
        List transloadingModifyRegistration = new ArrayList<>();
        List unitModifyRegistration = new ArrayList<>();
        for (int i = 0; i < xDataList.size(); i++) {
            if (i == 0) {
                useRegistration.add(useCountMap.getOrDefault("2300", 0));
                modificateModifyRegistration.add(changeReformCountMap.getOrDefault("2300", 0));
                transloadingModifyRegistration.add(changeTransferCountMap.getOrDefault("2300", 0));
                unitModifyRegistration.add(changeUnitCountMap.getOrDefault("2300", 0));
            } else if (i == 1) {
                useRegistration.add(useCountMap.getOrDefault("3000", 0));
                modificateModifyRegistration.add(changeTransferCountMap.getOrDefault("3000", 0));
                transloadingModifyRegistration.add(changeTransferCountMap.getOrDefault("3000", 0));
                unitModifyRegistration.add(changeUnitCountMap.getOrDefault("3000", 0));
            } else if (i == 2) {
                useRegistration.add(useCountMap.getOrDefault("2000", 0));
                modificateModifyRegistration.add(changeTransferCountMap.getOrDefault("2000", 0));
                transloadingModifyRegistration.add(changeTransferCountMap.getOrDefault("2000", 0));
                unitModifyRegistration.add(changeUnitCountMap.getOrDefault("2000", 0));
            } else if (i == 3) {
                useRegistration.add(useCountMap.getOrDefault("1000", 0));
                modificateModifyRegistration.add(changeTransferCountMap.getOrDefault("1000", 0));
                transloadingModifyRegistration.add(changeTransferCountMap.getOrDefault("1000", 0));
                unitModifyRegistration.add(changeUnitCountMap.getOrDefault("1000", 0));
            } else if (i == 4) {
                useRegistration.add(useCountMap.getOrDefault("4000", 0));
                modificateModifyRegistration.add(changeTransferCountMap.getOrDefault("4000", 0));
                transloadingModifyRegistration.add(changeTransferCountMap.getOrDefault("4000", 0));
                unitModifyRegistration.add(changeUnitCountMap.getOrDefault("4000", 0));
            } else if (i == 5) {
                useRegistration.add(useCountMap.getOrDefault("5000", 0));
                modificateModifyRegistration.add(changeTransferCountMap.getOrDefault("5000", 0));
                transloadingModifyRegistration.add(changeTransferCountMap.getOrDefault("5000", 0));
                unitModifyRegistration.add(changeUnitCountMap.getOrDefault("5000", 0));
            } else if (i == 6) {
                useRegistration.add(useCountMap.getOrDefault("6000", 0));
                modificateModifyRegistration.add(changeTransferCountMap.getOrDefault("6000", 0));
                transloadingModifyRegistration.add(changeTransferCountMap.getOrDefault("6000", 0));
                unitModifyRegistration.add(changeUnitCountMap.getOrDefault("6000", 0));
            } else if (i == 7) {
                useRegistration.add(useCountMap.getOrDefault("8000", 0));
                modificateModifyRegistration.add(changeTransferCountMap.getOrDefault("8000", 0));
                transloadingModifyRegistration.add(changeTransferCountMap.getOrDefault("8000", 0));
                unitModifyRegistration.add(changeUnitCountMap.getOrDefault("8000", 0));
            } else if (i == 8) {
                useRegistration.add(useCountMap.getOrDefault("9000", 0));
                modificateModifyRegistration.add(changeTransferCountMap.getOrDefault("9000", 0));
                transloadingModifyRegistration.add(changeTransferCountMap.getOrDefault("9000", 0));
                unitModifyRegistration.add(changeUnitCountMap.getOrDefault("9000", 0));
            }
        }
        resultMap.put("useRegistration", useRegistration);
        resultMap.put("modificateModifyRegistration", modificateModifyRegistration);
        resultMap.put("transloadingModifyRegistration", transloadingModifyRegistration);
        resultMap.put("unitModifyRegistration", unitModifyRegistration);

        return resultMap;

    }

    public List<Map<String, Object>> dataStatisticByReginCode(DPFilterParamDto dpFilterParamDto) {
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParent(dpFilterParamDto);
        List<Map<String, Object>> result = regionModels.parallelStream().map(r -> {
            DPFilterParamDto filterParamDto = new DPFilterParamDto();
            filterParamDto.setCityCode(r.getRegionCode().toString());
            Map<String, Object> itemResult = staticsCenterMapCountDataForRegin(filterParamDto);
            itemResult.put(REGION_CODE, r.getRegionCode());
            itemResult.put(REGION_NAME, r.getRegionName());
            return itemResult;
        }).collect(Collectors.toList());
        return result;
    }


    private Map<String, Object> staticsCenterMapCountDataForRegin(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> result = new HashMap<>();
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (StringUtils.isEmpty(orgCode)) {
            result.put(DPMapStatisticsItemEnum.DEVICE_COUNT.getCode(), 0L);
            result.put(DPMapStatisticsItemEnum.CERTIFICATE_COUNT.getCode(), 0L);
            return result;
        }
        Long certificateCount = jgUseRegistrationManageMapper.countCertificateByReginCode(orgCode);
        Long deviceCount = countEquipByReginCode(orgCode);
        result.put(DPMapStatisticsItemEnum.CERTIFICATE_COUNT.getCode(), certificateCount);
        result.put(DPMapStatisticsItemEnum.DEVICE_COUNT.getCode(), deviceCount);
        return result;
    }

    private Long countEquipByReginCode(String orgCode) {
        long num = 0;
        CountRequest request = new CountRequest();
        request.indices("idx_biz_view_jg_all");
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        // 按照管辖机构区域信息模糊查询
        boolMust.must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(orgCode) + "*"));
        //已赋码
        boolMust.must(QueryBuilders.existsQuery("SUPERVISORY_CODE"));
        boolMust.mustNot(QueryBuilders.termQuery("SUPERVISORY_CODE", "null"));
        //状态为已认领
        String[] status = {"草稿", "已拒领", "待认领"};
        boolMust.mustNot(QueryBuilders.termsQuery("STATUS", Arrays.asList(status)));
        // 且8大类，目的去掉脏数据
        boolMust.must(QueryBuilders.termsQuery("EQU_LIST_CODE", StCommonServiceImpl.getEquipmentCategory().stream().map(EquipmentCategoryDto::getCode).collect(Collectors.toList())));
        request.query(boolMust);
        try {
            CountResponse response = restHighLevelClient.count(request, RequestOptions.DEFAULT);
            num = response.getCount();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return num;
    }

    public Map<String, Object> dataStatisticCountByReginCode(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> mapList = this.dataStatisticByReginCode(dpFilterParamDto);
        if (ObjectUtils.isEmpty(mapList)) {
            resultMap.put(DPMapStatisticsItemEnum.CERTIFICATE_COUNT.getCode(), 0);
            resultMap.put(DPMapStatisticsItemEnum.DEVICE_COUNT.getCode(), 0);
            return resultMap;
        }
        long certificateCount = mapList.stream().mapToLong(x -> (Long) x.get("certificateCount")).sum();
        long deviceCount = mapList.stream().mapToLong(x -> (Long) x.get("deviceCount")).sum();
        resultMap.put(DPMapStatisticsItemEnum.CERTIFICATE_COUNT.getCode(), certificateCount);
        resultMap.put(DPMapStatisticsItemEnum.DEVICE_COUNT.getCode(), deviceCount);
        return resultMap;
    }

    public Map<String, Object> newRegEquCount(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("dataKey", "newRegisterEq");
        map.put("value", "新增登记设备");
        List<Map<String, Object>> legendData = new ArrayList<>();
        legendData.add(map);
        resultMap.put("legendData", legendData);
        List xDataList = new ArrayList<>();
        List newRegisterEq = new ArrayList<>();
        Map<String, Object> useCountMap = new HashMap<>();
        Map<String, Object> vehicleCountMap = new HashMap<>();
        if ("month".equals(dpFilterParamDto.getSearchType())) {
            List<Map<String, Object>> useCountList = jgStatisticsMapper.newRegEquCountByMonth(dpFilterParamDto.getCityCode());
            List<Map<String, Object>> vehicleCountList = jgStatisticsMapper.newVehicleEquCountByMonth(dpFilterParamDto.getCityCode());
            for (int i = 0; i < useCountList.size(); i++) {
                useCountMap.put(useCountList.get(i).getOrDefault("date_format", "") + "", Integer.valueOf(useCountList.get(i).getOrDefault("count", 0) + ""));
            }
            for (int i = 0; i < vehicleCountList.size(); i++) {
                vehicleCountMap.put(vehicleCountList.get(i).getOrDefault("date_format", "") + "", Integer.valueOf(vehicleCountList.get(i).getOrDefault("count", 0) + ""));
            }
            for (int i = 0; i < LocalDate.now().getDayOfMonth(); i++) {
                xDataList.add(LocalDate.now().minusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                newRegisterEq.add(Integer.valueOf(useCountMap.getOrDefault(LocalDate.now().minusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), 0) + "")
                        + Integer.valueOf(vehicleCountMap.getOrDefault(LocalDate.now().minusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), 0) + ""));
            }

        } else if ("year".equals(dpFilterParamDto.getSearchType())) {
            List<Map<String, Object>> useCountList = jgStatisticsMapper.newRegEquCountByYear(dpFilterParamDto.getCityCode());
            List<Map<String, Object>> vehicleCountList = jgStatisticsMapper.newVehicleEquCountByYear(dpFilterParamDto.getCityCode());
            for (int i = 0; i < useCountList.size(); i++) {
                useCountMap.put(useCountList.get(i).getOrDefault("date_format", "") + "", Integer.valueOf(useCountList.get(i).getOrDefault("count", 0) + ""));
            }
            for (int i = 0; i < vehicleCountList.size(); i++) {
                vehicleCountMap.put(vehicleCountList.get(i).getOrDefault("date_format", "") + "", Integer.valueOf(vehicleCountList.get(i).getOrDefault("count", 0) + ""));
            }
            for (int i = 0; i < LocalDate.now().getMonth().getValue(); i++) {
                xDataList.add(LocalDate.now().minusMonths(i).format(DateTimeFormatter.ofPattern("yyyy-MM")));
                newRegisterEq.add(Integer.valueOf(useCountMap.getOrDefault(LocalDate.now().minusMonths(i).format(DateTimeFormatter.ofPattern("yyyy-MM")), 0) + "")
                        + Integer.valueOf(vehicleCountMap.getOrDefault(LocalDate.now().minusMonths(i).format(DateTimeFormatter.ofPattern("yyyy-MM")), 0) + ""));
            }

        } else if ("lastYear".equals(dpFilterParamDto.getSearchType())) {
            List<Map<String, Object>> useCountList = jgStatisticsMapper.newRegEquCountByLastYear(dpFilterParamDto.getCityCode());
            List<Map<String, Object>> vehicleCountList = jgStatisticsMapper.newVehicleEquCountByLastYear(dpFilterParamDto.getCityCode());
            for (int i = 0; i < useCountList.size(); i++) {
                useCountMap.put(useCountList.get(i).getOrDefault("date_format", "") + "", Integer.valueOf(useCountList.get(i).getOrDefault("count", 0) + ""));
            }
            for (int i = 0; i < vehicleCountList.size(); i++) {
                vehicleCountMap.put(vehicleCountList.get(i).getOrDefault("date_format", "") + "", Integer.valueOf(vehicleCountList.get(i).getOrDefault("count", 0) + ""));
            }
            int lastYear = LocalDate.now().getYear() - 1;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            for (int i = 12; i >= 1; i--) {
                String time = LocalDate.of(lastYear, i, 1).format(formatter);
                xDataList.add(time);
                newRegisterEq.add(Integer.valueOf(useCountMap.getOrDefault(time, 0) + "")
                        + Integer.valueOf(vehicleCountMap.getOrDefault(time, 0) + ""));
            }
        }
        Collections.reverse(xDataList);
        Collections.reverse(newRegisterEq);
        resultMap.put("xdata", xDataList);
        resultMap.put("newRegisterEq", newRegisterEq);
        return resultMap;
    }

    public List<Map<String, Object>> newRegCount(DPFilterParamDto dpFilterParamDto) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        //年使用登记设备
        List<Map<String, Object>> useEquCountListYear = jgStatisticsMapper.newRegEquCountByYear(dpFilterParamDto.getCityCode());
        //年气瓶使用登记设备
        List<Map<String, Object>> vehicleEquCountListYear = jgStatisticsMapper.newVehicleEquCountByYear(dpFilterParamDto.getCityCode());
        //月使用登记设备
        List<Map<String, Object>> useEquCountListMonth = jgStatisticsMapper.newRegEquCountByMonth(dpFilterParamDto.getCityCode());
        //月气瓶使用登记设备
        List<Map<String, Object>> vehicleEquCountListMonth = jgStatisticsMapper.newVehicleEquCountByMonth(dpFilterParamDto.getCityCode());
        //年气瓶使用登记
        String vehicleCountYear = jgStatisticsMapper.newVehicleCountByYear(dpFilterParamDto.getCityCode());
        //月气瓶使用登记
        String vehicleCountListMonth = jgStatisticsMapper.newVehicleCountByMonth(dpFilterParamDto.getCityCode());
        /**
         * [ { "name": "本年新增登记", "value": 52 }, { "name": "本年新增设备", "value": 83 },
         * { "name": "本月新增登记", "value": 16 }, { "name": "本月新增设备", "value": 50 } ]
         */
        int useYear = 0;
        int useMonth = 0;
        int usrEqYear = 0;
        int usrEqMonth = 0;
        //本年新增登记
        for (int i = 0; i < useEquCountListYear.size(); i++) {
            useYear += Integer.valueOf(useEquCountListYear.get(i).getOrDefault("count", 0) + "");
            usrEqYear += Integer.valueOf(useEquCountListYear.get(i).getOrDefault("count", 0) + "");
        }
        useYear += StringUtils.isBlank(vehicleCountYear) ? 0 : Integer.valueOf(vehicleCountYear);

        //本年新增设备
        for (int i = 0; i < vehicleEquCountListYear.size(); i++) {
            usrEqYear += Integer.valueOf(vehicleEquCountListYear.get(i).getOrDefault("count", 0) + "");
        }

        //本月新增登记
        for (int i = 0; i < useEquCountListMonth.size(); i++) {
            useMonth += Integer.valueOf(useEquCountListMonth.get(i).getOrDefault("count", 0) + "");
            usrEqMonth += Integer.valueOf(useEquCountListMonth.get(i).getOrDefault("count", 0) + "");
        }
        useMonth += StringUtils.isBlank(vehicleCountListMonth) ? 0 : Integer.valueOf(vehicleCountListMonth);
        //本月新增设备
        for (int i = 0; i < vehicleEquCountListMonth.size(); i++) {
            usrEqMonth += Integer.valueOf(vehicleEquCountListMonth.get(i).getOrDefault("count", 0) + "");
        }


        for (int i = 0; i < 4; i++) {
            Map<String, Object> map = new HashMap<>();
            if (i == 0) {
                map.put("name", "本年新增登记");
                map.put("value", useYear);
            } else if (i == 1) {
                map.put("name", "本年新增设备");
                map.put("value", usrEqYear);
            } else if (i == 2) {
                map.put("name", "本月新增登记");
                map.put("value", useMonth);
            } else if (i == 3) {
                map.put("name", "本月新增设备");
                map.put("value", usrEqMonth);
            }
            resultList.add(map);
        }

        return resultList;
    }

    public Map<String, Object> JGCenterMapCountForGlobal(DPFilterParamDto dpFilterParamDto) {
        Map<String, Object> result = new HashMap<>();
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (StringUtils.isEmpty(orgCode)) {
            return new HashMap<>();
        }
        // 0.气瓶数量统计
        long cylinderNum = stCommonService.staticsCenterMapCountDataForCylinder(result, orgCode, true, true, false);
        // 1.8大类设备数量统计,压力容器里包括气瓶所以需要特殊处理，在统计压力容器时去掉气瓶的数量
        stCommonService.staticsCenterMapCountDataForEquip(result, cylinderNum, orgCode, true, true, false);
        // 2.压力管道长度统计
        stCommonService.staticsCenterMapCountDataForPipeline(result, orgCode, true, false);
        // 3.已纳管设备总数
        this.staticsCenterMapCountDataForEquipIsManage(result);
        // 4.登记证总数
        this.staticsCenterMapCountCertificate(result, orgCode);
        // 5.超过15年电梯数量
        this.staticsCenterMapCountDataForOver15Years(result, orgCode);
        // 6.使用登记办理量
        this.staticsCenterMapCountDataForUseReg(result, orgCode);
        // 7.施工告知办理量
        this.staticsCenterMapCountDataForConstructionNotice(result, orgCode);
        // 8.变更办理量
        this.staticsCenterMapCountDataForChange(result, orgCode);

        return result;
    }

    private void staticsCenterMapCountDataForChange(Map<String, Object> result, String orgCode) {
        Long num = jgStatisticsMapper.changeCountByOrgCode(orgCode);
        result.put(DPMapStatisticsItemEnum.CHANGE_COUNT.getCode(), num);
    }

    private void staticsCenterMapCountDataForConstructionNotice(Map<String, Object> result, String orgCode) {
        Long num = jgStatisticsMapper.constructionNoticeCount(orgCode);
        result.put(DPMapStatisticsItemEnum.CONSTRUCTION_NOTICE_COUNT.getCode(), num);
    }

    private void staticsCenterMapCountDataForOver15Years(Map<String, Object> result, String orgCode) {
        String time = LocalDate.now().minusYears(15).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Long num = jgStatisticsMapper.over15yearsCount(orgCode, time);
        result.put(DPMapStatisticsItemEnum.OVER15YEARS_ELEVATORS.getCode(), num);
    }

    private void staticsCenterMapCountDataForUseReg(Map<String, Object> result, String orgCode) {
        //使用告知
        long num = jgStatisticsMapper.useCountByOrgCode(orgCode);
        result.put(DPMapStatisticsItemEnum.USE_REGISTRATION_COUNT.getCode(), num);
    }

    private void staticsCenterMapCountCertificate(Map<String, Object> result, String orgCode) {
        long num = jgStatisticsMapper.certificateCountByOrgCode(orgCode);
        result.put(DPMapStatisticsItemEnum.CERTIFICATE_COUNT.getCode(), num);
    }

    private void staticsCenterMapCountDataForEquipIsManage(Map<String, Object> result) {
        result.put(DPMapStatisticsItemEnum.DEVICE_COUNT.getCode(), result.get(DPMapStatisticsItemEnum.TOTAL.getCode()));
        result.remove(DPMapStatisticsItemEnum.TOTAL.getCode());
    }

    public List<Map<String, Object>> JGCenterMapCountForOverview(DPFilterParamDto dpFilterParamDto) {
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParent(dpFilterParamDto);
        return regionModels.parallelStream().map(r -> {
            DPFilterParamDto filterParamDto = new DPFilterParamDto();
            filterParamDto.setCityCode(r.getRegionCode().toString());
            Map<String, Object> itemResult = JGCenterMapCountForGlobal(filterParamDto);
            itemResult.put("regionCode", r.getRegionCode());
            itemResult.put("regionName", r.getRegionName());
            return itemResult;
        }).collect(Collectors.toList());
    }

    public List<Map<String, Object>> noticeList(DPFilterParamDto dpFilterParamDto) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return new ArrayList<>();
        }
        String time = LocalDate.now().minusDays(29).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return jgStatisticsMapper.selectNoticeList(orgCode, time);
    }

    public List<Map<String, Object>> noticeCountTop(DPFilterParamDto dpFilterParamDto) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return new ArrayList<>();
        }
        String time = LocalDate.now().minusDays(29).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return jgStatisticsMapper.selectNoticeCountTopTen(orgCode, time);
    }

    public Map<String, Object> noticeCountTopChart(DPFilterParamForDetailDto dpFilterParamForDetailDto) {
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParent(dpFilterParamForDetailDto.getCityCode());
        List<Map<String, Object>> result = regionModels.parallelStream().map(r -> {
            String orgCode = stCommonService.getAndSetOrgCode(r.getRegionCode() + "");
            DPFilterParamForDetailDto dpFilterParamForDetailDtoForSearch = new DPFilterParamForDetailDto();
            dpFilterParamForDetailDtoForSearch.setOrgCode(orgCode);
            dpFilterParamForDetailDtoForSearch.setCityCode(r.getRegionCode() + "");
            Map<String, Object> itemResult = new HashMap<>();
            itemResult.put("xdata", r.getRegionName());
            getNoticeCountTopChart(itemResult, dpFilterParamForDetailDtoForSearch);
            return itemResult;
        }).collect(Collectors.toList());

        Map<String, Object> returnMap = new HashMap<>();
        List<Map<String, Object>> legendData = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("dataKey", "count");
        map.put("value", "施工数量");
        map.put("chartType", "bar");
        legendData.add(map);
        returnMap.put("legendData", legendData);

        List xdata = new ArrayList();
        List count = new ArrayList();

        for (int i = 0; i < result.size(); i++) {
            xdata.add(result.get(i).get("xdata"));
            count.add(result.get(i).get("count") == null ? "0" : result.get(i).get("count"));
        }

        returnMap.put("xdata", xdata);
        returnMap.put("count", count);

        return returnMap;
    }

    public Page<Map<String, Object>> noticeCountTopPage(Page<Map<String, Object>> page, DPFilterParamForDetailDto dpFilterParamForDetailDto) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamForDetailDto.getCityCode());
        dpFilterParamForDetailDto.setOrgCode(orgCode);
        Page<Map<String, Object>> returnPage = jgStatisticsMapper.noticeCountTopPageNew(page, dpFilterParamForDetailDto);
        List<String> unitCodeList = new ArrayList<>();
        for (int i = 0; i < returnPage.getRecords().size(); i++) {
            unitCodeList.add(returnPage.getRecords().get(i).get("useUnitCode").toString());
        }
        if (CollectionUtils.isEmpty(unitCodeList)) {
            return page;
        }
        returnPage.setRecords(jgStatisticsMapper.noticeCountTopPageByUseUnitCode(unitCodeList, dpFilterParamForDetailDto));
        return returnPage;
    }

    public List<Map<String, Object>> noticeCountTopType(DPFilterParamForDetailDto dpFilterParamForDetailDto) {
        List<Map<String, Object>> enumList = new ArrayList<>();
        Map<String, Object> enumMap = new HashMap<>();
        enumMap.put("title", "安装改造维修单位");
        enumMap.put("value", "安装改造维修单位");
        enumList.add(enumMap);
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("title", "业务类型");
        map.put("value", "0");
        map.put("children", enumList);
        result.add(map);
        return result;
    }

    private void getNoticeCountTopChart(Map<String, Object> itemResult, DPFilterParamForDetailDto dpFilterParamForDetailDto) {
        Long count = jgStatisticsMapper.getNoticeCountTopChart(dpFilterParamForDetailDto);
        itemResult.put("count", count);
    }

    private List<Long> countBizFinishedNumForDetail(DPFilterParamDto dpFilterParamDto, String businessType) {
        // 1.统计各业务办理量注意要和x轴顺序一致
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        // 省、市、区县为按照行政区划进行编码的，公司的code为行政区划编码
        if (orgCode == null) {
            return Arrays.asList(0L, 0L, 0L, 0L, 0L, 0L);
        }
        if (BusinessTypeEnum.AZGZ.getCode().equals(businessType)) {
            return commonMapper.countBizFinishedNumForDPAZGZ(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.JDJY.getCode().equals(businessType)) {
            return commonMapper.countBizFinishedNumForDPJDJY(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.SYDJ.getCode().equals(businessType)) {
            return commonMapper.countBizFinishedNumForDPSYDJ(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.DQJY.getCode().equals(businessType)) {
            return commonMapper.countBizFinishedNumForDPDQJY(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.BGDJ.getCode().equals(businessType)) {
            return commonMapper.countBizFinishedNumForDPBGDJ(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.ZXBX.getCode().equals(businessType)) {
            return commonMapper.countBizFinishedNumForDPZXBX(orgCode, dpFilterParamDto);
        } else {
            return commonMapper.countBizFinishedNumForDP(orgCode, dpFilterParamDto);
        }
    }

    private List<Long> countBizDataInFlowingForDetail(DPFilterParamDto dpFilterParamDto, String businessType) {
        // 1.统计各业务办理量注意要和x轴顺序一致
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        // 省、市、区县为按照行政区划进行编码的，公司的code为行政区划编码
        if (orgCode == null) {
            return Arrays.asList(0L, 0L, 0L, 0L, 0L, 0L);
        }
        if (BusinessTypeEnum.AZGZ.getCode().equals(businessType)) {
            return commonMapper.countAllInFlowingForDPNoFinishedBizDataAZGZ(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.JDJY.getCode().equals(businessType)) {
            return commonMapper.countAllInFlowingForDPNoFinishedBizDataJDJY(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.SYDJ.getCode().equals(businessType)) {
            return commonMapper.countAllInFlowingForDPNoFinishedBizDataSYDJ(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.DQJY.getCode().equals(businessType)) {
            return commonMapper.countAllInFlowingForDPNoFinishedBizDataDQJY(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.BGDJ.getCode().equals(businessType)) {
            return commonMapper.countAllInFlowingForDPNoFinishedBizDataBGDJ(orgCode, dpFilterParamDto);
        } else if (BusinessTypeEnum.ZXBX.getCode().equals(businessType)) {
            return commonMapper.countAllInFlowingForDPNoFinishedBizDataZXBX(orgCode, dpFilterParamDto);
        } else {
            return commonMapper.countAllInFlowingForDPNoFinishedBizData(orgCode, dpFilterParamDto);
        }
    }

    public Map<String, Object> queryBizCycleDataDetail(DPFilterParamForDetailDto dpFilterParamForDetailDto) {
        //查询子区域
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParent(dpFilterParamForDetailDto.getCityCode());

        List<Map<String, Object>> result = regionModels.parallelStream().map(r -> {
            DPFilterParamDto filterParamDto = new DPFilterParamDto();
            filterParamDto.setCityCode(r.getRegionCode().toString());
            if (null != dpFilterParamForDetailDto.getTimeSearchOne()) {
                filterParamDto.setBeginDate(dpFilterParamForDetailDto.getTimeSearchOne().getBeginDate());
                filterParamDto.setEndDate(dpFilterParamForDetailDto.getTimeSearchOne().getEndDate());
            }
            Map<String, Object> itemResult = new HashMap<>();
            itemResult.put("xdata", r.getRegionName());
            List<Long> ydata = this.countBizFinishedNumForDetail(filterParamDto, dpFilterParamForDetailDto.getTreeValue());
            BigDecimal finishedNum = BigDecimal.valueOf(ydata.stream().mapToLong(Long::longValue).sum());
            List<Long> everyInFlow = countBizDataInFlowingForDetail(filterParamDto, dpFilterParamForDetailDto.getTreeValue());
            BigDecimal everyNum = BigDecimal.valueOf(everyInFlow.stream().mapToLong(Long::longValue).sum());
            BigDecimal all = everyNum.add(finishedNum);
            if (all.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal percent = finishedNum.divide(all, 2, RoundingMode.HALF_UP);
                itemResult.put("percentData", percent.toPlainString());
            } else {
                itemResult.put("percentData", "0");
            }
            itemResult.put("finishedNum", all);
            return itemResult;
        }).collect(Collectors.toList());

        Map<String, Object> returnMap = new HashMap<>();
        List<Map<String, Object>> legendData = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            Map<String, Object> map = new HashMap<>();
            if (i == 0) {
                map.put("dataKey", "finishedNum");
                map.put("value", "总数");
                map.put("chartType", "bar");
            } else {
                map.put("dataKey", "percentData");
                map.put("value", "完结率");
                map.put("chartType", "line");
            }
            legendData.add(map);
        }
        returnMap.put("legendData", legendData);

        List xdata = new ArrayList();
        List finishedNum = new ArrayList();
        List percentData = new ArrayList();

        for (int i = 0; i < result.size(); i++) {
            xdata.add(result.get(i).get("xdata"));
            finishedNum.add(result.get(i).get("finishedNum"));
            percentData.add(result.get(i).get("percentData"));
        }

        returnMap.put("xdata", xdata);
        returnMap.put("finishedNum", finishedNum);
        returnMap.put("percentData", percentData);

        return returnMap;
    }

    public List<Map<String, Object>> getBusinessType(DPFilterParamForDetailDto dpFilterParamDto) {
        List<HashMap<String, Object>> enumList = BusinessTypeEnum.getEnumList();
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("title", "业务类型");
        map.put("value", "0");
        map.put("children", enumList);
        result.add(map);
        return result;
    }

    public Page<Map<String, Object>> queryBizCycleDataDetailList(DPFilterParamForDetailDto dpFilterParamForDetailDto, Page<Map<String, Object>> page) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamForDetailDto.getCityCode());
        Page<Map<String, Object>> maps = null;
        DPFilterParamDto filterParamDto = new DPFilterParamDto();
        filterParamDto.setCityCode(dpFilterParamForDetailDto.getCityCode());
        filterParamDto.setCompanyName(dpFilterParamForDetailDto.getCompanyName());
        filterParamDto.setSuperviseUnitName(dpFilterParamForDetailDto.getSuperviseUnitName());
        if (null != dpFilterParamForDetailDto.getTimeSearchOne()) {
            filterParamDto.setBeginDate(dpFilterParamForDetailDto.getTimeSearchOne().getBeginDate());
            filterParamDto.setEndDate(dpFilterParamForDetailDto.getTimeSearchOne().getEndDate());
        }
        if (BusinessTypeEnum.AZGZ.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = commonMapper.countBizFinishedNumForDPListAZGZ(page, orgCode, filterParamDto);
        } else if (BusinessTypeEnum.JDJY.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = commonMapper.countBizFinishedNumForDPListJDJY(page, orgCode, filterParamDto);
        } else if (BusinessTypeEnum.SYDJ.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = commonMapper.countBizFinishedNumForDPListSYDJ(page, orgCode, filterParamDto);
        } else if (BusinessTypeEnum.DQJY.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = commonMapper.countBizFinishedNumForDPListDQJY(page, orgCode, filterParamDto);
        } else if (BusinessTypeEnum.BGDJ.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = commonMapper.countBizFinishedNumForDPListBGDJ(page, orgCode, filterParamDto);
        } else if (BusinessTypeEnum.ZXBX.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = commonMapper.countBizFinishedNumForDPListZXBX(page, orgCode, filterParamDto);
        } else {
            maps = commonMapper.countBizFinishedNumForDPList(page, orgCode, filterParamDto);
        }
        return maps;
    }

    public List<Map<String, Object>> noticeListBusinessType(DPFilterParamForDetailDto dpFilterParamDto) {
        List<HashMap<String, Object>> enumList = NoticBusinessTypeEnum.getEnumList();
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("title", "业务类型");
        map.put("value", "0");
        map.put("children", enumList);
        result.add(map);
        return result;
    }

    public Page<Map<String, Object>> noticeDetailList(Page<Map<String, Object>> page, DPFilterParamForDetailDto dpFilterParamDto) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamDto.getCityCode());
        if (orgCode == null) {
            return new Page<>();
        }
        String time = LocalDate.now().minusDays(29).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (NoticBusinessTypeEnum.AZ.getCode().equals(dpFilterParamDto.getTreeValue())) {
            return jgStatisticsMapper.selectAZNoticeDetailList(page, orgCode, time, dpFilterParamDto);
        } else if (NoticBusinessTypeEnum.WX.getCode().equals(dpFilterParamDto.getTreeValue())) {
            return jgStatisticsMapper.selectWXNoticeDetailList(page, orgCode, time, dpFilterParamDto);
        } else if (NoticBusinessTypeEnum.GZ.getCode().equals(dpFilterParamDto.getTreeValue())) {
            return jgStatisticsMapper.selectGZNoticeDetailList(page, orgCode, time, dpFilterParamDto);
        } else if (NoticBusinessTypeEnum.YZ.getCode().equals(dpFilterParamDto.getTreeValue())) {
            return jgStatisticsMapper.selectYZNoticeDetailList(page, orgCode, time, dpFilterParamDto);
        } else {
            return jgStatisticsMapper.selectNoticeDetailList(page, orgCode, time, dpFilterParamDto);
        }
    }

    public List<Map<String, String>> equOnJgServiceOperationRecords(String record) {
        return commonMapper.equOnJgServiceOperationRecords(record).stream()
                .map(x -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("operatingTime", x.get("recDate"));
                    String content = String.format("%s  创建人：%s  单号【%s】  审批单位：%s",
                            x.get("businessType"), x.get("recUserName"), x.get("applyNo"), x.get("approvalUnit"));
                    map.put("content", content);
                    map.put("routePath", x.get("routePath"));
                    return map;
                })
                .collect(Collectors.toList());
    }

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

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

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

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


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

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

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

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

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

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

        if (!ObjectUtils.isEmpty(map.getString(IS_INTO_MANAGEMENT))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String param = QueryParser.escape(map.getString(IS_INTO_MANAGEMENT));
            pBuilder.must(QueryBuilders.matchQuery(IS_INTO_MANAGEMENT, param));
            boolMust.must(pBuilder);
        } else {
            if ("1".equals(map.getString("IS_SUPERVISORY"))) {
                //已赋码
                boolMust.must(QueryBuilders.existsQuery("SUPERVISORY_CODE"));
                boolMust.mustNot(QueryBuilders.termQuery("SUPERVISORY_CODE", "null"));
                //状态为已认领
                String[] status = {"草稿", "已拒领", "待认领"};
                boolMust.mustNot(QueryBuilders.termsQuery("STATUS", Arrays.asList(status)));
            } else if ("2".equals(map.getString("IS_SUPERVISORY"))) {
                //未赋码
                boolMust.mustNot(QueryBuilders.existsQuery("SUPERVISORY_CODE"));
                //状态为已认领
                String[] status = {"草稿", "已拒领", "待认领"};
                boolMust.mustNot(QueryBuilders.termsQuery("STATUS", Arrays.asList(status)));
            } else {
                //状态为已认领
                String[] status = {"草稿", "已拒领", "待认领"};
                boolMust.mustNot(QueryBuilders.termsQuery("STATUS", Arrays.asList(status)));
            }
        }

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

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

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

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

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

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

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

        // 设备类别
        if (!ObjectUtils.isEmpty(map.getString(EQU_CATEGORY_CODE))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(EQU_CATEGORY_CODE));
            pBuilder.must(QueryBuilders.termQuery(EQU_CATEGORY_CODE, test));
            boolMust.must(pBuilder);
        }
        // 是否车用气瓶
        if (CylinderTypeEnum.CYLINDER.getCode().equals(map.getString(EQU_CATEGORY_CODE))) {
            if (!ObjectUtils.isEmpty(map.getString(WHETHER_VEHICLE_CYLINDER))) {
                BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
                String test = QueryParser.escape(map.getString(WHETHER_VEHICLE_CYLINDER));
                pBuilder.must(QueryBuilders.termQuery(WHETHER_VEHICLE_CYLINDER, test));
                boolMust.must(pBuilder);
            }
        }
        // 是否撬装式压力容器
        if ("2100".equals(map.getString(EQU_CATEGORY_CODE))) {
            if (!ObjectUtils.isEmpty(map.getString(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL))) {
                if ("1".equals(map.getString(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL))) {
                    BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
                    String test = QueryParser.escape(map.getString(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL));
                    pBuilder.must(QueryBuilders.termQuery(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL, test));
                    boolMust.must(pBuilder);
                } else {
                    BoolQueryBuilder orBuilder = QueryBuilders.boolQuery();
                    orBuilder.should(QueryBuilders.termQuery(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL, "0"));
                    orBuilder.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery(WHETHER_SKID_MOUNTED_PRESSURE_VESSEL)));
                    orBuilder.minimumShouldMatch(1);
                    boolMust.must(orBuilder);
                }
            }
        }
        // 设备代码模糊查询
        if (!ObjectUtils.isEmpty(map.getString(EQU_CODE))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(EQU_CODE));
            pBuilder.must(QueryBuilders.wildcardQuery(EQU_CODE, "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 单位内部编号模糊查询
        if (!ObjectUtils.isEmpty(map.getString("USE_INNER_CODE"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_INNER_CODE"));
            pBuilder.must(QueryBuilders.wildcardQuery("USE_INNER_CODE", "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 出厂编号/产品编码模糊查询
        if (!ObjectUtils.isEmpty(map.getString(FACTORY_NUM))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(FACTORY_NUM));
            pBuilder.must(QueryBuilders.wildcardQuery(FACTORY_NUM, "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 制造单位（生产单位）名称模糊查询
        if (!ObjectUtils.isEmpty(map.getString("PRODUCE_UNIT_NAME"))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("PRODUCE_UNIT_NAME"));
            pBuilder.must(QueryBuilders.wildcardQuery("PRODUCE_UNIT_NAME", "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 模糊查询
        if (!ObjectUtils.isEmpty(map.getString(USE_PLACE_CODE))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString(USE_PLACE_CODE));
            pBuilder.must(QueryBuilders.wildcardQuery(USE_PLACE_CODE, "*" + QueryParser.escape(test.toLowerCase()) + "*"));
            boolMust.must(pBuilder);
        }
        // 工程装置名称模糊查询
        if (!ObjectUtils.isEmpty(map.getString(PROJECT_CONTRAPTION))) {
            BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
            pBuilder.must(QueryBuilders.termsQuery("PROJECT_CONTRAPTION.keyword", map.getString(PROJECT_CONTRAPTION)));
            boolMust.must(pBuilder);
        }
        builder.query(boolMust);
        builder.sort("REC_DATE", SortOrder.DESC);
        builder.from((pageNumber - 1) * size);
        builder.size(size);
        request.source(builder);
        List<JSONObject> list = new LinkedList<>();
        long totle = 0;
        if (log.isDebugEnabled()) {
            log.debug("查询es 的查询条件: {}", request);
        }
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (SearchHit hit : response.getHits().getHits()) {
                System.out.println(hit);
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hit);
                JSONObject dto2 = jsonObject.getJSONObject("sourceAsMap");
                if (!ValidationUtil.isEmpty(dto2.get(CONSTRUCTIONTYPE))) {
                    // 转化施工类型
                    String constructionType = dto2.get(CONSTRUCTIONTYPE).toString();
                    if (!ValidationUtil.isEmpty(constructionType)) {
                        List<String> constructionTypeList = Arrays.asList(constructionType.split(","));
                        List<String> statusList = new ArrayList<>();
                        for (String cType : constructionTypeList) {
                            Integer integer = Integer.valueOf(cType);
                            String status = ConstructionEnum.getName.get(integer);
                            statusList.add(status);
                        }
                        dto2.put(CONSTRUCTIONTYPE, Joiner.on(",").join(statusList));
                    }
                }
                if (!ValidationUtil.isEmpty(dto2.get(EQUSTATE))) {
                    Integer integer = Integer.valueOf(dto2.get(EQUSTATE).toString());
                    String status = EquimentEnum.getName.get(integer);
                    dto2.put(EQUSTATE, status);
                }
                if (!ValidationUtil.isEmpty(dto2.get(DATA_SOURCE))) {
                    String s = dto2.get(DATA_SOURCE).toString();
                    dto2.put(DATA_SOURCE, s);
                    dto2.put(DATA_SOURCE_NAME, EquipSourceEnum.getDataSourceName(s));
                }
                dto2.put("record", dto2.get(SEQUENCE_NBR));
                list.add(dto2);
            }

            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());
            object.put("companyType", company.getCompanyType());
        }
        return object;
    }


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

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

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

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

    public List<EquipmentCategory> getEquipmentCategoryList(String code, String type) {
        List<EquipmentCategory> result = new ArrayList<>();
        LambdaQueryWrapper<EquipmentCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipmentCategory::getCode, code);
        EquipmentCategory equipmentCategory = equipmentCategoryMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(type)) {
            if (!ValidationUtil.isEmpty(equipmentCategory)) {
                result.add(equipmentCategory);
            }
        } else {
            LambdaQueryWrapper<EquipmentCategory> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(EquipmentCategory::getParentId, equipmentCategory.getId());
            List<EquipmentCategory> equipmentCategories = equipmentCategoryMapper.selectList(wrapper2);
            if (!ValidationUtil.isEmpty(equipmentCategories)) {
                result = equipmentCategories;
            }
        }
        return result;
    }

    /**
     * 将对象的属性由驼峰转为纯大写下划线格式
     *
     * @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 = com.baomidou.mybatisplus.core.toolkit.StringUtils.camelToUnderline(fieldName).toUpperCase();
            Object value;
            try {
                value = field.get(object);
                // 需要转为jsonArray的字段
                if (!ValidationUtil.isEmpty(strToJsonArrayFields) && Arrays.asList(strToJsonArrayFields).contains(underscoreFieldName)) {
                    value = JSON.parseArray((String) field.get(object));
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            if (!ValidationUtil.isEmpty(value)) {
                result.put(underscoreFieldName.toUpperCase(), value);
            }
        }
        return result;
    }

    /**
     * 查询设备基本信息
     *
     * @param 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 = "";
        String fullArea = "";

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

        // 使用信息
        IdxBizJgUseInfo useInfo = idxBizJgUseInfoMapper.selectOne(new QueryWrapper<IdxBizJgUseInfo>().eq("RECORD", record));
        if (!ValidationUtil.isEmpty(useInfo)) {

            if (!ValidationUtil.isEmpty(useInfo.getProvince()) && !ValidationUtil.isEmpty(useInfo.getProvinceName())) {
                province = useInfo.getProvince() + "_" + useInfo.getProvinceName();
                fullAddress += useInfo.getProvinceName();
                fullArea += useInfo.getProvinceName() + "/";
            }
            if (!ValidationUtil.isEmpty(useInfo.getCity()) && !ValidationUtil.isEmpty(useInfo.getCityName())) {
                city = useInfo.getCity() + "_" + useInfo.getCityName();
                fullAddress += useInfo.getCityName();
                fullArea += useInfo.getCityName() + "/";
            }
            if (!ValidationUtil.isEmpty(useInfo.getCounty()) && !ValidationUtil.isEmpty(useInfo.getCountyName())) {
                county = useInfo.getCounty() + "_" + useInfo.getCountyName();
                fullAddress += useInfo.getCountyName();
                fullArea += useInfo.getCountyName() + "/";
            }
            if (!ValidationUtil.isEmpty(useInfo.getFactoryUseSiteStreet()) && !ValidationUtil.isEmpty(useInfo.getStreetName())) {
                street = useInfo.getFactoryUseSiteStreet() + "_" + useInfo.getStreetName();
                useInfo.setFactoryUseSiteStreet(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);
                }
                if (!ValidationUtil.isEmpty(fullArea)) {
                    useInfoMap.put("FULLAREA", fullArea.substring(0, fullArea.length() - 1));
                }
                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);
                }
                if (!ValidationUtil.isEmpty(fullArea)) {
                    useInfoMap.put("FULLAREA", fullArea.substring(0, fullArea.length() - 1));
                }
                useInfoMap.put("USEINFO_SEQ", useInfo.getSequenceNbr());
                useInfoMap.put("USE_PLACE", useInfo.getUsePlace());
                if (!ValidationUtil.isEmpty(useInfo.getLongitudeLatitude())) {
                    useInfoMap.put("LONGITUDE_LATITUDE", JSON.parseObject(useInfo.getLongitudeLatitude()));
                    useInfoMap.put("USE_LONGITUDE_LATITUDE", JSON.parseObject(useInfo.getLongitudeLatitude()));
                }
                if (!ValidationUtil.isEmpty(useInfo.getAddress())) {
                    useInfoMap.put("USE_ADDRESS", useInfo.getAddress());
                    useInfoMap.put("FULL_ADDRESS", useInfo.getAddress());
                }
            }
            if (!useInfoMap.isEmpty()) {
                Map<String, Object> filterMap = useInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }
        // 设计制造
        IdxBizJgDesignInfo designInfo = idxBizJgDesignInfoMapper.selectOne(new QueryWrapper<IdxBizJgDesignInfo>().eq("RECORD", 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 = idxBizJgFactoryInfoMapper.selectOne(new QueryWrapper<IdxBizJgFactoryInfo>().eq("RECORD", 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 = this.queryConstructionNewestDetailByRecord(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 = idxBizJgRegisterInfoMapper.selectOne(new QueryWrapper<IdxBizJgRegisterInfo>().eq("RECORD", record));
        if (!ValidationUtil.isEmpty(registerInfo)) {
            String equCategory = registerInfo.getEquCategory();// 设备类别
            String equDefine = registerInfo.getEquDefine();// 设备品种
            List<EquipmentCategory> categoryList1 = this.getEquipmentCategoryList(equCategory, null);
            List<EquipmentCategory> categoryList2 = this.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 = this.queryMaintenanceNewestDetailByRecord(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 = idxBizJgSupervisionInfoMapper.selectOne(new QueryWrapper<IdxBizJgSupervisionInfo>().eq("RECORD", 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 = idxBizJgOtherInfoMapper.selectOne(new QueryWrapper<IdxBizJgOtherInfo>().eq("RECORD", 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());
            }
            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 = this.queryInspectionNewestDetailByRecord(record);
        if (!ValidationUtil.isEmpty(inspectionDetectionInfo)) {
            Map<String, Object> inspectionDetectionInfoMap;
            if (!ValidationUtil.isEmpty(fieldType)) {
                inspectionDetectionInfoMap = Bean.BeantoMap(inspectionDetectionInfo);
                inspectionDetectionInfoMap.put("inspectiondetectioninfoSeq", inspectionDetectionInfo.getSequenceNbr());
                inspectionDetectionInfoMap.put("inspectReport", JSON.parseArray(inspectionDetectionInfo.getInspectReport()));
            } else {
                String[] fields = {"INSPECT_REPORT"};
                inspectionDetectionInfoMap = convertCamelToUnderscore(inspectionDetectionInfo, fields);
                inspectionDetectionInfoMap.put("INSPECTIONDETECTIONINFO_SEQ", inspectionDetectionInfo.getSequenceNbr());
            }
            if (!inspectionDetectionInfoMap.isEmpty()) {
                Map<String, Object> filterMap = inspectionDetectionInfoMap.entrySet()
                        .stream()
                        .filter(e -> e.getValue() != null && e.getValue() != "")
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                objMap.putAll(filterMap);
            }
        }

        objMap.put("completedBusinessTypes", judgeTheBusinessAccordingByRecord(record, objMap));
        // 账号类型（用于车用气瓶流程页面-》监管审核-》打开设备详情 时隐藏保存按钮）
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        objMap.put("accountType", reginParams.getCompany().getCompanyType());
        // 登记日期
        if (!ValidationUtil.isEmpty(registerInfo.getUseOrgCode())) {
            Optional<JgUseRegistrationManage> firstRecord = jgUseRegistrationManageMapper.selectList(new QueryWrapper<JgUseRegistrationManage>().lambda()
                    .eq(JgUseRegistrationManage::getUseRegistrationCode, registerInfo.getUseOrgCode())
                    .eq(JgUseRegistrationManage::getIsDelete, 0)
                    .orderByDesc(JgUseRegistrationManage::getRecDate)).stream().findFirst();

            firstRecord.ifPresent(jgUseRegistrationManage -> {
                Date auditPassDate = jgUseRegistrationManage.getAuditPassDate();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String formattedDate = dateFormat.format(auditPassDate);
                objMap.put("REGISTRATION_DATE", formattedDate);
            });
        }
        return objMap;
    }

    //查询最新的记录
    public IdxBizJgConstructionInfo queryConstructionNewestDetailByRecord(String record) {
        IdxBizJgConstructionInfo result = new IdxBizJgConstructionInfo();
        QueryWrapper<IdxBizJgConstructionInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(IdxBizJgConstructionInfo::getRecord, record).orderByDesc(IdxBizJgConstructionInfo::getUscDate);
        List<IdxBizJgConstructionInfo> constructionInfoList = idxBizJgConstructionInfoMapper.selectList(queryWrapper);
        if (!ValidationUtil.isEmpty(constructionInfoList)) {
            BeanUtils.copyProperties(constructionInfoList.get(0), result);
            ;
        }
        return result;
    }

    //查询最新的记录
    public IdxBizJgMaintenanceRecordInfo queryMaintenanceNewestDetailByRecord(String record) {
        IdxBizJgMaintenanceRecordInfo result = new IdxBizJgMaintenanceRecordInfo();
        QueryWrapper<IdxBizJgMaintenanceRecordInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(IdxBizJgMaintenanceRecordInfo::getRecord, record).orderByDesc(IdxBizJgMaintenanceRecordInfo::getInformEnd);
        List<IdxBizJgMaintenanceRecordInfo> maintenanceRecordInfoList = idxBizJgMaintenanceRecordInfoMapper.selectList(queryWrapper);
        if (!ValidationUtil.isEmpty(maintenanceRecordInfoList)) {
            BeanUtils.copyProperties(maintenanceRecordInfoList.get(0), result);
        }
        return result;
    }

    //查询最新的记录
    public IdxBizJgInspectionDetectionInfo queryInspectionNewestDetailByRecord(String record) {
        IdxBizJgInspectionDetectionInfo result = new IdxBizJgInspectionDetectionInfo();
        QueryWrapper<IdxBizJgInspectionDetectionInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(IdxBizJgInspectionDetectionInfo::getRecord, record).orderByDesc(IdxBizJgInspectionDetectionInfo::getInspectDate);
        List<IdxBizJgInspectionDetectionInfo> inspectionDetectionInfoList = idxBizJgInspectionDetectionInfoMapper.selectList(queryWrapper);
        if (!ValidationUtil.isEmpty(inspectionDetectionInfoList)) {
            BeanUtils.copyProperties(inspectionDetectionInfoList.get(0), result);
        }
        return result;
    }

    /**
     * 根据record判断设备完成了哪些业务（安装告知/维保备案/使用登记）
     *
     * @return
     */
    public String judgeTheBusinessAccordingByRecord(String record, Map<String, Object> objMap) {
        String business = "";
        // 安装告知
        Map<String, Object> installDetail = useRegistrationMapper.getInstallDetail(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 = useRegistrationMapper.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 = useRegistrationMapper.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 = idxBizJgTechParamsElevatorMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsElevator>().eq("RECORD", 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 = idxBizJgTechParamsVehicleMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsVehicle>().eq("RECORD", 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 = idxBizJgTechParamsRopewayMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsRopeway>().eq("RECORD", 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());
                }
                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 = idxBizJgTechParamsRidesMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsRides>().eq("RECORD", 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 = idxBizJgTechParamsBoilerMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsBoiler>().eq("RECORD", 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 = idxBizJgTechParamsVesselMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsVessel>().eq("RECORD", 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 = idxBizJgTechParamsPipelineMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsPipeline>().eq("RECORD", 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 = idxBizJgTechParamsLiftingMapper.selectOne(new QueryWrapper<IdxBizJgTechParamsLifting>().eq("RECORD", 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 = this.queryMainPartsListByRecord(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 = this.queryProtectionListByRecord(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;
    }

    public List<IdxBizJgProtectionDevices> queryProtectionListByRecord(String record) {
        QueryWrapper<IdxBizJgProtectionDevices> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(IdxBizJgProtectionDevices::getRecord, record).orderByDesc(IdxBizJgProtectionDevices::getRecDate);
        return idxBizJgProtectionDevicesMapper.selectList(queryWrapper);
    }

    public List<IdxBizJgMainParts> queryMainPartsListByRecord(String record) {
        QueryWrapper<IdxBizJgMainParts> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(IdxBizJgMainParts::getRecord, record).orderByDesc(IdxBizJgMainParts::getRecDate);
        return idxBizJgMainPartsMapper.selectList(queryWrapper);
    }

    public Page<SafetyProblemTracingDto> queryProblemPageByEquipId(Page<SafetyProblemTracingDto> page, String equipId) {
        SafetyProblemTracingDto problemModel = new SafetyProblemTracingDto();
        problemModel.setSourceId(equipId);
        return safetyProblemTracingMapper.queryForSafetyProblemTracingPage(page, problemModel);
    }

    /**
     * 根据ID查询
     */
    public SafetyProblemTracingDto selectSafetyProblem(Long sequenceNbr) {
        SafetyProblemTracingDto entity = new SafetyProblemTracingDto();
        LambdaQueryWrapper<SafetyProblemTracing> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SafetyProblemTracing::getSequenceNbr, sequenceNbr);
        SafetyProblemTracing problem = safetyProblemTracingMapper.selectOne(queryWrapper);
        BeanUtil.copyProperties(problem, entity);
        Map<String, String> problemStatusObj = new HashMap<>();
        problemStatusObj.put("problemStatusCode", entity.getProblemStatusCode());
        entity.setProblemStatusObj(problemStatusObj);
        return entity;
    }

    public Page<Map<String, Object>> queryEquipListByProblemId(Page<Map<String, Object>> page, String problemId) {
        LambdaQueryWrapper<SafetyProblemTracing> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SafetyProblemTracing::getSequenceNbr, problemId);
        SafetyProblemTracing problem = safetyProblemTracingMapper.selectOne(queryWrapper);
        Page<Map<String, Object>> list = new Page<>();
        if (problem.getSourceTypeCode().equals(SafetyProblemSourceTypeEnum.EQUIP.getCode())) {
            list = safetyProblemTracingMapper.queryEquipListByProblemId(page, problemId);
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("USE_UNIT_CREDIT_CODE", problem.getPrincipalUnitCode());
            jsonObject.put("number", page.getCurrent());
            jsonObject.put("size", page.getSize());
            Page<JSONObject> result = this.queryForEquipmentRegisterPage(jsonObject);
            List<Map<String, Object>> finalList = Lists.newArrayList();
            result.getRecords().forEach(item -> {
                Map<String, Object> map = new HashMap<>();
                map.put("record", item.get("SEQUENCE_NBR"));
                map.put("equList", item.get("EQU_LIST"));
                map.put("equListCode", item.get("EQU_LIST_CODE"));
                map.put("equCategory", item.get("EQU_CATEGORY"));
                map.put("useUnitName", item.get("USE_UNIT_NAME"));
                map.put("code96333", item.get("CODE96333"));
                map.put("supervisoryCode", item.get("SUPERVISORY_CODE"));
                map.put("problemStatus", item.get("problemStatus"));
                if (SafetyProblemStatusEnum.UNHANDLED.getCode().equals(item.get("problemStatus"))) {
                    map.put("problemStatusColor", SafetyProblemStatusEnum.UNHANDLED.getColor());
                    map.put("problemStatusName", "异常");
                } else {
                    map.put("problemStatusColor", SafetyProblemStatusEnum.HANDLED.getColor());
                    map.put("problemStatusName", "正常");
                }
                finalList.add(map);
            });
            BeanUtils.copyProperties(result, list);
            list.setRecords(finalList);
        }
        return list;
    }


    public Page<Map<String, Object>> queryPrincipalUnitByProblemId(Page<Map<String, Object>> page, String problemId) {
        LambdaQueryWrapper<SafetyProblemTracing> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SafetyProblemTracing::getSequenceNbr, problemId);
        SafetyProblemTracing problem = safetyProblemTracingMapper.selectOne(queryWrapper);
        return safetyProblemTracingMapper.queryPrincipalUnitByProblemId(page, problemId, problem.getSourceTypeCode());
    }

    /**
     * 根据sequenceNbr查询---大屏使用
     *
     * @param sequenceNbr 主键
     * @return
     */
    public Object getRegistrationDetail(String sequenceNbr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<FormValue> jsonData = getJsonData(registrationBasicJson);
        HashMap<String, Object> result = new HashMap<>();
        // 基本信息
        JgUseRegistrationManage jgUseRegistrationManage = jgUseRegistrationManageMapper.selectById(sequenceNbr);
        Map<String, Object> objectMap = Bean.BeantoMap(jgUseRegistrationManage);
        jsonData.forEach(f -> {
            Object o = objectMap.get(f.getKey());
            if (!ObjectUtils.isEmpty(o)) {
                f.setValue(o.toString());
                if ("auditPassDate".equals(f.getKey())) {
                    f.setValue(simpleDateFormat.format(jgUseRegistrationManage.getAuditPassDate()));
                }
            }
        });
        // 流水信息
        List<JgCertificateChangeRecord> changeRecordList = jgCertificateChangeRecordMapper.selectList(new LambdaQueryWrapper<JgCertificateChangeRecord>()
                .eq(JgCertificateChangeRecord::getUseRegistrationCode, jgUseRegistrationManage.getUseRegistrationCode())
                .or().eq(JgCertificateChangeRecord::getCertificateNo, jgUseRegistrationManage.getCertificateNo())
                .orderByDesc(JgCertificateChangeRecord::getCreateDate));
        List<Map<String, String>> collect = changeRecordList.stream()
                .map(x -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("operatingTime", simpleDateFormat.format(x.getRecDate()));
                    map.put("operater", x.getChangeContent());
                    map.put("label", simpleDateFormat.format(x.getRecDate()));
                    return map;
                }).collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("datas", collect);
        map.put("title", "使用登记证流水");
        map.put("renderType", "timeline");
        result.put("title", objectMap.get("useUnitName"));
        result.put("keyParams", jsonData);
        result.put("infoRecords", map);
        return result;
    }

    private List<FormValue> getJsonData(Resource resource) {
        String json;
        try {
            json = IOUtils.toString(resource.getInputStream(), String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return parseArray(json, FormValue.class);
    }

    /**
     * 根据sequenceNbr查询使用登记证对应设备列表---使用登记证详情用
     * 分页接口
     *
     * @param sequenceNbr 主键
     * @return
     */
    public Page<JSONObject> certificateEquList(int current, int size, String sequenceNbr) {
        return queryEquForPageByCertificateSeqList("", Collections.singletonList(Long.parseLong(sequenceNbr)), current, size);
    }

    /**
     * 根据证的sequenceNbr集合，批量查询证下面的所有设备
     *
     * @param enableType      启用停用业务使用 - 过滤设备状态 （1：在用 2：停用） 对应枚举：EquimentEnum
     * @param sequenceNbrList 证的sequenceNbr集合
     * @param current         分页-当前页
     * @param size            分页-分页数
     * @return 查询结果
     */
    public Page<JSONObject> queryEquForPageByCertificateSeqList(String enableType, List<Long> sequenceNbrList, int current, int size) {
        List<JgUseRegistrationManage> jgUseRegistrationManageList = jgUseRegistrationManageMapper.selectList(new LambdaQueryWrapper<JgUseRegistrationManage>()
                .in(JgUseRegistrationManage::getSequenceNbr, sequenceNbrList)
                .eq(JgUseRegistrationManage::getIsDelete, 0));
        if (ValidationUtil.isEmpty(jgUseRegistrationManageList)) {
            return new Page<>();
        }

        List<JSONObject> list = new LinkedList<>();
        long totle = 0;

        Page<JSONObject> result = new Page<>(Optional.of(current).orElse(1), Optional.of(size).orElse(10));
        Set<String> useOrgCodes = jgUseRegistrationManageList.stream().map(JgUseRegistrationManage::getUseRegistrationCode).collect(Collectors.toSet());

        // es中通过查询【使用登记证编号】所有设备
        SearchRequest request = new SearchRequest("idx_biz_view_jg_all");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        TermsQueryBuilder termsQuery = QueryBuilders.termsQuery("USE_ORG_CODE", useOrgCodes);
        boolQuery.must(termsQuery);

        // 设备状态 对应枚举EquimentEnum
        if (!ObjectUtils.isEmpty(enableType)) {
            BoolQueryBuilder elcBuilder = QueryBuilders.boolQuery();
            elcBuilder.must(QueryBuilders.matchPhraseQuery("EQU_STATE", QueryParser.escape(enableType)));
            boolQuery.must(elcBuilder);
        }

        builder.query(boolQuery);
        builder.from((current - 1) * size);
        builder.size(size);
        request.source(builder);

        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (SearchHit hit : response.getHits().getHits()) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hit);
                JSONObject dto = jsonObject.getJSONObject("sourceAsMap");
                dto.put("record", dto.get("SEQUENCE_NBR"));
                dto.put("equipAddress", dto.get("USE_PLACE") + "/" + dto.get("ADDRESS"));
                list.add(dto);
            }
            totle = Objects.requireNonNull(response.getInternalResponse().hits().getTotalHits()).value;
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.setRecords(list);
        result.setTotal(totle);
        return result;
    }

    public Page<SafetyProblemTracingDto> getProblemRecords(Page<SafetyProblemTracingDto> page, SafetyProblemTracingDto problemModel) {
        String orgCode = stCommonService.getAndSetOrgCode(problemModel.getCityCode());
        if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isEmpty(orgCode)) {
            return new Page<>();
        }
        // 默认登录监管单位orgcode过滤
        problemModel.setGoverningBodyOrgCode(orgCode);
        if (!ObjectUtils.isEmpty(problemModel.getGoverningBodyOrgCode())) {
            // 筛选条件起效
            problemModel.setGoverningBodyOrgCode(problemModel.getGoverningBodyOrgCode());
        }
        // 使用orgCode过滤
        // 将单位类型从code转化为value
        if (!ValidationUtil.isEmpty(problemModel.getPrincipalUnitType())) {
            Collection<DataDictionary> unitTypeList = iDataDictionaryService.list(new QueryWrapper<DataDictionary>()
                    .eq("type", "UNIT_TYPE_NEW")
                    .eq("is_delete", false)
                    .orderByAsc("sort_num"));
            Map<String, String> unitTypeMap = unitTypeList.stream().collect(Collectors.toMap(DataDictionary::getCode, DataDictionary::getName));
            problemModel.setPrincipalUnitType(unitTypeMap.getOrDefault(problemModel.getPrincipalUnitType(), null));
        }
        return safetyProblemTracingMapper.queryForSafetyProblemTracingPage(page, problemModel);
    }

    public Page<JgUseRegistrationManageDto> getRegistrationRecords(Page<JgUseRegistrationManageDto> page, JgUseRegistrationManageDto dto, String cityCode) {
        String orgCode = stCommonService.getAndSetOrgCode(cityCode);
        return jgUseRegistrationManageMapper.getRecords(page, dto, orgCode);
    }

    public Map<String, Object> getProblemChart(SafetyProblemTracingDto problemModel) {
        String orgCode = stCommonService.getAndSetOrgCode(problemModel.getCityCode());
        if (ObjectUtils.isEmpty(orgCode)) {
            return new HashMap<>();
        }
        Map<String, Object> resultMap = new HashMap<>();
        String sourceTypeCode = "all".equals(problemModel.getSourceTypeCode()) ? null : problemModel.getSourceTypeCode();
        List<String> xdata = safetyProblemTracingMapper.getBusinessType(sourceTypeCode, orgCode);
        if (ObjectUtils.isEmpty(xdata)) {
            return resultMap;
        }
        List<Map<String, Object>> countMap = safetyProblemTracingMapper.getBusinessCount(sourceTypeCode, orgCode);
        List<String> redCount = new ArrayList<>();
        List<String> yellowCount = new ArrayList<>();
        List<String> greenCount = new ArrayList<>();
        List<String> greyCount = new ArrayList<>();
        List<String> stationRates = new ArrayList<>();

        xdata.forEach(r -> {
            List<Map<String, Object>> redList = countMap.stream().filter(map -> map.get("problemType").equals(r) && "0".equals(map.get("problemStatusCode").toString())).collect(Collectors.toList());
            List<Map<String, Object>> greenList = countMap.stream().filter(map -> map.get("problemType").equals(r) && "1".equals(map.get("problemStatusCode").toString())).collect(Collectors.toList());
            String red = ObjectUtils.isEmpty(redList) ? "0" : redList.get(0).get("num").toString();
            String green = ObjectUtils.isEmpty(greenList) ? "0" : greenList.get(0).get("num").toString();
            redCount.add(red);
            greenCount.add(green);
            yellowCount.add("0");
            greyCount.add("0");
            Long problemSum = Long.valueOf(red) + Long.valueOf(green);
            BigDecimal percent = (new BigDecimal(Double.valueOf(green) * 100).divide(new BigDecimal(problemSum.doubleValue()), 2, RoundingMode.HALF_UP));
            stationRates.add(percent.toString());
        });
        Set<Map<String, String>> legendData = new HashSet<>();
        for (int i = 0; i < 5; i++) {
            Map<String, String> map = new HashMap<>();
            if (i == 0) {
                map.put("dataKey", "redCount");
                map.put("value", "红");
                map.put("chartType", "bar");
            } else if (i == 1) {
                map.put("dataKey", "yellowCount");
                map.put("value", "黄");
                map.put("chartType", "bar");
            } else if (i == 2) {
                map.put("dataKey", "greenCount");
                map.put("value", "绿");
                map.put("chartType", "bar");
            } else if (i == 3) {
                map.put("dataKey", "greyCount");
                map.put("value", "灰");
                map.put("chartType", "bar");
            } else {
                map.put("dataKey", "stationRate");
                map.put("value", "闭环率");
                map.put("chartType", "line");
            }
            legendData.add(map);
        }
        resultMap.put("legendData", legendData);
        resultMap.put("xdata", xdata);
        resultMap.put("redCount", redCount);
        resultMap.put("yellowCount", yellowCount);
        resultMap.put("greenCount", greenCount);
        resultMap.put("greyCount", greyCount);
        resultMap.put("stationRate", stationRates);
        return resultMap;
    }

    public List<Map<String, Object>> getJgBusinessType() {
        List<HashMap<String, Object>> enumList = JgBusinessTypeEnum.getEnumList();
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("title", "监督管理全部业务");
        map.put("value", "all");
        map.put("children", enumList);
        result.add(map);
        return result;
    }

    public Page<Map<String, Object>> getJgBusinessList(DPFilterParamForDetailDto dpFilterParamForDetailDto, Page<Map<String, Object>> page) {
        String orgCode = stCommonService.getAndSetOrgCode(dpFilterParamForDetailDto.getCityCode());
        Page<Map<String, Object>> maps = null;
        DPFilterParamDto filterParamDto = new DPFilterParamDto();
        filterParamDto.setCityCode(dpFilterParamForDetailDto.getCityCode());
        filterParamDto.setCompanyName(dpFilterParamForDetailDto.getCompanyName());
        filterParamDto.setSuperviseUnitName(dpFilterParamForDetailDto.getSuperviseUnitName());
        filterParamDto.setBusinessTypeCode(dpFilterParamForDetailDto.getBusinessTypeCode());
        filterParamDto.setEquCategoryCode(dpFilterParamForDetailDto.getEquCategoryCode());
        filterParamDto.setEquListCode(dpFilterParamForDetailDto.getEquListCode());
        filterParamDto.setStatus(dpFilterParamForDetailDto.getStatus());
        if (null != dpFilterParamForDetailDto.getTimeSearchOne()) {
            filterParamDto.setBeginDate(dpFilterParamForDetailDto.getTimeSearchOne().getBeginDate());
            filterParamDto.setEndDate(dpFilterParamForDetailDto.getTimeSearchOne().getEndDate());
        }
        // 判断是否根据具体的业务类型筛选，如果是则需要将treeValue置空，满足对应xml中的动态union all
        // 当BusinessTypeCode不为空，则查对应BusinessTypeCode具体的业务，此时需要将treeValue置空，取消xml中的union all 拼接
        // 当BusinessTypeCode为空，则查询对应treeValue下所有业务，此时不能将treeValue置空，需要使用xml中的union all 拼接各个业务查询
        String treeValue = dpFilterParamForDetailDto.getBusinessTypeCode() != "" ? null : dpFilterParamForDetailDto.getTreeValue();
        if (JgBusinessTypeEnum.SGGZ.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = jgStatisticsMapper.countBizFinishedNumForDPListSGGZ(page, orgCode, filterParamDto, treeValue);
        } else if (JgBusinessTypeEnum.SYDJ.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = jgStatisticsMapper.countBizFinishedNumForDPListSYDJ(page, orgCode, filterParamDto, treeValue);
        } else if (JgBusinessTypeEnum.BGDJ.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = jgStatisticsMapper.countBizFinishedNumForDPListBGDJ(page, orgCode, filterParamDto, treeValue);
        } else if (JgBusinessTypeEnum.TYQY.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = jgStatisticsMapper.countBizFinishedNumForDPListTYQY(page, orgCode, filterParamDto, treeValue);
        } else if (JgBusinessTypeEnum.ZXBX.getCode().equals(dpFilterParamForDetailDto.getTreeValue())) {
            maps = jgStatisticsMapper.countBizFinishedNumForDPListZXBF(page, orgCode, filterParamDto, treeValue);
        } else {
            maps = jgStatisticsMapper.countBizFinishedNumForDPListAll(page, orgCode, filterParamDto, treeValue);
        }
        return maps;
    }

    public List<Map<String, Object>> getJgBusinessAllType(String treeValue) {
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(allBusinessType);
        return resourceJson.get(treeValue);
    }

    public Map<String, Object> queryBarChartDataForSkjs(DPFilterParamDto dpFilterParamDto) {
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParentAndNoAccessIf3Level(dpFilterParamDto);
        String orgCodeP = stCommonService.getAndSetOrgCode(dpFilterParamDto);
        List<LegendDataDto> legendDataDtos = this.buildLegendDataListForSkjs();
        // 2.按照前端约定格式返回数据
        Map<String, Object> result = new HashMap<>();
        //2.1 图列数据构造
        result.put("legendData", legendDataDtos);
        if (orgCodeP == null) {
            return result;
        }
        List<String> xData = new ArrayList<>();
        // 2.2 Y轴数据构造 定义5个图列 再查询各自数据
        List<String> oneSetYData = new ArrayList<>();
        List<String> cylinderYData = new ArrayList<>();
        List<String> pipelineYData = new ArrayList<>();
        List<String> companyYData = new ArrayList<>();
        List<String> userYData = new ArrayList<>();
        // 多线程处理
        Map<String, SkjsCountItemDto> countItemMap = regionModels.parallelStream().map(r -> {
            String regionCode = r.getRegionCode().toString();
            String orgCode = stCommonService.getAndSetOrgCode(regionCode);
            SkjsCountItemDto countItemDto = new SkjsCountItemDto();
            countItemDto.setRegionCode(regionCode);
            if (!ValidationUtil.isEmpty(orgCode)) {
                Map<String, Object> data = new HashMap<>();
                // 查询各自统计数据作为Y轴数据
                // 0. 气瓶数量统计
                long cylinderNum = stCommonService.staticsCenterMapCountDataForCylinder(data, orgCode, false, false, false);
                countItemDto.setCylinder(String.valueOf(cylinderNum));
                // 1. 设备数量统计
                long oneSetNum = stCommonService.staticsCenterMapCountDataForEquip(data, cylinderNum, orgCode, true, false, false);
                countItemDto.setOneSet(String.valueOf(oneSetNum));
                // 2. 压力管道长度统计
                countItemDto.setPipeline(stCommonService.staticsCenterMapCountDataForPipeline(data, orgCode, true, false));
                // 3. 单位数量统计
                this.staticsCompanyForSkjs(countItemDto, orgCode, regionCode);
                // 4. 人员数量统计
                this.staticsUserForSkjs(countItemDto, regionCode, orgCode);
            } else {
                countItemDto.setDefaultValues();
            }
            return countItemDto;
        }).collect(Collectors.toMap(SkjsCountItemDto::getRegionCode, Function.identity()));
        // 排序及数据构建
        regionModels.forEach(r -> {
            xData.add(r.getRegionName());
            SkjsCountItemDto countItemDto = countItemMap.get(r.getRegionCode().toString());
            oneSetYData.add(countItemDto.getOneSet());
            cylinderYData.add(countItemDto.getCylinder());
            pipelineYData.add(countItemDto.getPipeline());
            companyYData.add(countItemDto.getCompany());
            userYData.add(countItemDto.getUser());
        });
        result.put("oneSet", oneSetYData);
        result.put("cylinder", cylinderYData);
        result.put("pipeline", pipelineYData);
        result.put("company", companyYData);
        result.put("user", userYData);
        result.put("xdata", xData);
        return result;
    }

    private List<LegendDataDto> buildLegendDataListForSkjs() {
        List<LegendDataDto> legendDataDtos = new ArrayList<>();
        legendDataDtos.add(LegendDataDto.builder().dataKey("oneSet").value("设备（台套）").build());
        legendDataDtos.add(LegendDataDto.builder().dataKey("cylinder").value("气瓶（个）").build());
        legendDataDtos.add(LegendDataDto.builder().dataKey("pipeline").value("压力管道（千米）").build());
        legendDataDtos.add(LegendDataDto.builder().dataKey("company").value("企业").build());
        legendDataDtos.add(LegendDataDto.builder().dataKey("user").value("人员").build());
        return legendDataDtos;
    }

    public Map<String, Object> querySkjsDetail(DPFilterParamDto dpFilterParamDto) {
        String orgCodeP = stCommonService.getAndSetOrgCode(dpFilterParamDto);
        List<RegionModel> regionModels = stCommonService.setRegionIfRootParentAndNoAccessIf3Level(dpFilterParamDto);
        List<RegionModelDto> regionModelsDto = new ArrayList<>();
        regionModels.forEach(r -> {
            RegionModelDto regionModelDto = new RegionModelDto();
            regionModelDto.setRegionCode(r.getRegionCode().toString());
            regionModelDto.setRegionName(r.getRegionName());
            regionModelDto.setLevel(r.getLevel());
            regionModelDto.setParentRegionCode(Objects.toString(r.getParentRegionCode()));
            regionModelsDto.add(regionModelDto);
        });
        if (orgCodeP == null || regionModels.isEmpty()) {
            return this.getDefaultSkjsDetail();
        }

        Map<String, Object> result = new HashMap<>();
        // 设备上线情况
        result.put("equipOnLineInfo", this.getEquipOnLineInfo(regionModelsDto));
        // 企业上线情况
        result.put("companyOnLineInfo", this.getCompanyOnLineInfo(regionModelsDto));
        // 人员上线情况
        result.put("userOnLineInfo", this.getUserOnLineInfo(regionModelsDto));
        return result;
    }

    private Map<String, Object> getDefaultSkjsDetail() {
        Map<String, Object> result = new HashMap<>();
        // 设备上线情况
        result.put("equipOnLineInfo", new ArrayList<>());
        // 企业上线情况
        result.put("companyOnLineInfo", new ArrayList<>());
        // 人员上线情况
        result.put("userOnLineInfo", new ArrayList<>());
        return result;
    }

    private Object getEquipOnLineInfo(List<RegionModelDto> regionModels) {
        List<Map<String, Object>> baselineData;
        // 如果是地市数据则计算上线率，上线率=系统已有数据/最新期底数x100%
        if (RegulatoryUnitLevelEnum.CITY.getLevel().equals(regionModels.get(0).getLevel())
                || regionModels.stream().anyMatch(e -> RegulatoryUnitLevelEnum.PROVINCE.getLevel().equals(e.getLevel()))) {
            baselineData = zlStatisticsMapper.getEquBaselineData();
        } else {
            baselineData = Lists.newArrayList();
        }
        // 多线程处理
        Map<String, SkjsEquipCountItemDto> countItemMap = regionModels.parallelStream().map(r -> {
            String regionCode = r.getRegionCode();
            String orgCode = stCommonService.getAndSetOrgCode(regionCode);
            SkjsEquipCountItemDto countItemDto = new SkjsEquipCountItemDto();
            countItemDto.setRegionCode(regionCode);
            countItemDto.setRegionName(r.getRegionName());
            countItemDto.setOrgBranchCode(orgCode);
            if (!ValidationUtil.isEmpty(orgCode)) {
                Map<String, Object> data = new HashMap<>();
                // 是否按监管机构代码精确匹配
                Boolean isOrgBranchCodeExactMatch = !ValidationUtil.isEmpty(RegulatoryUnitLevelEnum.getEnumByLevelCode(r.getLevel()));
                // 0. 气瓶数量统计
                long cylinderNum = stCommonService.staticsCenterMapCountDataForCylinder(data, orgCode, false, false, isOrgBranchCodeExactMatch);
                countItemDto.setQp(String.valueOf(cylinderNum));
                // 1. 设备数量统计-台套
                stCommonService.staticsCenterMapCountDataForEquip(data, cylinderNum, orgCode, true, false, isOrgBranchCodeExactMatch);
                countItemDto.setDt(String.valueOf(data.get(DPMapStatisticsItemEnum.ELEVATORS.getCode())));
                countItemDto.setQzjx(String.valueOf(data.get(DPMapStatisticsItemEnum.LIFTING_MACHINERY.getCode())));
                countItemDto.setKysd(String.valueOf(data.get(DPMapStatisticsItemEnum.PASSENGER_ROPEWAYS.getCode())));
                countItemDto.setDxylss(String.valueOf(data.get(DPMapStatisticsItemEnum.LARGE_AMUSEMENT_FACILITIES.getCode())));
                countItemDto.setCc(String.valueOf(data.get(DPMapStatisticsItemEnum.ON_SITE_MOTOR_VEHICLES.getCode())));
                countItemDto.setGl(String.valueOf(data.get(DPMapStatisticsItemEnum.BOILERS.getCode())));
                countItemDto.setYlrq(String.valueOf(data.get(DPMapStatisticsItemEnum.PRESSURE_VESSELS.getCode())));
                // 2. 压力管道长度统计
                countItemDto.setYlgd(stCommonService.staticsCenterMapCountDataForPipeline(data, orgCode, true, isOrgBranchCodeExactMatch));
                // 如果是地市数据则计算上线率，上线率=系统已有数据/最新期底数x100%
                if ("610000".equals(r.getParentRegionCode())) {
                    Map<String, Object> baselineMap = baselineData.stream().filter(d -> d.get("city_code").equals(regionCode)).findFirst().orElse(null);
                    if (!ValidationUtil.isEmpty(baselineMap)) {
                        countItemDto.setGlBaseline(baselineMap.get("boiler").toString());
                        countItemDto.setGlOnlineRate(calculateRate(countItemDto.getGl(), baselineMap.get("boiler").toString()));
                        countItemDto.setDtBaseline(baselineMap.get("elevator").toString());
                        countItemDto.setDtOnlineRate(calculateRate(countItemDto.getDt(), baselineMap.get("elevator").toString()));
                        countItemDto.setQzjxBaseline(baselineMap.get("lifting").toString());
                        countItemDto.setQzjxOnlineRate(calculateRate(countItemDto.getQzjx(), baselineMap.get("lifting").toString()));
                        countItemDto.setKysdBaseline(baselineMap.get("ropeway").toString());
                        countItemDto.setKysdOnlineRate(calculateRate(countItemDto.getKysd(), baselineMap.get("ropeway").toString()));
                        countItemDto.setDxylssBaseline(baselineMap.get("rides").toString());
                        countItemDto.setDxylssOnlineRate(calculateRate(countItemDto.getDxylss(), baselineMap.get("rides").toString()));
                        countItemDto.setCcBaseline(baselineMap.get("vehicle").toString());
                        countItemDto.setCcOnlineRate(calculateRate(countItemDto.getCc(), baselineMap.get("vehicle").toString()));
                        countItemDto.setQpBaseline(baselineMap.get("cylinder").toString());
                        countItemDto.setQpOnlineRate(calculateRate(countItemDto.getQp(), baselineMap.get("cylinder").toString()));
                        countItemDto.setYlrqBaseline(baselineMap.get("vessel").toString());
                        countItemDto.setYlrqOnlineRate(calculateRate(countItemDto.getYlrq(), baselineMap.get("vessel").toString()));
                        countItemDto.setYlgdBaseline(baselineMap.get("pipeline").toString());
                        countItemDto.setYlgdOnlineRate(calculateRate(countItemDto.getYlgd(), baselineMap.get("pipeline").toString()));
                    }
                }
            } else {
                countItemDto.setDefaultValues();
            }
            return countItemDto;
        }).collect(Collectors.toMap(SkjsEquipCountItemDto::getRegionCode, Function.identity()));
        // 排序
        List<SkjsEquipCountItemDto> countItemDtos = regionModels.stream().map(r -> countItemMap.get(r.getRegionCode().toString())).collect(Collectors.toList());
        // 设置汇总数据
        this.setEquipSummaryRow(countItemDtos);
        return countItemDtos;
    }

    private String calculateRate(String numerator, String denominator) {
        double num = NumberUtils.toDouble(numerator, 0.0);
        double den = NumberUtils.toDouble(denominator, 0.0);

        if (den == 0) {
            return num == 0 ? "0%" : "100%";
        } else if (num == 0) {
            return "0%";
        }
        
        double rate = num / den;
        if (rate >= 1) {
            return "100%";
        }
        // 如果是整数百分比，则返回不带小数的形式，否则保留两位小数
        if (rate * 100 % 1 == 0) {
            return String.format("%d%%", (int) (rate * 100));
        } else {
            return String.format("%.2f%%", rate * 100);
        }
    }

    private Object getCompanyOnLineInfo(List<RegionModelDto> regionModels) {
        // 多线程处理
        Map<String, SkjsCompanyCountItemDto> companyCountItemDtoMap = regionModels.parallelStream().map(r -> {
            String regionCode = r.getRegionCode();
            String conditionRegionCode = regionCode;
            String orgCode = stCommonService.getAndSetOrgCode(regionCode);
            // 按管辖机构统计企业数量时：检验检测机构直接归属省局管辖，则只有省局才统计检验检测机构数量。其他地市区县不统计
            // 只有按监管单位统计（r.getLevel()为空或者为省市区县级）才需要判断是否传regionCode
            if (!ValidationUtil.isEmpty(RegulatoryUnitLevelEnum.getEnumByLevelCode(r.getLevel())) || ValidationUtil.isEmpty(r.getLevel())) {
                if (!RegulatoryUnitLevelEnum.PROVINCE.getLevel().equals(r.getLevel())) {
                    conditionRegionCode = null;
                }
            }
            // 按管辖机构统计企业数量时：如果统计本监管单位则使用精确匹配
            boolean isOrgCodeExactMatch = !ValidationUtil.isEmpty(RegulatoryUnitLevelEnum.getEnumByLevelCode(r.getLevel()));
            SkjsCompanyCountItemDto companyCountItemDto = new SkjsCompanyCountItemDto();
            companyCountItemDto.setRegionCode(regionCode);
            companyCountItemDto.setRegionName(r.getRegionName());
            companyCountItemDto.setSuperviseKey(regionCode + "_" + r.getRegionName());
            if (StringUtils.isNotEmpty(orgCode)) {
                List<CountDto> countDtos = enterpriseInfoMapper.countByUnitTypeAndOrgCode(orgCode, conditionRegionCode, isOrgCodeExactMatch);
                int u1 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_USE) || c.getKeyStr().contains(COMPANY_TYPE_PERSON)).mapToInt(CountDto::getIntValue).sum();
                int u3 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_MANUFACTURE)).mapToInt(CountDto::getIntValue).sum();
                int u2 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_MAINTENANCE)).mapToInt(CountDto::getIntValue).sum();
                int u4 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_FILLING)).mapToInt(CountDto::getIntValue).sum();
                int u6 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_JYJC)).mapToInt(CountDto::getIntValue).sum();
                int u5 = countDtos.stream().filter(c -> c.getKeyStr().contains(COMPANY_TYPE_DESIGN)).mapToInt(CountDto::getIntValue).sum();
                companyCountItemDto.setSydw(String.valueOf(u1));
                companyCountItemDto.setZzdw(String.valueOf(u3));
                companyCountItemDto.setAgwdw(String.valueOf(u2));
                companyCountItemDto.setCzdw(String.valueOf(u4));
                companyCountItemDto.setJyjcjg(String.valueOf(u6));
                companyCountItemDto.setSjdw(String.valueOf(u5));
            } else {
                companyCountItemDto.setDefaultValues();
            }
            return companyCountItemDto;
        }).collect(Collectors.toMap(SkjsCompanyCountItemDto::getRegionCode, Function.identity()));
        // 按照区域排序
        List<SkjsCompanyCountItemDto> countItemDtos = regionModels.stream().map(r -> companyCountItemDtoMap.get(r.getRegionCode().toString())).collect(Collectors.toList());
        // 汇总数据处理
        this.setCompanySummaryRow(countItemDtos);
        return countItemDtos;
    }


    private Object getUserOnLineInfo(List<RegionModelDto> regionModels) {
        // 多线程处理
        Map<String, SkjsUserCountItemDto> userCountItemDtoMap = regionModels.parallelStream().map(r -> {
            String regionCode = r.getRegionCode().toString();
            String conditionRegionCode = regionCode;
            String orgCode = stCommonService.getAndSetOrgCode(regionCode);
            SkjsUserCountItemDto userCountItemDto = new SkjsUserCountItemDto();
            userCountItemDto.setRegionCode(regionCode);
            userCountItemDto.setRegionName(r.getRegionName());
            userCountItemDto.setSuperviseKey(regionCode + "_" + r.getRegionName());
            //按管辖机构统计企业数量时：检验检测机构直接归属省局管辖，则只有省局才统计检验检测机构数量。其他地市区县不统计
            //只有按监管单位统计（r.getLeveL（)为空或者为省市区县级）才需要判断是否传regionCode
            if (!ValidationUtil.isEmpty(RegulatoryUnitLevelEnum.getEnumByLevelCode(r.getLevel())) || ValidationUtil.isEmpty(r.getLevel())) {
                if (!RegulatoryUnitLevelEnum.PROVINCE.getLevel().equals(r.getLevel())) {
                    conditionRegionCode = null;
                }
            }
            //按管辖机构统计企业数量时：如果统计本监管单位则使用精确匹配
            boolean isOrgCodeExactMatch = !ValidationUtil.isEmpty(RegulatoryUnitLevelEnum.getEnumByLevelCode(r.getLevel()));
            if (StringUtils.isNotEmpty(orgCode)) {
                List<CountDto> countDtos = zlStatisticsMapper.countUserByPostAndAreaCode(orgCode, conditionRegionCode, isOrgCodeExactMatch);
                // 作业人员
                int zyry = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.ZYRY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 检验人员
                int jyry = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.ZJRY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 检测人员
                int jcyr = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.JCRY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 生产[设计单位、安改维、制造单位]-主要负责人
                int sczyfzr = countDtos.stream().filter(c -> (c.getKeyStr().contains(COMPANY_TYPE_MANUFACTURE) || c.getKeyStr().contains(COMPANY_TYPE_DESIGN) || c.getKeyStr().contains(COMPANY_TYPE_MAINTENANCE)) && c.getKeyStr().contains(UserPostEnum.ZYFZR.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 生产[设计单位、安改维、制造单位]-质量安全总监
                int sczlaqzj = countDtos.stream().filter(c -> (c.getKeyStr().contains(COMPANY_TYPE_MANUFACTURE) || c.getKeyStr().contains(COMPANY_TYPE_DESIGN) || c.getKeyStr().contains(COMPANY_TYPE_MAINTENANCE)) && c.getKeyStr().contains(UserPostEnum.ZLAQZJ.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 生产[设计单位、安改维、制造单位]-质量安全员
                int sczlaqy = countDtos.stream().filter(c -> (c.getKeyStr().contains(COMPANY_TYPE_MANUFACTURE) || c.getKeyStr().contains(COMPANY_TYPE_DESIGN) || c.getKeyStr().contains(COMPANY_TYPE_MAINTENANCE)) && c.getKeyStr().contains(UserPostEnum.ZLAQY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 使用单位[使用单位、个人主体]-主要负责人
                int syzyfzr = countDtos.stream().filter(c -> (c.getKeyStr().contains(COMPANY_TYPE_USE) || c.getKeyStr().contains(COMPANY_TYPE_PERSON)) && c.getKeyStr().contains(UserPostEnum.ZYFZR.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 使用单位[使用单位、个人主体]-安全总监
                int syaqzj = countDtos.stream().filter(c -> (c.getKeyStr().contains(COMPANY_TYPE_USE) || c.getKeyStr().contains(COMPANY_TYPE_PERSON)) && c.getKeyStr().contains(UserPostEnum.AQZJ.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 使用单位[使用单位、个人主体]-安全员
                int syaqy = countDtos.stream().filter(c -> (c.getKeyStr().contains(COMPANY_TYPE_USE) || c.getKeyStr().contains(COMPANY_TYPE_PERSON)) && c.getKeyStr().contains(UserPostEnum.AQY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 技术负责人
                int jsfzr = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.JSFZR.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 设计人员
                int sjry = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.SJRY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 技术人员
                int jsry = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.JSRY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 质量检验人员
                int zljyry = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.ZLJYRY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 项目负责人
                int xmfzr = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.XMFZR.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 理化检验人员
                int lhjyry = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.LHJYRY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 化验人员
                int hyry = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.HYRY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 检验检测区域负责人
                int jyjcqyfzr = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.JYJCQYFZR.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 质量保证体系人员
                int zlbztxry = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.ZLBZTXRY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 安全管理员
                int aqgly = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.AQGLY.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 质量负责人
                int zlfzr = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.ZLFZR.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 责任师
                int zrs = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.ZRS.getCode())).mapToInt(CountDto::getIntValue).sum();
                // 检查人员
                int jcary = countDtos.stream().filter(c -> c.getKeyStr().contains(UserPostEnum.JCARY.getCode())).mapToInt(CountDto::getIntValue).sum();
                userCountItemDto.setZyry(String.valueOf(zyry));
                userCountItemDto.setJyry(String.valueOf(jyry));
                userCountItemDto.setJcry(String.valueOf(jcyr));
                userCountItemDto.setSczyfzr(String.valueOf(sczyfzr));
                userCountItemDto.setSczlaqzj(String.valueOf(sczlaqzj));
                userCountItemDto.setSczlaqy(String.valueOf(sczlaqy));
                userCountItemDto.setSyzyfzr(String.valueOf(syzyfzr));
                userCountItemDto.setSyaqzj(String.valueOf(syaqzj));
                userCountItemDto.setSyaqy(String.valueOf(syaqy));
                userCountItemDto.setJsfzr(String.valueOf(jsfzr));
                userCountItemDto.setSjry(String.valueOf(sjry));
                userCountItemDto.setJsry(String.valueOf(jsry));
                userCountItemDto.setZljyry(String.valueOf(zljyry));
                userCountItemDto.setXmfzr(String.valueOf(xmfzr));
                userCountItemDto.setLhjyry(String.valueOf(lhjyry));
                userCountItemDto.setHyry(String.valueOf(hyry));
                userCountItemDto.setJyjcqyfzr(String.valueOf(jyjcqyfzr));
                userCountItemDto.setZlbztxry(String.valueOf(zlbztxry));
                userCountItemDto.setAqgly(String.valueOf(aqgly));
                userCountItemDto.setZlfzr(String.valueOf(zlfzr));
                userCountItemDto.setZrs(String.valueOf(zrs));
                userCountItemDto.setJcary(String.valueOf(jcary));
            } else {
                userCountItemDto.setDefaultValues();
            }
            return userCountItemDto;
        }).collect(Collectors.toMap(SkjsUserCountItemDto::getRegionCode, Function.identity()));
        // 排序
        List<SkjsUserCountItemDto> userCountItemDtos = regionModels.stream().map(r -> userCountItemDtoMap.get(r.getRegionCode().toString())).collect(Collectors.toList());
        // 汇总行构建
        this.setUserSummaryRow(userCountItemDtos);
        return userCountItemDtos;
    }

    private void setUserSummaryRow(List<SkjsUserCountItemDto> countItems) {
        SkjsUserCountItemDto summary = new SkjsUserCountItemDto();
        summary.setRegionCode("summary");
        summary.setRegionName("合计");
        summary.setZyry(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getZyry())).sum()));
        summary.setJyry(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getJyry())).sum()));
        summary.setJcry(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getJcry())).sum()));
        summary.setSczyfzr(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getSczyfzr())).sum()));
        summary.setSczlaqzj(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getSczlaqzj())).sum()));
        summary.setSczlaqy(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getSczlaqy())).sum()));
        summary.setSyzyfzr(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getSyzyfzr())).sum()));
        summary.setSyaqzj(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getSyaqzj())).sum()));
        summary.setSyaqy(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getSyaqy())).sum()));
        summary.setJsfzr(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getJsfzr())).sum()));
        summary.setSjry(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getSjry())).sum()));
        summary.setJsry(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getJsry())).sum()));
        summary.setZljyry(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getZljyry())).sum()));
        summary.setXmfzr(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getXmfzr())).sum()));
        summary.setLhjyry(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getLhjyry())).sum()));
        summary.setHyry(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getHyry())).sum()));
        summary.setJyjcqyfzr(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getJyjcqyfzr())).sum()));
        summary.setZlbztxry(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getZlbztxry())).sum()));
        summary.setAqgly(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getAqgly())).sum()));
        summary.setZlfzr(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getZlfzr())).sum()));
        summary.setZrs(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getZrs())).sum()));
        summary.setJcary(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getJcary())).sum()));
        countItems.add(summary);
    }

    private void setCompanySummaryRow(List<SkjsCompanyCountItemDto> countItems) {
        SkjsCompanyCountItemDto summary = new SkjsCompanyCountItemDto();
        summary.setRegionCode("summary");
        summary.setRegionName("合计");
        summary.setSydw(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getSydw())).sum()));
        summary.setZzdw(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getZzdw())).sum()));
        summary.setAgwdw(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getAgwdw())).sum()));
        summary.setCzdw(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getCzdw())).sum()));
        summary.setJyjcjg(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getJyjcjg())).sum()));
        summary.setSjdw(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getSjdw())).sum()));
        countItems.add(summary);
    }


    private void setEquipSummaryRow(List<SkjsEquipCountItemDto> countItems) {
        SkjsEquipCountItemDto summary = new SkjsEquipCountItemDto();
        summary.setRegionCode("summary");
        summary.setRegionName("合计");
        summary.setDt(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getDt())).sum()));
        summary.setQzjx(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getQzjx())).sum()));
        summary.setKysd(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getKysd())).sum()));
        summary.setDxylss(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getDxylss())).sum()));
        summary.setCc(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getCc())).sum()));
        summary.setGl(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getGl())).sum()));
        summary.setYlrq(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getYlrq())).sum()));
        summary.setYlgd(sumWithValidation(countItems));
        summary.setQp(String.valueOf(countItems.stream().mapToLong(e -> Long.parseLong(e.getQp())).sum()));
        countItems.add(summary);
    }

    public String sumWithValidation(List<SkjsEquipCountItemDto> list) {
        return list.stream()
                .filter(Objects::nonNull)
                .map(item -> {
                    try {
                        return new BigDecimal(item.getYlgd());
                    } catch (NumberFormatException e) {
                        log.warn("Invalid number in item {}", item);
                        return BigDecimal.ZERO;
                    }
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(3, RoundingMode.HALF_UP).toPlainString();
    }

    public List<Map<String, Object>> getSuperviseTreeByLoginUnitCode(String orgCode) {
        List<Map<String, Object>> result = (List<Map<String, Object>>) redisUtils.get(REGULATOR_UNIT_TREE);
        return filterByOrgCode(result, orgCode);
    }

    public List<Map<String, Object>> filterByOrgCode(List<Map<String, Object>> nodeList, String targetOrgCode) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> node : nodeList) {
            String currentOrgCode = (String) node.get("orgCode");
            if (targetOrgCode.equals(currentOrgCode)) {
                // 深拷贝当前节点避免修改原数据
                Map<String, Object> copiedNode = new HashMap<>(node);
                result.add(copiedNode);
                return result;
            } else {
                // 检查子节点是否存在匹配
                List<Map<String, Object>> children = (List<Map<String, Object>>) node.get("children");
                if (children != null && !children.isEmpty()) {
                    List<Map<String, Object>> filteredChildren = filterByOrgCode(children, targetOrgCode);
                    if (!filteredChildren.isEmpty()) {
                        Map<String, Object> copiedNode = new HashMap<>(filteredChildren.get(0));
                        result.add(copiedNode);
                        return result;
                    }
                }
            }
        }
        return result;
    }

    public Map<String, Object> queryBarChartDataForSkjsBySupervise(DPFilterParamDto dpFilterParamDto) {
        String orgCodeP = stCommonService.getAndSetOrgCode(dpFilterParamDto);
        Map<String, Object> parentModel = getSuperviseTreeByLoginUnitCode(orgCodeP).get(0);
        List<Map<String, Object>> regionModels = (List<Map<String, Object>>) parentModel.get("children");
        List<LegendDataDto> legendDataDtos = this.buildLegendDataListForSkjs();
        // 2.按照前端约定格式返回数据
        Map<String, Object> result = new HashMap<>();
        //2.1 图列数据构造
        result.put("legendData", legendDataDtos);

        List<String> xData = new ArrayList<>();
        // 2.2 Y轴数据构造 定义5个图列 再查询各自数据
        List<String> oneSetYData = new ArrayList<>();
        List<String> cylinderYData = new ArrayList<>();
        List<String> pipelineYData = new ArrayList<>();
        List<String> companyYData = new ArrayList<>();
        List<String> userYData = new ArrayList<>();
        // 多线程处理
        Map<String, SkjsCountItemDto> countItemMap = regionModels.parallelStream().map(r -> {
            String companyCode = r.get("companyCode").toString();
            String orgCode = r.get("orgCode").toString();
            SkjsCountItemDto countItemDto = new SkjsCountItemDto();
            countItemDto.setRegionCode(companyCode);
            if (!ValidationUtil.isEmpty(orgCode)) {
                Map<String, Object> data = new HashMap<>();
                // 查询各自统计数据作为Y轴数据
                // 0. 气瓶数量统计
                long cylinderNum = stCommonService.staticsCenterMapCountDataForCylinder(data, orgCode, false, false, false);
                countItemDto.setCylinder(String.valueOf(cylinderNum));
                // 1. 设备数量统计
                long oneSetNum = stCommonService.staticsCenterMapCountDataForEquip(data, cylinderNum, orgCode, true, false, false);
                countItemDto.setOneSet(String.valueOf(oneSetNum));
                // 2. 压力管道长度统计
                countItemDto.setPipeline(stCommonService.staticsCenterMapCountDataForPipeline(data, orgCode, true, false));
                // 3. 单位数量统计。按监管单位统计，检验检测机构只挂在省局下，所以各地市及区县等监管机构不统计检验检测机构企业数量
                this.staticsCompanyForSkjs(countItemDto, orgCode, null);
                // 4. 人员数量统计.按监管单位统计，检验检测机构只挂在省局下，所以各地市及区县等监管机构不统计检验检测机构企业人员数量
                this.staticsUserForSkjs(countItemDto, null, orgCode);
            } else {
                countItemDto.setDefaultValues();
            }
            return countItemDto;
        }).collect(Collectors.toMap(SkjsCountItemDto::getRegionCode, Function.identity()));
        // 排序及数据构建
        regionModels.forEach(r -> {
            xData.add(r.get("companyName").toString());
            SkjsCountItemDto countItemDto = countItemMap.get(r.get("companyCode").toString());
            oneSetYData.add(countItemDto.getOneSet());
            cylinderYData.add(countItemDto.getCylinder());
            pipelineYData.add(countItemDto.getPipeline());
            companyYData.add(countItemDto.getCompany());
            userYData.add(countItemDto.getUser());
        });
        result.put("oneSet", oneSetYData);
        result.put("cylinder", cylinderYData);
        result.put("pipeline", pipelineYData);
        result.put("company", companyYData);
        result.put("user", userYData);
        result.put("xdata", xData);
        return result;
    }

    public Map<String, Object> querySkjsBySuperviseDetail(DPFilterParamDto dpFilterParamDto) {
        String orgCodeP = stCommonService.getAndSetOrgCode(dpFilterParamDto);
        Map<String, Object> parentModel = getSuperviseTreeByLoginUnitCode(orgCodeP).get(0);
        List<Map<String, Object>> childrenRegionModelList = (List<Map<String, Object>>) parentModel.get("children");
        List<RegionModelDto> regionModels = Lists.newArrayList();
        if (childrenRegionModelList != null) {
            childrenRegionModelList.forEach(r -> {
                RegionModelDto regionModel = new RegionModelDto();
                regionModel.setRegionCode(r.get("companyCode").toString());
                regionModel.setRegionName((String) r.get("companyName"));
                regionModel.setParentRegionCode((String) parentModel.get("companyCode"));
                regionModels.add(regionModel);
            });
        }
        // 如果是省局、地市局、区县局查看，则把各对应省局、地市局、区县局数据单独添加到列表中
        if (!ValidationUtil.isEmpty(RegulatoryUnitLevelEnum.getEnumByLevelCode((String) parentModel.get("level")))) {
            RegionModelDto regionModel = new RegionModelDto();
            regionModel.setRegionCode(parentModel.get("companyCode").toString());
            regionModel.setRegionName((String) parentModel.get("companyName"));
            // 设置等级字段是为了区分本级监管单位在查询时是否需要精确匹配
            regionModel.setLevel((String) parentModel.get("level"));
            regionModels.add(regionModel);
        }
        if (orgCodeP == null || regionModels.isEmpty()) {
            return this.getDefaultSkjsDetail();
        }

        Map<String, Object> result = new HashMap<>();
        // 设备上线情况
        result.put("equipOnLineInfo", this.getEquipOnLineInfo(regionModels));
        // 企业上线情况
        result.put("companyOnLineInfo", this.getCompanyOnLineInfo(regionModels));
        // 人员上线情况
        result.put("userOnLineInfo", this.getUserOnLineInfo(regionModels));
        return result;
    }
}
