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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.module.common.api.dto.DPFilterParamDto;
import com.yeejoin.amos.boot.module.common.api.dto.DPFilterParamForDetailDto;
import com.yeejoin.amos.boot.module.common.api.entity.AlertStatistics;
import com.yeejoin.amos.boot.module.common.api.enums.UnitTypeEnum;
import com.yeejoin.amos.boot.module.common.api.enums.UserPostEnum;
import com.yeejoin.amos.boot.module.statistcs.biz.utils.JsonUtils;
import com.yeejoin.amos.boot.module.statistics.api.enums.InformationManageTypeEnum;
import com.yeejoin.amos.boot.module.statistics.api.feign.TzsServiceFeignClient;
import com.yeejoin.amos.boot.module.statistics.api.mapper.AlertStatisticsMapper;
import com.yeejoin.amos.boot.module.statistics.api.mapper.ZLStatisticsMapper;
import com.yeejoin.amos.boot.module.statistics.api.vo.EquCategoryVo;
import com.yeejoin.amos.boot.module.ymt.api.dto.EquipmentCategoryDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.EquipmentCategory;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgOtherInfo;
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.EquipmentCategoryMapper;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import org.apache.commons.compress.utils.Lists;
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.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ZLDPStatisticsServiceImpl {


    private static final String EQU_STATE = "EQU_STATE";

    private final ZLStatisticsMapper screenMapper;

    private final DataDictionaryServiceImpl iDataDictionaryService;

    private final AlertStatisticsMapper alertStatisticsMapper;

    private final RestHighLevelClient restHighLevelClient;

    private final StCommonServiceImpl stCommonService;

    private final EquipmentCategoryMapper equipmentCategoryMapper;

    // 设备纳管  纳管：true 未纳管：false
    public static final String IS_INTO_MANAGEMENT = "IS_INTO_MANAGEMENT";
    // 信信息化管理情况:1-二维码；2-电子标签；99-无
    public static final String INFORMATION_SITUATION = "INFORMATION_SITUATION";

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

    @Autowired
    private TzsServiceFeignClient tzsServiceFeignClient;

    public ZLDPStatisticsServiceImpl(ZLStatisticsMapper screenMapper, DataDictionaryServiceImpl iDataDictionaryService, AlertStatisticsMapper alertStatisticsMapper, RestHighLevelClient restHighLevelClient, StCommonServiceImpl stCommonService, EquipmentCategoryMapper equipmentCategoryMapper) {
        this.screenMapper = screenMapper;
        this.iDataDictionaryService = iDataDictionaryService;
        this.alertStatisticsMapper = alertStatisticsMapper;
        this.restHighLevelClient = restHighLevelClient;
        this.stCommonService = stCommonService;
        this.equipmentCategoryMapper = equipmentCategoryMapper;
    }


    public List<Map<String, Object>> companyInfo(DPFilterParamDto screenDto) {

        List<Map<String,Object>> list = screenMapper.getCompanyInfo(screenDto);
        List<Map<String,Object>> returnList = new ArrayList<>();

        //数据处理后Map，key为企业类型+设备，value为计数
        Map<String, Integer> dataMap = new HashMap<>();
        for(Map<String,Object> map : list){
            if(null == map.get("equipCategory") || CollectionUtils.isEmpty((JSONArray) JSONArray.parse((String) map.get("equipCategory")))){
                String[] unitTypeArray = ((String) map.get("unitType")).split("#");
                for (String unitTypeName : unitTypeArray) {
                    if (dataMap.containsKey(unitTypeName + "null")) {
                        dataMap.put(unitTypeName + "null", dataMap.get(unitTypeName + "null") + 1);
                    } else {
                        dataMap.put(unitTypeName + "null", 1);
                    }
                }
            }else {
                JSONArray equipCategoryArray = (JSONArray) JSONArray.parse((String) map.get("equipCategory"));
                String[] unitTypeArray = ((String) map.get("unitType")).split("#");
                for (String unitTypeName : unitTypeArray) {
                    for (Object o : equipCategoryArray) {
                        if (dataMap.containsKey(unitTypeName + o)) {
                            dataMap.put(unitTypeName + o, dataMap.get(unitTypeName + o) + 1);
                        } else {
                            dataMap.put(unitTypeName + o, 1);
                        }
                    }
                }
            }
        }
        /**
         * 4000	起重机械
         * 3000	电梯
         * 5000	场（厂）内机动车辆
         * 1000	锅炉
         * 2000	压力容器
         * 6000	大型游乐设施（B类）
         * 9000	客运索道
         * 8000 压力管道
         */



        //充装Map
        Map<String,Object> chongzhuangMap = new HashMap<>();
        List<Map<String,Object>> chongzhuangCompanyList = new ArrayList<>();
        chongzhuangMap.put("key","chongzhuangCompany");
        chongzhuangMap.put("value","充装单位");
        //充装压力容器
        Map<String,Object> chongzhuangyalirongqiMap = new HashMap<>();
        chongzhuangyalirongqiMap.put("key","key04");
        chongzhuangyalirongqiMap.put("name","气瓶");
        chongzhuangyalirongqiMap.put("value",dataMap.getOrDefault("充装单位2000",0));
        chongzhuangCompanyList.add(chongzhuangyalirongqiMap);
        chongzhuangMap.put("data",chongzhuangCompanyList);
        //无设备类型
        Map<String,Object> chongzhuangNullMap = new HashMap<>();
        chongzhuangNullMap.put("key","key09");
        chongzhuangNullMap.put("name","无设备类型");
        chongzhuangNullMap.put("value",dataMap.getOrDefault("充装单位null",0));
        chongzhuangCompanyList.add(chongzhuangNullMap);
        chongzhuangMap.put("data",chongzhuangCompanyList);

        //安改维Map
        Map<String,Object> angaiweiMap = new HashMap<>();
        List<Map<String,Object>> angaiweiCompanyList = new ArrayList<>();
        angaiweiMap.put("key","angaiweiCompany");
        angaiweiMap.put("value","安改维单位");
        //安改维电梯
        Map<String,Object> angaiweidiantiMap = new HashMap<>();
        angaiweidiantiMap.put("key","key01");
        angaiweidiantiMap.put("name","电梯");
        angaiweidiantiMap.put("value",dataMap.getOrDefault("安装改造维修单位3000",0));
        angaiweiCompanyList.add(angaiweidiantiMap);
        //安改维锅炉
        Map<String,Object> angaiweiguoluMap = new HashMap<>();
        angaiweiguoluMap.put("key","key02");
        angaiweiguoluMap.put("name","锅炉");
        angaiweiguoluMap.put("value",dataMap.getOrDefault("安装改造维修单位1000",0));
        angaiweiCompanyList.add(angaiweiguoluMap);
        //安改维场内机动车
        Map<String,Object> angaiweijidongcheMap = new HashMap<>();
        angaiweijidongcheMap.put("key","key03");
        angaiweijidongcheMap.put("name","场内机动车");
        angaiweijidongcheMap.put("value",dataMap.getOrDefault("安装改造维修单位5000",0));
        angaiweiCompanyList.add(angaiweijidongcheMap);
        //安改维压力管道
        Map<String,Object> angaiweiyaliguandaoMap = new HashMap<>();
        angaiweiyaliguandaoMap.put("key","key05");
        angaiweiyaliguandaoMap.put("name","压力管道");
        angaiweiyaliguandaoMap.put("value",dataMap.getOrDefault("安装改造维修单位8000",0));
        angaiweiCompanyList.add(angaiweiyaliguandaoMap);
        //安改维起重机械
        Map<String,Object> angaiweiqizhongjixieMap = new HashMap<>();
        angaiweiqizhongjixieMap.put("key","key06");
        angaiweiqizhongjixieMap.put("name","起重机械");
        angaiweiqizhongjixieMap.put("value",dataMap.getOrDefault("安装改造维修单位4000",0));
        angaiweiCompanyList.add(angaiweiqizhongjixieMap);
        //安改维游乐设施
        Map<String,Object> angaiweiyoulesheshiMap = new HashMap<>();
        angaiweiyoulesheshiMap.put("key","key07");
        angaiweiyoulesheshiMap.put("name","大型游乐设施");
        angaiweiyoulesheshiMap.put("value",dataMap.getOrDefault("安装改造维修单位6000",0));
        angaiweiCompanyList.add(angaiweiyoulesheshiMap);
        //安改维客运索道
        Map<String,Object> angaiweikeyunsuodaoMap = new HashMap<>();
        angaiweikeyunsuodaoMap.put("key","key08");
        angaiweikeyunsuodaoMap.put("name","客运索道");
        angaiweikeyunsuodaoMap.put("value",dataMap.getOrDefault("安装改造维修单位9000",0));
        angaiweiCompanyList.add(angaiweikeyunsuodaoMap);
        angaiweiMap.put("data",angaiweiCompanyList);
        //无设备类型
        Map<String,Object> angaiweiNullMap = new HashMap<>();
        angaiweiNullMap.put("key","key09");
        angaiweiNullMap.put("name","无设备类型");
        angaiweiNullMap.put("value",dataMap.getOrDefault("安装改造维修单位null",0));
        angaiweiCompanyList.add(angaiweiNullMap);
        angaiweiMap.put("data",angaiweiCompanyList);

        //设计Map
        Map<String,Object> shejiMap = new HashMap<>();
        List<Map<String,Object>> shejiCompanyList = new ArrayList<>();
        shejiMap.put("key","shejiCompany");
        shejiMap.put("value","设计单位");
        //设计压力容器
        Map<String,Object> shejiyalirongqiMap = new HashMap<>();
        shejiyalirongqiMap.put("key","key04");
        shejiyalirongqiMap.put("name","压力容器");
        shejiyalirongqiMap.put("value",dataMap.getOrDefault("设计单位2000",0));
        shejiCompanyList.add(shejiyalirongqiMap);
        //设计压力管道
        Map<String,Object> shejiyaliguandaoMap = new HashMap<>();
        shejiyaliguandaoMap.put("key","key05");
        shejiyaliguandaoMap.put("name","压力管道");
        shejiyaliguandaoMap.put("value",dataMap.getOrDefault("设计单位8000",0));
        shejiCompanyList.add(shejiyaliguandaoMap);
        shejiMap.put("data",shejiCompanyList);
        //无设备类型
        Map<String,Object> shejiNullMap = new HashMap<>();
        shejiNullMap.put("key","key09");
        shejiNullMap.put("name","无设备类型");
        shejiNullMap.put("value",dataMap.getOrDefault("设计单位null",0));
        shejiCompanyList.add(shejiNullMap);
        shejiMap.put("data",shejiCompanyList);

        //制造Map
        Map<String,Object> zhizaoMap = new HashMap<>();
        List<Map<String,Object>> zhizaoCompanyList = new ArrayList<>();
        zhizaoMap.put("key","zhizaoCompany");
        zhizaoMap.put("value","制造单位");
        //制造电梯
        Map<String,Object> zhizaodiantiMap = new HashMap<>();
        zhizaodiantiMap.put("key","key01");
        zhizaodiantiMap.put("name","电梯");
        zhizaodiantiMap.put("value",dataMap.getOrDefault("制造单位3000",0));
        zhizaoCompanyList.add(zhizaodiantiMap);
        //制造锅炉
        Map<String,Object> zhizaoguoluMap = new HashMap<>();
        zhizaoguoluMap.put("key","key02");
        zhizaoguoluMap.put("name","锅炉");
        zhizaoguoluMap.put("value",dataMap.getOrDefault("制造单位1000",0));
        zhizaoCompanyList.add(zhizaoguoluMap);
        //制造场内机动车
        Map<String,Object> zhizaojidongcheMap = new HashMap<>();
        zhizaojidongcheMap.put("key","key03");
        zhizaojidongcheMap.put("name","场内机动车");
        zhizaojidongcheMap.put("value",dataMap.getOrDefault("制造单位5000",0));
        zhizaoCompanyList.add(zhizaojidongcheMap);
        //制造压力容器
        Map<String,Object> zhizaoyalirongqiMap = new HashMap<>();
        zhizaoyalirongqiMap.put("key","key04");
        zhizaoyalirongqiMap.put("name","压力容器");
        zhizaoyalirongqiMap.put("value",dataMap.getOrDefault("制造单位2000",0));
        zhizaoCompanyList.add(zhizaoyalirongqiMap);
        //制造起重机械
        Map<String,Object> zhizaoqizhongjixieMap = new HashMap<>();
        zhizaoqizhongjixieMap.put("key","key06");
        zhizaoqizhongjixieMap.put("name","起重机械");
        zhizaoqizhongjixieMap.put("value",dataMap.getOrDefault("制造单位4000",0));
        zhizaoCompanyList.add(zhizaoqizhongjixieMap);
        //制造游乐设施
        Map<String,Object> zhizaoyoulesheshiMap = new HashMap<>();
        zhizaoyoulesheshiMap.put("key","key07");
        zhizaoyoulesheshiMap.put("name","大型游乐设施");
        zhizaoyoulesheshiMap.put("value",dataMap.getOrDefault("制造单位6000",0));
        zhizaoCompanyList.add(zhizaoyoulesheshiMap);
        //制造客运索道
        Map<String,Object> zhizaokeyunsuodaoMap = new HashMap<>();
        zhizaokeyunsuodaoMap.put("key","key08");
        zhizaokeyunsuodaoMap.put("name","客运索道");
        zhizaokeyunsuodaoMap.put("value",dataMap.getOrDefault("制造单位9000",0));
        zhizaoCompanyList.add(zhizaokeyunsuodaoMap);
        zhizaoMap.put("data",zhizaoCompanyList);
        //无设备类型
        Map<String,Object> zhizaoNullMap = new HashMap<>();
        zhizaoNullMap.put("key","key09");
        zhizaoNullMap.put("name","无设备类型");
        zhizaoNullMap.put("value",dataMap.getOrDefault("制造单位null",0));
        zhizaoCompanyList.add(zhizaoNullMap);
        zhizaoMap.put("data",zhizaoCompanyList);

        //使用Map
        Map<String,Object> shiyongMap = new HashMap<>();
        List<Map<String,Object>> shiyongCompanyList = new ArrayList<>();
        shiyongMap.put("key","shiyongCompany");
        shiyongMap.put("value","使用单位");
        //使用电梯
        Map<String,Object> shiyongdiantiMap = new HashMap<>();
        shiyongdiantiMap.put("key","key01");
        shiyongdiantiMap.put("name","电梯");
        shiyongdiantiMap.put("value",dataMap.getOrDefault("使用单位3000",0));
        shiyongCompanyList.add(shiyongdiantiMap);
        //使用锅炉
        Map<String,Object> shiyongguoluMap = new HashMap<>();
        shiyongguoluMap.put("key","key02");
        shiyongguoluMap.put("name","锅炉");
        shiyongguoluMap.put("value",dataMap.getOrDefault("使用单位1000",0));
        shiyongCompanyList.add(shiyongguoluMap);
        //使用锅炉
        Map<String,Object> shiyongjidongcheMap = new HashMap<>();
        shiyongjidongcheMap.put("key","key03");
        shiyongjidongcheMap.put("name","场内机动车");
        shiyongjidongcheMap.put("value",dataMap.getOrDefault("使用单位5000",0));
        shiyongCompanyList.add(shiyongjidongcheMap);
        //使用压力容器
        Map<String,Object> shiyongyalirongqiMap = new HashMap<>();
        shiyongyalirongqiMap.put("key","key04");
        shiyongyalirongqiMap.put("name","压力容器");
        shiyongyalirongqiMap.put("value",dataMap.getOrDefault("使用单位2000",0));
        shiyongCompanyList.add(shiyongyalirongqiMap);
        //使用压力管道
        Map<String,Object> shiyongyaliguandaoMap = new HashMap<>();
        shiyongyaliguandaoMap.put("key","key05");
        shiyongyaliguandaoMap.put("name","压力管道");
        shiyongyaliguandaoMap.put("value",dataMap.getOrDefault("使用单位8000",0));
        shiyongCompanyList.add(shiyongyaliguandaoMap);
        //使用起重机械
        Map<String,Object> shiyongqizhongjixieMap = new HashMap<>();
        shiyongqizhongjixieMap.put("key","key06");
        shiyongqizhongjixieMap.put("name","起重机械");
        shiyongqizhongjixieMap.put("value",dataMap.getOrDefault("使用单位4000",0));
        shiyongCompanyList.add(shiyongqizhongjixieMap);
        //使用游乐设施
        Map<String,Object> shiyongyoulesheshiMap = new HashMap<>();
        shiyongyoulesheshiMap.put("key","key07");
        shiyongyoulesheshiMap.put("name","大型游乐设施");
        shiyongyoulesheshiMap.put("value",dataMap.getOrDefault("使用单位6000",0));
        shiyongCompanyList.add(shiyongyoulesheshiMap);
        //使用客运索道
        Map<String,Object> shiyongkeyunsuodaoMap = new HashMap<>();
        shiyongkeyunsuodaoMap.put("key","key08");
        shiyongkeyunsuodaoMap.put("name","客运索道");
        shiyongkeyunsuodaoMap.put("value",dataMap.getOrDefault("使用单位9000",0));
        shiyongCompanyList.add(shiyongkeyunsuodaoMap);
        shiyongMap.put("data",shiyongCompanyList);
        //无设备类型
        Map<String,Object> shiyongNullMap = new HashMap<>();
        shiyongNullMap.put("key","key09");
        shiyongNullMap.put("name","无设备类型");
        shiyongNullMap.put("value",dataMap.getOrDefault("使用单位null",0));
        shiyongCompanyList.add(shiyongNullMap);
        shiyongMap.put("data",shiyongCompanyList);

        returnList.add(zhizaoMap);
        returnList.add(angaiweiMap);
        returnList.add(shiyongMap);
        returnList.add(shejiMap);
        returnList.add(chongzhuangMap);

        return returnList;
    }

    public List<Map<String, Object>> testOrg(DPFilterParamDto screenDto) {
        List<Map<String, Object>> list = screenMapper.testOrg(screenDto);
        List<Map<String, Object>> returnList = new ArrayList<>();
        Map<String, Object> dataMap = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            dataMap.put((String) list.get(i).get("agencyType"), list.get(i).get("count"));
        }
        /**
         * 1	甲类检验机构A1级
         * 2	甲类检验机构A2级
         * 4	甲类检验机构B1级
         * 5	甲类检验机构B2级
         * 6	乙类检验机构
         * 7	丙类检验机构
         * 8	检测机构
         * 9	综合检验机构甲类（旧规）
         * 10	综合检验机构乙类（旧规）
         * 11	综合检验机构丙类（旧规）
         * 12	自检机构（旧规）
         * 13	气瓶检验机构（旧规）
         * 14	无损检测机构（旧规）
         */
        Map<String, Object> newMap = new HashMap<>();
        newMap.put("key", "new");
        newMap.put("name", "新分类");
        List<Map<String, Object>> newList = new ArrayList<>();
        Map<String, Object> newMap1 = new HashMap<>();
        newMap1.put("name", "甲类检验机构A1级");
        newMap1.put("value", dataMap.getOrDefault("1", 0));
        newList.add(newMap1);
        Map<String, Object> newMap2 = new HashMap<>();
        newMap2.put("name", "甲类检验机构A2级");
        newMap2.put("value", dataMap.getOrDefault("2", 0));
        newList.add(newMap2);
        Map<String, Object> newMap3 = new HashMap<>();
        newMap3.put("name", "甲类检验机构B1级");
        newMap3.put("value", dataMap.getOrDefault("4", 0));
        newList.add(newMap3);
        Map<String, Object> newMap4 = new HashMap<>();
        newMap4.put("name", "甲类检验机构B2级");
        newMap4.put("value", dataMap.getOrDefault("5", 0));
        newList.add(newMap4);
        Map<String, Object> newMap5 = new HashMap<>();
        newMap5.put("name", "乙类检验机构");
        newMap5.put("value", dataMap.getOrDefault("6", 0));
        newList.add(newMap5);
        Map<String, Object> newMap6 = new HashMap<>();
        newMap6.put("name", "丙类检验机构");
        newMap6.put("value", dataMap.getOrDefault("7", 0));
        newList.add(newMap6);
        Map<String, Object> newMap7 = new HashMap<>();
        newMap7.put("name", "检测机构");
        newMap7.put("value", dataMap.getOrDefault("8", 0));
        newList.add(newMap7);
        newMap.put("data", newList);
        Map<String, Object> oldMap = new HashMap<>();
        oldMap.put("key", "old");
        oldMap.put("name", "旧分类");
        List<Map<String, Object>> oldList = new ArrayList<>();
        Map<String, Object> oldMap1 = new HashMap<>();
        oldMap1.put("name", "综合检验机构甲类（旧规）");
        oldMap1.put("value", dataMap.getOrDefault("9", 0));
        oldList.add(oldMap1);
        Map<String, Object> oldMap2 = new HashMap<>();
        oldMap2.put("name", "综合检验机构乙类（旧规）");
        oldMap2.put("value", dataMap.getOrDefault("10", 0));
        oldList.add(oldMap2);
        Map<String, Object> oldMap3 = new HashMap<>();
        oldMap3.put("name", "综合检验机构丙类（旧规）");
        oldMap3.put("value", dataMap.getOrDefault("11", 0));
        oldList.add(oldMap3);
        Map<String, Object> oldMap4 = new HashMap<>();
        oldMap4.put("name", "自检机构（旧规）");
        oldMap4.put("value", dataMap.getOrDefault("12", 0));
        oldList.add(oldMap4);
        Map<String, Object> oldMap5 = new HashMap<>();
        oldMap5.put("name", "气瓶检验机构（旧规）");
        oldMap5.put("value", dataMap.getOrDefault("13", 0));
        oldList.add(oldMap5);
        Map<String, Object> oldMap6 = new HashMap<>();
        oldMap6.put("name", "无损检测机构（旧规）");
        oldMap6.put("value", dataMap.getOrDefault("14", 0));
        oldList.add(oldMap6);
        oldMap.put("data", oldList);
        returnList.add(newMap);
        returnList.add(oldMap);
        return returnList;
    }


    public Map<String, Object> userCount(DPFilterParamDto screenDto) {
        List<Map<String, String>> list = screenMapper.userCount(screenDto);
        Map<String, Integer> dataMap = new HashMap<>();
        for (Map<String, String> map : list) {
            String[] split = map.get("unitType").split("#");
            for (int i = 0; i < split.length; i++) {
                if (dataMap.containsKey(split[i])) {
                    dataMap.put(split[i], dataMap.get(split[i]) + 1);
                } else {
                    dataMap.put(split[i], 1);
                }
            }
        }
        List<String> xlist = Arrays.asList("制造单位", "安改维单位", "使用单位", "设计单位", "充装单位");
        List<Integer> ylist = new ArrayList();
        xlist.forEach(x -> {
            ylist.add(dataMap.getOrDefault(x, 0));
        });
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("xdata", xlist);
        returnMap.put("ydata", ylist);
        return returnMap;
    }


    public Map<String, Object> supervisorCount(DPFilterParamDto screenDto) {
        List<Map<String, Object>> list = screenMapper.supervisorCount(screenDto);
        Map<String, Integer> dataMap = new HashMap<>();
        for (Map<String, Object> map : list) {
            dataMap.put((String) map.get("industrySupervisor"), Integer.valueOf(map.get("count").toString()));
        }

        List<DataDictionary> dataDictionaryList = iDataDictionaryService.getByType("HYZGBM");
        List<String> xlist = dataDictionaryList.stream().map(DataDictionary::getName).collect(Collectors.toList());
        List<Object> ylist = new ArrayList();
        dataDictionaryList.forEach(x -> {
            ylist.add(dataMap.getOrDefault(x.getCode(), 0));
        });
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("xdata", xlist);
        returnMap.put("ydata", ylist);
        return returnMap;
    }


    public List<Map<String, Object>> equipmentInformCount(DPFilterParamDto screenDto) {
        //设置模糊搜索
        String orgCode = stCommonService.getAndSetOrgCode(screenDto.getCityCode());
        List<Map<String, Object>> returnList = new ArrayList<>();
        List<DataDictionary> dataDictionaryList = iDataDictionaryService.getByType("ADDRESS");
        if(orgCode == null){
            this.setEquipmentInformCountDefaultData(returnList, dataDictionaryList);
            return returnList;
        }
        SearchRequest searchRequest = new SearchRequest("idx_biz_view_jg_all");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        boolMust.must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(orgCode) + "*"));
        // 且8大类，目的去掉脏数据
        boolMust.must(QueryBuilders.termsQuery("EQU_LIST_CODE",StCommonServiceImpl.getEquipmentCategory().stream().map(EquipmentCategoryDto::getCode).collect(Collectors.toList())));
        // 只统计已纳管设备
        boolMust.must(QueryBuilders.termQuery("IS_INTO_MANAGEMENT", Boolean.TRUE));
        // 有监管码
        boolMust.must(QueryBuilders.existsQuery("SUPERVISORY_CODE"));
        boolMust.mustNot(QueryBuilders.termQuery("SUPERVISORY_CODE","null"));
        searchSourceBuilder.query(boolMust);
        searchSourceBuilder.aggregation(AggregationBuilders.terms("count_by_use_site_code").field("USE_SITE_CODE").size(500));
        searchRequest.source(searchSourceBuilder);
        Map<String, Integer> dataMap = new HashMap<>();

        try {
            // 执行搜索请求
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            // 获取所有聚合结果
            Aggregations aggregations = searchResponse.getAggregations();
            Terms termsResult = aggregations.get("count_by_use_site_code");

            for (Terms.Bucket bucket : termsResult.getBuckets()) {
                String category = bucket.getKeyAsString(); // 或者使用 bucket.getKey() 对于非字符串类型
                long docCount = bucket.getDocCount();
                dataMap.put(category, (int) docCount);
            }
            dataDictionaryList.forEach(x -> {
                Map<String, Object> map = new HashMap<>();
                map.put("name", x.getName());
                map.put("value", dataMap.getOrDefault(x.getCode(), 0));
                dataMap.remove(x.getCode());
                returnList.add(map);
            });
            Map<String, Object> otherMap = new HashMap<>();
            otherMap.put("name", "其他");
            otherMap.put("value", dataMap.values().stream().mapToLong(e -> e).sum());
            returnList.add(otherMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnList;
    }

    private void setEquipmentInformCountDefaultData(List<Map<String, Object>> returnList, List<DataDictionary> dataDictionaryList) {
        dataDictionaryList.forEach(x -> {
            Map<String, Object> map = new HashMap<>();
            map.put("name", x.getName());
            map.put("value", 0);
            returnList.add(map);
        });
    }

    public Map<String,Object> userCountNew(DPFilterParamDto screenDto) {
        List<String> unitTypeList = UnitTypeEnum.getNameListByType(screenDto.getCompanyType());
        List<Map<String, String>> userListMap = UserPostEnum.getEnumListByType(screenDto.getCompanyType());
        List<Map<String, String>> list = screenMapper.userCountNew(screenDto, unitTypeList);
        Map<String, Integer> dataMap = new HashMap<>();
        for (Map<String, String> map : list) {
            JSONArray jsonArray = JSONArray.parseArray(map.get("new_post"));
            if (!ValidationUtil.isEmpty(jsonArray)) {
                for(int j = 0; j < jsonArray.size(); j++){
                    dataMap.put(jsonArray.getString(j), dataMap.getOrDefault(jsonArray.getString(j), 0) + 1);
                }
            }
        }
        Map<String, Object> returnMap = new HashMap<>();
        List<Object> xdata = new ArrayList<>();
        List<Object> ydata = new ArrayList<>();
        for (Map<String, String> map : userListMap) {
            xdata.add(map.get("name"));
            ydata.add(dataMap.getOrDefault(map.get("code"), 0));
        }
        returnMap.put("xdata", xdata);
        returnMap.put("ydata", ydata);
        return returnMap;
    }

    public JSONArray statisticInfoByRegionAndDate(DPFilterParamDto params) {
        LocalDate today = LocalDate.now();
        LocalDate startDate;
        LocalDate endDate;
        String regionCode = params.getCityCode();
        String orgCode = stCommonService.getAndSetOrgCode(regionCode);
        if (ObjectUtils.isEmpty(params.getBeginDate()) || ObjectUtils.isEmpty(params.getBeginDate())) {
            startDate = today.minusDays(6);
            endDate = today;
        } else {
            startDate = LocalDate.parse(params.getBeginDate());
            endDate = LocalDate.parse(params.getEndDate());
        }
        params.setBeginDate(startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        params.setEndDate(endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        AlertStatistics statistics = alertStatisticsMapper.statisticsInfoByRegionAndDate(regionCode, startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")), endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        JSONArray jsonArray = new JSONArray();
        if (!ObjectUtils.isEmpty(statistics)) {
            JSONObject jsonObject0 = new JSONObject();
            jsonObject0.put("key", "dtkr");
            jsonObject0.put("value", ValidationUtil.isEmpty(statistics.getTrappedPeople()) ? 0 : statistics.getTrappedPeople());
            jsonObject0.put("name", "电梯困人");

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("key", "slts");
            jsonObject1.put("value", ValidationUtil.isEmpty(statistics.getComplaint()) ? 0 : statistics.getComplaint());
            jsonObject1.put("name", "受理投诉");

            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("key", "gzbx");
            jsonObject2.put("value", ValidationUtil.isEmpty(statistics.getBreakdownRescue()) ? 0 : statistics.getBreakdownRescue());
            jsonObject2.put("name", "故障维修");

            JSONObject jsonObject3 = new JSONObject();
            DPFilterParamDto filterParamDto = new DPFilterParamDto();
            filterParamDto.setBeginDate(startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            filterParamDto.setEndDate(endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            Long rescuedPersonNum = alertStatisticsMapper.countRescuedPersonNum(orgCode, filterParamDto);
            jsonObject3.put("key", "jjbkck");
            jsonObject3.put("value", ValidationUtil.isEmpty(rescuedPersonNum) ? 0 : rescuedPersonNum);
            jsonObject3.put("name", "解救被困乘客");

            JSONObject jsonObject4 = new JSONObject();
            jsonObject4.put("key", "30fzdd");
            jsonObject4.put("value", ValidationUtil.isEmpty(statistics.getWithinThirtyRescue()) ? 0 : statistics.getWithinThirtyRescue());
            jsonObject4.put("name", "30分钟内到达");

            JSONObject jsonObject5 = new JSONObject();
            jsonObject5.put("key", "pjjysj");
            jsonObject5.put("value", ValidationUtil.isEmpty(statistics.getAvgTime()) ? 0 : this.roundString(statistics.getAvgTime()));
            jsonObject5.put("name", "平均救援时间");

            JSONObject jsonObject6 = new JSONObject();
            jsonObject6.put("key", "jycq");
            jsonObject6.put("value", orgCode == null ? 0L: this.getQuestionNumber("检验超期",params, orgCode));
            jsonObject6.put("name", "检验超期");

            JSONObject jsonObject7 = new JSONObject();
            jsonObject7.put("key", "jybhg");
            jsonObject7.put("value", orgCode == null ? 0L: this.getQuestionNumber("检验不合格",params, orgCode));
            jsonObject7.put("name", "检验不合格");

            JSONObject jsonObject8 = new JSONObject();
            jsonObject8.put("key", "wbcq");
            jsonObject8.put("value", orgCode == null ? 0L: this.getQuestionNumber("维保超期",params, orgCode));
            jsonObject8.put("name", "维保超期");

            JSONObject jsonObject9 = new JSONObject();
            jsonObject9.put("key", "csjsynx");
            jsonObject9.put("value", orgCode == null ? 0L: this.getQuestionNumber("超设计使用年限",params, orgCode));
            jsonObject9.put("name", "超设计使用年限");

            JSONObject jsonObject10 = new JSONObject();
            jsonObject10.put("key", "zzlq");
            jsonObject10.put("value", orgCode == null ? 0L: stCommonService.getYellowStatusCompany(params).getLongValue());
            jsonObject10.put("name", "许可临期");

            JSONObject jsonObject11 = new JSONObject();
            jsonObject11.put("key", "zzcq");
            jsonObject11.put("value", orgCode == null ? 0L: stCommonService.getRedStatusCompany(params).getLongValue());
            jsonObject11.put("name", "许可超期");

            jsonArray.add(jsonObject0);
            jsonArray.add(jsonObject1);
            jsonArray.add(jsonObject2);
            jsonArray.add(jsonObject3);
            jsonArray.add(jsonObject4);
            jsonArray.add(jsonObject5);
            jsonArray.add(jsonObject6);
            jsonArray.add(jsonObject7);
            jsonArray.add(jsonObject8);
            jsonArray.add(jsonObject9);
            jsonArray.add(jsonObject10);
            jsonArray.add(jsonObject11);

        }
        return jsonArray;
    }

    private Long roundString(String avgTime) {
        return Math.round(new Double(avgTime));
    }

    private Long getQuestionNumber(String problemType, DPFilterParamDto params, String orgCode) {
        return alertStatisticsMapper.countProblemByTypeDateAndOrgCode(problemType, params, orgCode);
    }

    public Map<String, Object> getEquipManagementRateStatistics(DPFilterParamForDetailDto paramDto) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> legendData = new ArrayList<>();
        legendData.add(createLegend("设备总数", "equipTotal", "bar", "个"));
        legendData.add(createLegend("纳管率", "claimRate", "line", "%"));

        List<RegionModel> regionList = stCommonService.setRegionIfRootParentAndNoAccessIf3Level("610000");
        // 获取区域名称并过滤
        List<String> xData = regionList.stream()
                .map(RegionModel::getRegionName)
                .filter(regionName -> !"西咸新区".equals(regionName))
                .collect(Collectors.toList());
        // 过滤掉 "西咸新区" 并获取 yData
        List<CountDto> yData = getYDataForQZ(regionList, paramDto);
        result.put("legendData", legendData);
        result.put("xdata", xData);
        result.put("equipTotal", yData.stream().map(CountDto::getLongValue).collect(Collectors.toList()));
        result.put("claimRate", yData.stream().map(CountDto::getStrValue).collect(Collectors.toList()));
        return result;
    }

    private List<CountDto> getYDataForQZ(List<RegionModel> regionList, DPFilterParamForDetailDto paramDto) {
        DecimalFormat decimalFormat = new DecimalFormat("0.0000");
        return regionList.parallelStream()
                .filter(region -> !"西咸新区".equals(region.getRegionName()))
                .map(region -> {
                    String orgCode = stCommonService.getAndSetOrgCode(region.getRegionCode().toString());
                    Long equipIsManageNum = staticsCenterMapCountDataForEquipIsManage(orgCode, paramDto);
                    Long equipTotal = getEquipTotalForCode(paramDto.getTreeValue(), region.getRegionCode().toString());
                    CountDto dto = new CountDto();
                    dto.setLongValue(equipTotal);
                    dto.setStrValue(calculateClaimRate(equipTotal, equipIsManageNum, decimalFormat));
                    return dto;
                }).collect(Collectors.toList());
    }

    private Long getEquipTotalForCode(String treeValue, String regionCode) {
        if (treeValue == null) {
            return screenMapper.getEquipTotal(regionCode);
        }
        switch (treeValue) {
            case "1000":
                return screenMapper.getEquListTotal("boiler", regionCode); // 锅炉
            case "2000":
                return screenMapper.getEquListTotal("vessel", regionCode); // 压力容器
            case "3000":
                return screenMapper.getEquListTotal("elevator", regionCode); // 电梯
            case "4000":
                return screenMapper.getEquListTotal("lifting", regionCode); // 起重机械
            case "5000":
                return screenMapper.getEquListTotal("vehicle", regionCode); // 厂车
            case "6000":
                return screenMapper.getEquListTotal("rides", regionCode); // 游乐设施
            case "8000":
                return screenMapper.getEquListTotal("pipeline", regionCode); // 压力管道
            case "9000":
                return screenMapper.getEquListTotal("ropeway", regionCode); // 客运索道
            case "2300":
                return screenMapper.getEquListTotal("cylinder", regionCode); // 气瓶
            default:
                return screenMapper.getEquipTotal(regionCode);
        }
    }

    private Map<String, Object> createLegend(String value, String dataKey, String chartType, String unit) {
        return new HashMap<String, Object>() {{
            put("value", value);
            put("dataKey", dataKey);
            put("chartType", chartType);
            put("unit", unit);
        }};
    }

    private String calculateClaimRate(Long equipTotal, Long equipIsManageNum, DecimalFormat decimalFormat) {
        if (equipIsManageNum == 0 || equipTotal == 0) {
            return "0";
        }
        BigDecimal equipTotalDecimal = BigDecimal.valueOf(equipTotal);
        BigDecimal equipIsManageDecimal = BigDecimal.valueOf(equipIsManageNum);
        BigDecimal claimRate = equipIsManageDecimal.divide(equipTotalDecimal, 4, RoundingMode.HALF_UP);

        return decimalFormat.format(claimRate);
    }

    private Long staticsCenterMapCountDataForEquipIsManage(String orgCode, DPFilterParamForDetailDto paramDto) {
        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.termQuery("IS_INTO_MANAGEMENT", true));

        if (StringUtils.isNotEmpty(paramDto.getTreeValue())) {
            if ("2300".equals(paramDto.getTreeValue())){
                boolMust.must(QueryBuilders.termQuery("EQU_CATEGORY_CODE", QueryParser.escape(paramDto.getTreeValue().toLowerCase())));
            }else {
                boolMust.must(QueryBuilders.termQuery("EQU_LIST_CODE", QueryParser.escape(paramDto.getTreeValue().toLowerCase())));
            }
        }
        // 且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 Page<JSONObject> queryByKeys(JSONObject map) {
        if (!ValidationUtil.isEmpty(map.get(EQU_STATE))) {
            map.put(EQU_STATE, EquimentEnum.getCode.get(map.get(EQU_STATE).toString()).toString());
        }

        Page<JSONObject> result = new Page<>(map.getInteger("number"), map.getInteger("size"));
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();

        // SEQUENCE_NBR
        if (!ObjectUtils.isEmpty(map.getString("SEQUENCE_NBR"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("SEQUENCE_NBR"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("SEQUENCE_NBR", "*" + test + "*"));
            boolMust.must(meBuilder);
        }

        if (!ObjectUtils.isEmpty(map.getString("cityCode"))) {
            String orgCode = stCommonService.getAndSetOrgCode((String) map.get("cityCode"));
            boolMust.must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(orgCode) + "*"));
        }

        if (!ObjectUtils.isEmpty(map.getString("superviseUnitName"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("superviseUnitName"));
            query.must(QueryBuilders.matchPhraseQuery("ORG_BRANCH_NAME", "*" + test + "*"));
            boolMust.must(query);
        }

        if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_NAME"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_UNIT_NAME"));
            query.must(QueryBuilders.matchPhraseQuery("USE_UNIT_NAME", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("USE_UNIT_CREDIT_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("USE_UNIT_CREDIT_CODE"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("USE_UNIT_CREDIT_CODE", test));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_LIST_CODE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            if ("2300".equals(map.getString("EQU_LIST_CODE"))) {
                meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_CATEGORY_CODE", QueryParser.escape(map.getString("EQU_LIST_CODE"))));
            } else {
                meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_LIST_CODE", QueryParser.escape(map.getString("EQU_LIST_CODE"))));
            }
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_LIST"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_LIST"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_LIST", "*" + test + "*"));
            boolMust.must(meBuilder);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_CATEGORY"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("EQU_CATEGORY"));
            meBuilder.must(QueryBuilders.matchPhraseQuery("EQU_CATEGORY", "*" + test + "*"));
            boolMust.must(meBuilder);

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

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

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

        if (!ObjectUtils.isEmpty(map.getString("ADDRESS"))) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getString("ADDRESS"));
            query.must(QueryBuilders.matchPhraseQuery("ADDRESS", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(map.getString("EQU_STATE"))) {
            BoolQueryBuilder meBuilder = QueryBuilders.boolQuery();
            String test = QueryParser.escape(map.getLong("EQU_STATE").toString());
            meBuilder.must(QueryBuilders.matchQuery("EQU_STATE", test));
            boolMust.must(meBuilder);
        }

        //默认查询已纳管
        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{
            //已赋码
            boolMust.must(QueryBuilders.existsQuery("SUPERVISORY_CODE"));
            boolMust.mustNot(QueryBuilders.termQuery("SUPERVISORY_CODE","null"));
            //状态为已认领
            String[] status = {"草稿","已拒领","待认领"};
            boolMust.mustNot(QueryBuilders.termsQuery("STATUS",Arrays.asList(status)));
        }

        builder.query(boolMust);
        builder.sort("REC_DATE", SortOrder.DESC);
        builder.from((map.getInteger("number") - 1) * map.getInteger("size"));
        builder.size(map.getInteger("size"));
        request.source(builder);
        List<JSONObject> list = new LinkedList<>();
        long totle = 0;
        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(EQU_STATE))) {
                    Integer integer = Integer.valueOf(dto2.get(EQU_STATE).toString());
                    String status = EquimentEnum.getName.get(integer);
                    dto2.put(EQU_STATE, status);
                }
                if (!ValidationUtil.isEmpty(dto2.get(INFORMATION_SITUATION))) {
                    String informationSituation = InformationManageTypeEnum.getName(dto2.get(INFORMATION_SITUATION).toString());
                    dto2.put(INFORMATION_SITUATION, informationSituation);
                }
                list.add(dto2);
            }
            totle = response.getInternalResponse().hits().getTotalHits().value;
            result.setRecords(list);
            result.setTotal(totle);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public Page<JSONObject> viewEquipPage(DPFilterParamForDetailDto paramDto) {
        Page<JSONObject> result = new Page<>(paramDto.getCurrent(), paramDto.getSize());
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();

        if (!ObjectUtils.isEmpty(paramDto.getCityCode())) {
            String orgCode = stCommonService.getAndSetOrgCode(paramDto.getCityCode());
            boolMust.must(QueryBuilders.wildcardQuery("ORG_BRANCH_CODE.keyword", QueryParser.escape(orgCode) + "*"));
        }

        if (!ObjectUtils.isEmpty(paramDto.getSuperviseUnitName())) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(paramDto.getSuperviseUnitName());
            query.must(QueryBuilders.matchPhraseQuery("ORG_BRANCH_NAME", "*" + test + "*"));
            boolMust.must(query);
        }

        if (!ObjectUtils.isEmpty(paramDto.getCompanyName())) {
            BoolQueryBuilder query = QueryBuilders.boolQuery();
            String test = QueryParser.escape(paramDto.getCompanyName());
            query.must(QueryBuilders.matchPhraseQuery("USE_UNIT_NAME", "*" + test + "*"));
            boolMust.must(query);
        }
        if (!ObjectUtils.isEmpty(paramDto.getTreeValue())) {
            if ("2300".equals(paramDto.getTreeValue())) {
                if (paramDto.getEquCategoryCode() != null) {
                    // treeValue 为 "2300" 且 equCategoryCode 非空时
                    BoolQueryBuilder query = QueryBuilders.boolQuery();
                    String escapedValue = QueryParser.escape(paramDto.getEquCategoryCode());
                    query.must(QueryBuilders.matchPhraseQuery("EQU_DEFINE_CODE", escapedValue));
                    boolMust.must(query);
                } else {
                    // treeValue 为 "2300" 且 equCategoryCode 为空时
                    BoolQueryBuilder query = QueryBuilders.boolQuery();
                    String escapedValue = QueryParser.escape(paramDto.getTreeValue());
                    query.must(QueryBuilders.matchPhraseQuery("EQU_CATEGORY_CODE", escapedValue));
                    boolMust.must(query);
                }
            } else {
                // treeValue 不为 "2300" 时
                BoolQueryBuilder query = QueryBuilders.boolQuery();
                String escapedValue = QueryParser.escape(paramDto.getTreeValue());
                query.must(QueryBuilders.matchPhraseQuery("EQU_LIST_CODE", escapedValue));

                // 处理 equCategoryCode 为空的情况
                if (paramDto.getEquCategoryCode() != null) {
                    escapedValue = QueryParser.escape(paramDto.getEquCategoryCode());
                    query.must(QueryBuilders.matchPhraseQuery("EQU_CATEGORY_CODE", escapedValue));
                }
                boolMust.must(query);
            }
        }

        BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
        String param = QueryParser.escape("true");
        pBuilder.must(QueryBuilders.matchQuery(IS_INTO_MANAGEMENT, param));
        boolMust.must(pBuilder);
        boolMust.must(QueryBuilders.termsQuery("EQU_LIST_CODE",
                StCommonServiceImpl.getEquipmentCategory().stream().map(EquipmentCategoryDto::getCode).collect(Collectors.toList())));

        builder.query(boolMust);
        builder.sort("REC_DATE", SortOrder.DESC);
        builder.from((paramDto.getCurrent() - 1) * paramDto.getSize());
        builder.size(paramDto.getSize());
        request.source(builder);
        List<JSONObject> list = new LinkedList<>();
        long totle = 0;
        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(EQU_STATE))) {
                    Integer integer = Integer.valueOf(dto2.get(EQU_STATE).toString());
                    String status = EquimentEnum.getName.get(integer);
                    dto2.put(EQU_STATE, status);
                }
                list.add(dto2);
            }
            totle = response.getInternalResponse().hits().getTotalHits().value;
            result.setRecords(list);
            result.setTotal(totle);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public List<EquCategoryVo> getEquCategoryList(String equListCode) {
        EquipmentCategory equList = equipmentCategoryMapper.selectOne(new LambdaQueryWrapper<EquipmentCategory>().eq(EquipmentCategory::getCode, equListCode));
        if (ValidationUtil.isEmpty(equList)) {
            return Lists.newArrayList();
        }
        List<EquipmentCategory> equipmentCategoryList = equipmentCategoryMapper.selectList(new LambdaQueryWrapper<EquipmentCategory>().eq(EquipmentCategory::getParentId, equList.getId()));
        if (ValidationUtil.isEmpty(equipmentCategoryList)) {
            return Lists.newArrayList();
        }
        return equipmentCategoryList.stream()
                .map(dto -> new EquCategoryVo(dto.getName(), dto.getCode(), null))
                .collect(Collectors.toList());
    }

    public List<Map<String, Object>> equipTree(String type) {
        List<Map<String, Object>> menus = new ArrayList<>();
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(equipCategory);
        List<Map<String, Object>> mapList;
        if (ValidationUtil.isEmpty(type)) {
            mapList = resourceJson.get(EquipmentClassifityEnum.BDLS.getCode());
        } else {
            if ("QTBF".equals(type)) {
                type = "superviseBusiness";
            }
            mapList = resourceJson.get(type) == null ? resourceJson.get(EquipmentClassifityEnum.BDLS.getCode()) : resourceJson.get(type);
        }
        for (Map map : mapList) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("instanceName", map.get("name"));
            resultMap.put("instanceId", map.get("code"));
            resultMap.put("image", map.get("imageUrl"));
            menus.add(resultMap);
        }
        return menus;
    }

    public Page<Map<String,Object>> getPersonPage(DPFilterParamDto paramDto, Page page) {
        String regionCode = paramDto.getCityCode();
        String orgCode = stCommonService.getAndSetOrgCode(regionCode);
        List<String> unitTypeList = UnitTypeEnum.getNameListByType(paramDto.getCompanyType());
        Page<Map<String, Object>> result = screenMapper.getPersonPage(page, paramDto, orgCode, unitTypeList);
        return result;
    }


    public List<Map<String, String>> getPersonType(String companyType) {
        return UserPostEnum.getEnumListByType(companyType);
    }

    public Object updateEquipInfo() {
        IPage<IdxBizJgOtherInfo> idxBizJgOtherInfoPage = new Page<>();
        Integer count = screenMapper.count();
        Integer times = 0;
        if (ValidationUtil.isEmpty(count) && count != 0) {
            times = count / 500;
            int last = count % 500;
            if (last > 0) {
                times++;
            }
        } else if (count == 0) {
            return "不存在需要更新信息化字段的数据";
        }
        for(int i = 0; i <= times ;  i ++  ) {
            idxBizJgOtherInfoPage.setCurrent(i);
            idxBizJgOtherInfoPage.setSize(500);
            idxBizJgOtherInfoPage = screenMapper.getEquipInfoPage(idxBizJgOtherInfoPage);
            Map<String,Map<String,Object>> updataMap = new HashMap<>();
            if (idxBizJgOtherInfoPage.getTotal() > 0) {
                idxBizJgOtherInfoPage.getRecords().forEach(e->{
                    Map<String,Object> map = new HashMap<>();
                    map.put(INFORMATION_SITUATION, e.getInformationSituation());
                    updataMap.put(e.getRecord(), map);
                });
            }
            tzsServiceFeignClient.commonUpdateEsDataByIds(updataMap);
        }
        return "信息化字段更新完成";
    }

    public List<Map<String, Object>> getInformationManageType() {
        return InformationManageTypeEnum.getEnumList();
    }
}
