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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.QRCodeUtil;
import com.yeejoin.amos.boot.module.jxiop.api.Enum.ElectricQuantity;
import com.yeejoin.amos.boot.module.jxiop.api.Enum.KGName;
import com.yeejoin.amos.boot.module.jxiop.api.dto.IndexDto;
import com.yeejoin.amos.boot.module.jxiop.api.dto.TreeDto;
import com.yeejoin.amos.boot.module.jxiop.api.entity.Region;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.MonitorFanIndicatorMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.RegionMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESEquipments;
import com.yeejoin.amos.boot.module.jxiop.biz.constants.CommonConstans;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.*;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.*;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.AlarmEventMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.SwitchPictureMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.SystemEnumMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.TemporaryDataMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.service.IMonitorFanIndicator;
import com.yeejoin.amos.component.robot.BadRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.Collator;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

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

/**
 * @description:
 * @author: tw
 * @createDate: 2023/7/3
 */
@Service
@EnableScheduling
@Slf4j
public class MonitorFanIndicatorImpl implements IMonitorFanIndicator {
    private final static List<String> fanStatesList = Arrays.asList("报警状态", "停机状态", "故障状态", "待机状态", "维护状态", "正常发电状态");

    @Autowired
    private MonitorFanIndicatorMapper monitorFanIndicatorregionMapper;

    @Autowired
    private StationBasicMapper stationBasicMapper;

    @Autowired
    private RegionMapper regionMapper;

//    @Autowired
//    InfluxDButils influxDButils;

    @Autowired
    SystemEnumMapper systemEnumMapper;

    @Autowired
    SwitchPictureMapper switchPictureMapper;

    @Autowired
    SjglZsjZsbtzServiceImpl sjglZsjZsbtzServiceImpl;

    @Autowired
    TpriDmpDatabookServiceImpl tpriDmpDatabookServiceImpl;

    @Autowired
    TemporaryDataMapper temporaryDataMapper;

    @Autowired
    AlarmEventMapper alarmEventMapper;

    @Autowired
    AlarmEventServiceImpl alarmEventService;

    @Autowired
    TemporaryDataServiceImpl temporaryDataService;

    @Autowired
    EmqKeeper emqKeeper;

    @Autowired
    CommonServiceImpl commonServiceImpl;
    @Value("classpath:/json/fanlocation.json")
    private Resource fanlocation;

    @Value("${pictureUrl}")
    String pictureUrl;

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

    private List<Map> list;



    public ResultsData getNationWideInfo(int current, int size, String gateway, String equipmentNumber) {
        String table = gateway;
        Map<String, List<String>> queryCodntion = new HashMap<>();
        queryCodntion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(gateway));
        queryCodntion.put("isAlarm.keyword", Arrays.asList("1"));
        List<ESEquipments> alldata = commonServiceImpl.getListDataByCondtionsAndLike(queryCodntion, null, ESEquipments.class, null);
        List<ESEquipments> waringData = alldata.stream().filter(esEquipments -> !esEquipments.getValue().equals("0.0") && !esEquipments.getValue().equals(esEquipments.getValueLabel())).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(equipmentNumber)) {
            waringData = waringData.stream().filter(esEquipments -> esEquipments.getEquipmentNumber().equals(equipmentNumber)).collect(Collectors.toList());
        }
        if (CollectionUtils.isNotEmpty(waringData)) {
            Integer newSize = waringData.size() >= size ? size : waringData.size();
            waringData = waringData.stream().sorted(Comparator.comparing(ESEquipments::getCreatedTime).reversed()).collect(Collectors.toList()).subList(((current - 1) * newSize), (current * newSize));
        }
        //对于查询到的告警信息进行按照时间顺序进行排序
        DataGridMock DataGridMock = new DataGridMock(current, !waringData.isEmpty() ? waringData.size() : 0, false, current, waringData);
        ColModel colModelequipmentNumber = new ColModel("equipmentNumber", "equipmentNumber", "设备", "设备", "dataGrid", "equipmentNumber");
        ColModel colModelvalueLabel = new ColModel("valueLabel", "valueLabel", "事件描述", "事件描述", "dataGrid", "valueLabel");
        ColModel colModelcreatedTime = new ColModel("createdTime", "createdTime", "发生时间", "发生时间", "dataGrid", "createdTime");
        ColModel colModelvalue = new ColModel("value", "value", "告警值", "告警值", "dataGrid", "value");
        List<ColModel> listColModel = new ArrayList<>();
        listColModel.add(colModelequipmentNumber);
        listColModel.add(colModelvalueLabel);
        listColModel.add(colModelcreatedTime);
        listColModel.add(colModelvalue);
        ResultsData resultsData = new ResultsData(DataGridMock, listColModel);
        return resultsData;
    }

//    @Override
//    public ResultsData getLsNationWideInfo(int current, int size, String stationBasicId, String equipmentNumber) {
//        StationBasic stationBasic = stationBasicMapper.selectById(stationBasicId);
//        String gateway = stationBasic.getFanGatewayId();
//        String table = gateway;
//        StringBuffer querysql = new StringBuffer("SELECT createdTime ,gatewayId,address,valueLabel,equipmentSpecificName,value FROM iot_data_%s  WHERE isAlarm='1'  and value!=valueLabel  and value!='0.0'  and  gatewayId=  %s ORDER BY time  desc   LIMIT %d OFFSET %d  ");
//        StringBuffer querysqlcount = new StringBuffer("SELECT count(value) FROM iot_data_%s  WHERE isAlarm='1'   and value!='0.0' and value!=valueLabel  and  gatewayId=   %s ");
//        if (StringUtils.isNotEmpty(equipmentNumber)) {
//            String date = " '%s' and equipmentSpecificName=~/.*%s风机.*/ ";
//            gateway = String.format(date, gateway, equipmentNumber);
//        } else {
//            gateway = String.format("'%s'", gateway);
//        }
//        String querysqln = String.format(querysql.toString(), table, gateway, size,  (current - 1) *size);
//        String querysqlcountn = String.format(querysqlcount.toString(), table, gateway);
//        //每个分机的指标数据
//        List<IndexDto> list = influxDButils.getListData(querysqln, IndexDto.class);
//        List<IndexDto> list1 = influxDButils.getListData(querysqlcountn, IndexDto.class);
//        //对于查询到的告警信息进行按照时间顺序进行排序
//        ArrayList<IndexDto> lisSort= (ArrayList<IndexDto>) list.stream().sorted(Comparator.comparing(IndexDto::getTimeString,Comparator.comparingLong(Long::parseLong)).reversed()).collect(Collectors.toList());
//        //构建平台数据
//        DataGridMock DataGridMock = new DataGridMock(current, !list1.isEmpty() ? list1.get(0).getCount() : 0, false, current, lisSort);
//        ColModel colModelequipmentNumber = new ColModel("equipmentNumber", "equipmentSpecificName", "风机号", "风机号", "dataGrid", "equipmentNumber");
//        ColModel colModelvalueLabel = new ColModel("valueLabel", "valueLabel", "事件描述", "事件描述", "dataGrid", "valueLabel");
//        ColModel colModelcreatedTime = new ColModel("createdTime", "createdTime", "发生时间", "发生时间", "dataGrid", "createdTime");
//        ColModel colModelvalue = new ColModel("value", "value", "告警值", "告警值", "dataGrid", "value");
//        List<ColModel> listColModel = new ArrayList<>();
//        listColModel.add(colModelequipmentNumber);
//        listColModel.add(colModelvalueLabel);
//        listColModel.add(colModelcreatedTime);
//        listColModel.add(colModelvalue);
//        ResultsData resultsData = new ResultsData(DataGridMock, listColModel);
//        return resultsData;
//    }


//    public Page<IndexDto> historyNationwideByPage(int current, int size, String stationBasicId) {
//        StationBasic stationBasic = stationBasicMapper.selectById(stationBasicId);
//        String gateway = stationBasic.getFanGatewayId();
//        String table = gateway;
//        StringBuffer querysql = new StringBuffer("SELECT createdTime ,gatewayId,address,valueLabel,equipmentSpecificName,value FROM iot_data_%s  WHERE isAlarm='1'  and value!=valueLabel  and value!='0.0'  and  gatewayId=  %s ORDER BY time  desc   LIMIT %d OFFSET %d  ");
//        StringBuffer querysqlcount = new StringBuffer("SELECT count(value) FROM iot_data_%s  WHERE isAlarm='1'   and value!='0.0' and value!=valueLabel  and  gatewayId=   %s ");
//        gateway = String.format("'%s'", gateway);
//        String querysqln = String.format(querysql.toString(), table, gateway, size,  (current - 1) *size);
//        String querysqlcountn = String.format(querysqlcount.toString(), table, gateway);
//        //每个分机的指标数据
//        List<IndexDto> list = influxDButils.getListData(querysqln, IndexDto.class);
//        List<IndexDto> list1 = influxDButils.getListData(querysqlcountn, IndexDto.class);
//        //对于查询到的告警信息进行按照时间顺序进行排序
//        ArrayList<IndexDto> lisSort= (ArrayList<IndexDto>) list.stream().sorted(Comparator.comparing(IndexDto::getTimeString,Comparator.comparingLong(Long::parseLong)).reversed()).collect(Collectors.toList());
//        Page<IndexDto> indexDtoPage = new Page<>();
//        indexDtoPage.setTotal(list1.size());
//        indexDtoPage.setRecords(lisSort);
//        indexDtoPage.setCurrent(current);
//        indexDtoPage.setSize(size);
//        return indexDtoPage;
//    }



//    public IPage<IndexDto> getFanIdxInfoByPage(String equipNum, String stationId, String frontModule, int current, int size, String systemType) {
//        StationBasic stationBasic = getOneByStationNumber(stationId);
//        Page<IndexDto> page = new Page<>(current, size);
//        String sql = "";
//        if (StringUtils.isNotEmpty(systemType)) {
//            sql = String.format("SELECT equipmentIndexName, value, frontModule,systemType, unit FROM \"indicators_%s\" WHERE equipmentNumber = '%s' and frontModule =~/%s/ and systemType =~/%s/ ", stationBasic.getFanGatewayId(), equipNum, frontModule, systemType);
//        } else {
//            sql = String.format("SELECT equipmentIndexName, value, frontModule,systemType, unit FROM \"indicators_%s\" WHERE equipmentNumber = '%s' and frontModule =~/%s/", stationBasic.getFanGatewayId(), equipNum, frontModule);
//        }
//        List<IndexDto> influxDBList = influxDButils.getListData(sql, IndexDto.class);
//        influxDBList.stream().forEach(e->{
//            Double f = Double.valueOf(e.getValue());
//            e.setValue(String.format("%.2f",f));
//
//        });
//
//        Collator instance = Collator.getInstance(Locale.CHINA);
//        Collections.sort(influxDBList,(e1,e2)->{
//            return instance.compare(e1.getSystemType(),e2.getSystemType());
//        });
//        List<IndexDto> collect = influxDBList.stream()
//                .skip((long) (current - 1) * size)
//                .limit(size)
//                .collect(Collectors.toList());
//        page.setTotal(influxDBList.size());
//        page.setRecords(collect);
//        return page;
//    }

    public TreeDto getTreeInfo(String sequenceNbr) {
        StationBasic stationBasic = stationBasicMapper.selectById(sequenceNbr);
        List<Integer> integers = JSON.parseArray(stationBasic.getBelongArea(), Integer.class);
        if (CollectionUtils.isEmpty(integers)) {
            throw new BadRequest("所属地区不能为空");
        }
        LambdaQueryWrapper<Region> regionLambda = new LambdaQueryWrapper<>();
        regionLambda.eq(Region::getRegionCode, integers.get(0));
        Region region = regionMapper.selectOne(regionLambda);
        TreeDto treeDto = new TreeDto();
        treeDto.setCode(String.valueOf(region.getRegionCode()));
        treeDto.setName(region.getRegionName());
        treeDto.setId(String.valueOf(region.getSequenceNbr()));
        treeDto.setParentCode("0");
        treeDto.setIsOnClick(0);
        List<TreeDto> stationListByRegionCode = stationBasicMapper.getStationListByRegionCode(String.valueOf(region.getRegionCode()));


        TreeDto fdzTreeDto = new TreeDto();
        fdzTreeDto.setName("风电站");
        fdzTreeDto.setCode("FDZ");
        fdzTreeDto.setParentCode(String.valueOf(region.getRegionCode()));
        fdzTreeDto.setIsOnClick(0);
        List<TreeDto> fdz = stationListByRegionCode.stream().filter(t -> t.getParentCode().contains("FDZ")&&t.getParentCode().length()<4).collect(Collectors.toList());
        fdzTreeDto.setChildren(fdz);

        TreeDto gfzTreeDto = new TreeDto();
        gfzTreeDto.setName("光伏站");
        gfzTreeDto.setCode("GFZ");
        gfzTreeDto.setParentCode(String.valueOf(region.getRegionCode()));
        gfzTreeDto.setIsOnClick(0);
        List<TreeDto> gfz = stationListByRegionCode.stream().filter(t -> t.getParentCode().contains("GFDZ")).collect(Collectors.toList());
        gfzTreeDto.setChildren(gfz);
        List<TreeDto> treeDtos = Arrays.asList(fdzTreeDto, gfzTreeDto);
        treeDto.setChildren(treeDtos);
        return treeDto;
    }

    /**
     * 根据网关与指标获取指标的平均值
     *
     * @param gateway
     * @param indicator
     * @return
     */
//    public Object getIndicatoralueAvage(String gateway, String indicator) {
//        return monitorFanIndicatorregionMapper.getIndicatoralueAvage(gateway, indicator);
//    }


    /**
     * 根据网关与指标获取指标的总值
     *
     * @param gateway
     * @param indicator
     * @return
     */
//    public Object getIndicatoralueTotal(String gateway, String indicator) {
//        return monitorFanIndicatorregionMapper.getIndicatoralueTotal(gateway, indicator);
//    }


    public StationBasic getOneByStationNumber(String stationId) {
        return stationBasicMapper.selectById(stationId);
    }

  //  public List<IndexDto> getFanStatusList(String stationId) {
        //        StationBasic stationBasic = getOneByStationNumber(stationId);
//        String sql = String.format("SELECT equipmentNumber, equipmentIndexName as state FROM \"indicators_%s\" WHERE equipmentIndexName =~/^报警状态|停机状态|故障状态|待机状态|维护状态|正常发电状态$/ and value = 'true'", stationBasic.getFanGatewayId());
//        List<IndexDto> influxDBList = influxDButils.getListData(sql, IndexDto.class);
//        Map<String, String> collect = influxDBList.stream().collect(Collectors.toMap(IndexDto::getEquipmentNumber, IndexDto::getState, (item1, item2) -> item1));
//        String sqlEquipNumList = String.format("SELECT (DISTINCT equipmentNumber) as equipmentNumber FROM \"indicators_%s\"", stationBasic.getFanGatewayId());
//        List<IndexDto> equipNumList = influxDButils.getListData(sqlEquipNumList, IndexDto.class);
//        List<Map<String, String>> fanConfigPower = monitorFanIndicatorregionMapper.getFanConfigPower(stationBasic.getFanGatewayId(), null);
//        String equipmentSpecificNames = fanConfigPower.stream().map(t -> t.get("equipmentSpecificName")).collect(Collectors.joining("|"));
//        String powerSql = String.format("SELECT equipmentNumber, value FROM \"indicators_%s\" WHERE equipmentSpecificName =~/^%s$/ and value = '9.0'", stationBasic.getFanGatewayId(), equipmentSpecificNames);
//        List<IndexDto> powerNum = influxDButils.getListData(powerSql, IndexDto.class);
//        List<String> powList = powerNum.stream().map(IndexDto::getEquipmentNumber).collect(Collectors.toList());
//        Date currentDayStartTime = DateUtils.dateAddMinutes(new Date(), -15);
//        String time = "";
//        try {
//            time = DateUtils.dateFormat(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//
//        String timeSql = String.format("select distinct equipmentNumber from \"indicators_%s\" where time >= '%s'", stationBasic.getFanGatewayId(), time);
//        List<IndexDto> timeSqlList = influxDButils.getListData(timeSql, IndexDto.class);
//        List<String> timeList = timeSqlList.stream().map(IndexDto::getEquipmentNumber).collect(Collectors.toList());
//        equipNumList.forEach(item -> {
//            item.setState(collect.get(item.getEquipmentNumber()));
//            if (!collect.containsKey(item.getEquipmentNumber())) {
//                item.setState("正常运行");
//            } else if (powList.contains(item.getEquipmentNumber())) {
//                item.setState("限功率");
//            } else if (!timeList.contains(item.getEquipmentNumber())) {
//                item.setState("通讯中断");
//            }
//        });
//        StationBasic stationBasic = getOneByStationNumber(stationId);
//        String sql = String.format("SELECT equipmentNumber, equipmentIndexName as state FROM \"indicators_%s\" WHERE (equipmentIndexName =~/^发电状态|报警状态|停机状态|故障状态|待机状态|维护状态|正常发电状态$/ and value = 'true') or (equipmentIndexName ='实时故障22' and value='9')", stationBasic.getFanGatewayId());
//        List<IndexDto> influxDBList = influxDButils.getListData(sql, IndexDto.class);
//        String sqlEquipNumList = String.format("SELECT (DISTINCT equipmentNumber) as equipmentNumber FROM \"indicators_%s\"", stationBasic.getFanGatewayId());
//        List<IndexDto> equipNumList = influxDButils.getListData(sqlEquipNumList, IndexDto.class);
//        Map<String, String> collect = influxDBList.stream().collect(Collectors.toMap(IndexDto::getEquipmentNumber, IndexDto::getState, (item1, item2) -> item1));
//        equipNumList.forEach(item -> {
//            String status = ObjectUtils.isEmpty(CommonConstans.fanStatus.get(collect.get(item.getEquipmentNumber()))) ? "通讯中断" : CommonConstans.fanStatus.get(collect.get(item.getEquipmentNumber()));
//            item.setState(status);
//        });
//        return equipNumList;
//    }

    public List<ESEquipments> getFanStatusListEs(String stationId) {
        StationBasic stationBasic = getOneByStationNumber(stationId);
        Map<String, List<String>> queryCondtion = new HashMap<>();
        queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("发电状态", "报警状态", "停机状态", "故障状态", "待机状态", "维护状态", "正常发电状态", "实时故障22"));
        queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
        List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
        Map<String, List<String>> queryCondtion1 = new HashMap<>();
        queryCondtion1.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("报警状态"));
        queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
        List<ESEquipments> equipNumList = commonServiceImpl.getListDataByCondtions(queryCondtion1, null, ESEquipments.class);
        Map<String, String> collect = result.stream().collect(Collectors.toMap(ESEquipments::getEquipmentNumber, ESEquipments::getEquipmentIndexName, (item1, item2) -> item1));
        equipNumList.forEach(item -> {
            String status = ObjectUtils.isEmpty(CommonConstans.fanStatus.get(collect.get(item.getEquipmentNumber()))) ? "通讯中断" : CommonConstans.fanStatus.get(collect.get(item.getEquipmentNumber()));
            item.setAddress(status);
        });
        return equipNumList;

    }


//    public List<IndexDto> getFanStatusListOptimize(String stationId) {
//        StationBasic stationBasic = getOneByStationNumber(stationId);
//        String sqlAll = String.format("SELECT * FROM \"indicators_%s\"",stationBasic.getFanGatewayId());
//        List<IndexDto> indexDtoList = influxDButils.getListData(sqlAll,IndexDto.class);
////        String sql = String.format("SELECT equipmentNumber, equipmentIndexName as state FROM \"indicators_%s\" WHERE equipmentIndexName =~/^报警状态|停机状态|故障状态|待机状态|维护状态|正常发电状态$/ and value = 'true'", stationBasic.getFanGatewayId());
////        List<IndexDto> influxDBList = influxDButils.getListData(sql, IndexDto.class);
////        Map<String, String> collect = influxDBList.stream().collect(Collectors.toMap(IndexDto::getEquipmentNumber, IndexDto::getState, (item1, item2) -> item1));
////        String sqlEquipNumList = String.format("SELECT (DISTINCT equipmentNumber) as equipmentNumber FROM \"indicators_%s\"", stationBasic.getFanGatewayId());
////        List<IndexDto> equipNumList = influxDButils.getListData(sqlEquipNumList, IndexDto.class);
////        String equipmentSpecificNames = fanConfigPower.stream().map(t -> t.get("equipmentSpecificName")).collect(Collectors.joining("|"));
//
//        List<IndexDto> influxDBList = indexDtoList.stream().
//                filter(indexDto -> fanStatesList.contains(indexDto.getEquipmentIndexName())&&indexDto.getValue().equals("true")).collect(Collectors.toList());
//        Map<String, String> collect = influxDBList.stream().collect(Collectors.toMap(IndexDto::getEquipmentNumber, IndexDto::getState, (item1, item2) -> item1));
//        List<IndexDto> equipNumList=indexDtoList.stream().filter(indexDto -> !ObjectUtils.isEmpty(indexDto.getEquipmentNumber())).collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(IndexDto::getEquipmentNumber))),ArrayList::new));
//        List<Map<String, String>> fanConfigPower = monitorFanIndicatorregionMapper.getFanConfigPower(stationBasic.getFanGatewayId(), null);
//        List<String > equipmentSpecificNames=fanConfigPower.stream().map(t -> t.get("equipmentSpecificName")).collect(Collectors.toList());
////        String powerSql = String.format("SELECT equipmentNumber, value FROM \"indicators_%s\" WHERE equipmentSpecificName =~/^%s$/ and value = '9.0'", stationBasic.getFanGatewayId(), equipmentSpecificNames);
////        List<IndexDto> powerNum = influxDButils.getListData(powerSql, IndexDto.class);
//        List<IndexDto> powerNum = indexDtoList.stream().filter(indexDto1 ->indexDto1.getValue().equals("9.0")&&equipmentSpecificNames.contains(indexDto1.getEquipmentSpecificName())).collect(Collectors.toList());
//        List<String> powList = powerNum.stream().map(IndexDto::getEquipmentNumber).collect(Collectors.toList());
//        Date currentDayStartTime = DateUtils.dateAddMinutes(new Date(), -15);
//        String time = "";
//        try {
//            time  = DateUtils.dateFormat(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        String timeSql = String.format("select distinct equipmentNumber from \"indicators_%s\" where time >= '%s'", stationBasic.getFanGatewayId(), time);
//        List<IndexDto> timeSqlList = influxDButils.getListData(timeSql, IndexDto.class);
//        List<String> timeList = timeSqlList.stream().map(IndexDto::getEquipmentNumber).collect(Collectors.toList());
//        equipNumList.forEach(item -> {
//            item.setState(collect.get(item.getEquipmentNumber()));
//            if (!collect.containsKey(item.getEquipmentNumber())) {
//                item.setState("正常运行");
//            } else if (powList.contains(item.getEquipmentNumber())) {
//                item.setState("限功率");
//            } else if (!timeList.contains(item.getEquipmentNumber())) {
//                item.setState("通讯中断");
//            }
//        });
//
//        return equipNumList;
//    }
 //   public List<IndexDto> getFanStatusStatistics(String stationId) {
//        StationBasic stationBasic = getOneByStationNumber(stationId);
//        String sql = String.format("SELECT equipmentNumber, equipmentIndexName as state FROM \"indicators_%s\" WHERE equipmentIndexName =~/^报警状态|停机状态|故障状态|待机状态|维护状态|正常发电状态$/ and value = 'true'", stationBasic.getFanGatewayId());
//        List<IndexDto> influxDBList = influxDButils.getListData(sql, IndexDto.class);
//        Map<String, String> collect = influxDBList.stream().collect(Collectors.toMap(IndexDto::getEquipmentNumber, IndexDto::getState, (item1, item2) -> item1));
//        String sqlEquipNumList = String.format("SELECT (DISTINCT equipmentNumber) as equipmentNumber FROM \"indicators_%s\"", stationBasic.getFanGatewayId());
//        List<IndexDto> equipNumList = influxDButils.getListData(sqlEquipNumList, IndexDto.class);
//        List<Map<String, String>> fanConfigPower = monitorFanIndicatorregionMapper.getFanConfigPower(stationBasic.getFanGatewayId(), null);
//        String equipmentSpecificNames = fanConfigPower.stream().map(t -> t.get("equipmentSpecificName")).collect(Collectors.joining("|"));
//        String powerSql = String.format("SELECT equipmentNumber, value FROM \"indicators_%s\" WHERE equipmentSpecificName =~/^%s$/ and value = '9.0'", stationBasic.getFanGatewayId(), equipmentSpecificNames);
//        List<IndexDto> powerNum = influxDButils.getListData(powerSql, IndexDto.class);
//        List<String> powList = powerNum.stream().map(IndexDto::getEquipmentNumber).collect(Collectors.toList());
//        Date currentDayStartTime = DateUtils.dateAddMinutes(new Date(), -15);
//        String time = "";
//        try {
//            time = DateUtils.dateFormat(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        String timeSql = String.format("select distinct equipmentNumber from \"indicators_%s\" where time >= '%s'", stationBasic.getFanGatewayId(), time);
//        List<IndexDto> timeSqlList = influxDButils.getListData(timeSql, IndexDto.class);
//        List<String> timeList = timeSqlList.stream().map(IndexDto::getEquipmentNumber).collect(Collectors.toList());
//        equipNumList.forEach(item -> {
//            item.setState(collect.get(item.getEquipmentNumber()));
//            if (!collect.containsKey(item.getEquipmentNumber())) {
//                item.setState("正常运行");
//            } else if (powList.contains(item.getEquipmentNumber())) {
//                item.setState("限功率");
//            } else if (!timeList.contains(item.getEquipmentNumber())) {
//                item.setState("通讯中断");
//            }
//        });
//        List<IndexDto> equipNumList = getFanStatusList(stationId);
//        Map<String, Long> countMap = equipNumList.stream().collect(Collectors.groupingBy(IndexDto::getState, Collectors.counting()));
//        List<IndexDto> resultList = new ArrayList<>();
//        List<String> list = Arrays.asList("正常运行", "报警运行", "停机状态", "故障状态", "限功率", "待机状态", "维护状态", "通讯中断");
//        HashMap<String, String> colorMap = new HashMap<>();
//        colorMap.put("正常运行", "#00aa00");
//        colorMap.put("报警运行", "#ffc400");
//        colorMap.put("停机状态", "#0055ff");
//        colorMap.put("故障状态", "#00aaff");
//        colorMap.put("限功率", "#a3f5aa");
//        colorMap.put("待机状态", "#ff0000");
//        colorMap.put("维护状态", "#ff00ff");
//        colorMap.put("通讯中断", "#7d8e95");
//        list.forEach(item -> {
//            IndexDto indexDto = new IndexDto();
//            indexDto.setCountString(countMap.containsKey(item) ? String.valueOf(countMap.get(item)) : "0");
//            indexDto.setEquipmentIndexName(item);
//            indexDto.setColor(colorMap.get(item));
//            resultList.add(indexDto);
//        });
//        return resultList;
//    }

    public IndexDto getFanBasicInfoByEquipNum(String equipNum, String stationId) {
//        IndexDto indexDto = new IndexDto();
//        StationBasic stationBasic = getOneByStationNumber(stationId);
//        String sql = String.format("SELECT equipmentNumber, equipmentSpecificName, equipmentIndexName  FROM \"indicators_%s\" WHERE equipmentNumber = '%s' and equipmentIndexName =~/^报警状态|停机状态|故障状态|待机状态|维护状态|正常发电状态$/ and value = 'true' order by time desc limit 1", stationBasic.getFanGatewayId(), equipNum);
//        List<IndexDto> influxDBList = influxDButils.getListData(sql, IndexDto.class);
//        if (CollectionUtils.isNotEmpty(influxDBList)) {
//            String equipmentSpecificName = influxDBList.get(0).getEquipmentSpecificName();
//            influxDBList.get(0).setEquipmentSpecificName(equipmentSpecificName.substring(0, equipmentSpecificName.indexOf("#")));
//            String s = StringUtils.substringAfterLast(equipmentSpecificName, "#");
//            influxDBList.get(0).setFanName(s);
//            indexDto = influxDBList.get(0);
//        } else {
//            List<Map<String, String>> fanConfigPower = monitorFanIndicatorregionMapper.getFanConfigPower(stationBasic.getFanGatewayId(), equipNum);
//            if (CollectionUtils.isEmpty(fanConfigPower)) {
//                throw new BadRequest("fan_config_power表数据未维护该风机");
//            }
//            String equipmentSpecificName = fanConfigPower.get(0).get("equipmentSpecificName");
//            String substring = equipmentSpecificName.substring(0, equipmentSpecificName.indexOf("#"));
//            indexDto.setEquipmentSpecificName(substring);
//            indexDto.setFanName(StringUtils.substringAfterLast(equipmentSpecificName, "#"));
//            indexDto.setEquipmentIndexName("正常运行");
//            String equipmentSpecificNames = fanConfigPower.stream().map(t -> t.get("equipmentSpecificName")).collect(Collectors.joining("|"));
//            String powerSql = String.format("SELECT equipmentNumber, value FROM \"indicators_%s\" WHERE equipmentSpecificName =~/^%s$/ and value = '9.0'", stationBasic.getFanGatewayId(), equipmentSpecificNames);
//            List<IndexDto> powerNum = influxDButils.getListData(powerSql, IndexDto.class);
//            List<String> powList = powerNum.stream().map(IndexDto::getEquipmentNumber).collect(Collectors.toList());
//
//            Date currentDayStartTime = DateUtils.dateAddMinutes(new Date(), -15);
//            String time = "";
//            try {
//                time  = DateUtils.dateFormat(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            String timeSql = String.format("select distinct equipmentNumber from \"indicators_%s\" where time >= '%s'", stationBasic.getFanGatewayId(), time);
//            List<IndexDto> timeSqlList = influxDButils.getListData(timeSql, IndexDto.class);
//            List<String> timeList = timeSqlList.stream().map(IndexDto::getEquipmentNumber).collect(Collectors.toList());
//
//            if (CollectionUtils.isNotEmpty(powList)) {
//                indexDto.setEquipmentIndexName("限功率");
//            }  else if (!timeList.contains(equipNum)) {
//                indexDto.setEquipmentIndexName("通讯中断");
//            }
//        }
//        indexDto.setEquipmentNumber(equipNum);
//        return indexDto;
        String json = null;
        try {
            json = IOUtils.toString(fanlocation.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONArray jsonArray = JSONObject.parseArray(json);
        JSONObject jsonObject = (JSONObject) jsonArray.get(Integer.valueOf(equipNum) - 1);
        IndexDto indexDto = new IndexDto();
        indexDto.setLongitude(String.valueOf(jsonObject.get("longitude")));
        indexDto.setLatitude(String.valueOf(jsonObject.get("latitude")));
        StationBasic stationBasic = getOneByStationNumber(stationId);
        List<ESEquipments> fanStatusList = getFanStatusListEs(stationId);
        String fanStatus = fanStatusList.stream().filter(esEquipments -> esEquipments.getEquipmentNumber().equals(equipNum)).collect(Collectors.toList()).get(0).getAddress();
        indexDto.setEquipmentIndexName(fanStatus);
        List<Map<String, String>> fanConfigPower = monitorFanIndicatorregionMapper.getFanConfigPower(stationBasic.getFanGatewayId(), equipNum);
        if (CollectionUtils.isEmpty(fanConfigPower)) {
            throw new BadRequest("fan_config_power表数据未维护该风机");
        }
        String equipmentSpecificName = fanConfigPower.get(0).get("equipmentSpecificName");
        String substring = equipmentSpecificName.substring(0, equipmentSpecificName.indexOf("#"));
        indexDto.setEquipmentSpecificName(substring);
        indexDto.setEquipmentNumber(equipNum);
        return indexDto;
    }

    /**
     *   根据风机号 场站号 模块获取实时温度
     * @param equipNum
     * @param stationId
     * @param frontModule
     * @return   风机的实时温度数据
     */
//    public HashMap<String, List<String>> getRealTimeTemperature(String equipNum, String stationId, String frontModule) {
//        HashMap<String, List<String>> realTimeTemperatureResult = new HashMap<>();
//        StationBasic stationBasic = getOneByStationNumber(stationId);
//        String sql = String.format("SELECT equipmentIndexName, value, frontModule, unit FROM \"indicators_%s\" WHERE equipmentNumber = '%s' and frontModule =~/%s/", stationBasic.getFanGatewayId(), equipNum, frontModule);
//        List<IndexDto> influxDBList = influxDButils.getListData(sql, IndexDto.class);
//        List<String> xList = new ArrayList<>();
//        List<String> yList = new ArrayList<>();
//        for (int i = 0; i < influxDBList.size(); i++) {
//            IndexDto indexDto = influxDBList.get(i);
//            if(indexDto.getEquipmentIndexName().contains("温度")){
//                xList.add(indexDto.getEquipmentIndexName());
//                yList.add(indexDto.getValue());
//            }
//        }
//        realTimeTemperatureResult.put("axisData", xList);
//        realTimeTemperatureResult.put("seriesData", yList);
//        return realTimeTemperatureResult;
//    }

//    public Integer getFanNum(String stationId) {
//        StationBasic stationBasic = getOneByStationNumber(stationId);
//        String sqlEquipNumList = String.format("SELECT (DISTINCT equipmentNumber) as equipmentNumber FROM \"indicators_%s\"", stationBasic.getFanGatewayId());
//        List<IndexDto> equipNumList = influxDButils.getListData(sqlEquipNumList, IndexDto.class);
//        return equipNumList.size();
//    }

//    public String getFanDataByType(String stationId, String equipNum, String frontModule, String typeName) {
//        StationBasic stationBasic = getOneByStationNumber(stationId);
//        String sql = String.format("SELECT equipmentIndexName, value, frontModule, unit FROM \"indicators_%s\" WHERE equipmentNumber = '%s' and frontModule =~/%s/ and equipmentIndexName = '%s'", stationBasic.getFanGatewayId(), equipNum, frontModule, typeName);
//        List<IndexDto> influxDBList = influxDButils.getListData(sql, IndexDto.class);
//        if (CollectionUtils.isNotEmpty(influxDBList) && StringUtils.isNotEmpty(influxDBList.get(0).getValue())) {
//            return influxDBList.get(0).getValue();
//        } else {
//            return "0";
//        }
//    }

//    public String getFJCount(String gatewayId){
//        String sql =  "SELECT count(DISTINCT equipmentNumber) as value FROM indicators_"+gatewayId;
//        List<IndicatorsDto> indicatorsDtoList = influxDButils.getListData(sql,IndicatorsDto.class);
//        if (indicatorsDtoList.size()>0){
//            return indicatorsDtoList.get(0).getValue();
//        }
//
//        return "0";
//    }


    public  Map<String,Object> getDetailsWindSpeedAll(String gatewayId, double installedCapacity,List<String> ids){
        Map<String, List<String>> queryCondtion = new HashMap<>();
        if (CollectionUtils.isNotEmpty(ids)) {
            queryCondtion.put(CommonConstans.QueryStringGateWayId, ids);
        }
        queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值", "南瑞光差保护_313P"));
        List<ESEquipments> indicatorsDtoList = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
        double sum = null == indicatorsDtoList?0.0: indicatorsDtoList.stream().mapToDouble(t -> Double.parseDouble(t.getValueF().toString())).sum();

        Double format = Double.parseDouble(String.format("%.2f", sum / installedCapacity));
        List<Map<String, Object>> list = temporaryDataMapper.timingTemporarysSorageData(gatewayId);
        Map<String,Object> map = new HashMap<>();
        List<String> values = new ArrayList<>();
        List<String> valueList = new ArrayList<>();
       Set<String> time = new  TreeSet<>();
        String v = list.get(0).get("value").toString();
        double min = Double.parseDouble(v);
        double max = Double.parseDouble(v);
        double mean = 0.0;
        String minTime =list.get(0).get("createdTime").toString();
        String maxTime =list.get(0).get("createdTime").toString();

        for (Map<String, Object> stringStringMap : list) {
            if (stringStringMap.get("equipmentIndexName").equals("有功功率")){
                double value = Double.parseDouble(stringStringMap.get("value").toString());
                values.add(  String.format("%.2f",value));
               if (value < min){
                   min = value;
                   minTime = stringStringMap.get("createdTime").toString();
               }else if (value > max){
                   max = value;
                   maxTime = stringStringMap.get("createdTime").toString();
               }
                time.add(stringStringMap.get("createdTime").toString());
            }else {
                valueList.add(stringStringMap.get("value").toString());
            }
        }

        for (String value : values) {
            mean += Double.parseDouble(value);
        }
        mean = Double.parseDouble(String.format("%.2f",mean/values.size()));

        List<Map<String,Object>> seriesData = new ArrayList<>();
        Map<String,Object> map3 = new HashMap<>();
        Map<String,Object> map1 = new HashMap<>();
        Map<String,Object> map2 = new HashMap<>();
        map1.put("data", values);
//        if (StringUtils.isNotEmpty(gatewayId)){
//            map2.put("data", valueList);
//            seriesData.add(map2);
//        }
        seriesData.add(map1);
        map.put("seriesData", seriesData);
        map.put("axisData",time);
        map.put("mean",mean);
        map.put("max",String.format("%.2f",max));
        map.put("min",String.format("%.2f",min));
        map.put("maxTime",maxTime);
        map.put("minTime",minTime);
        map.put("load", format);

        return map;
    }

//    public  Map<String,Object> getDetailsWindSpeed(String gatewayId,String name){
//        Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
//        String time = "";
//        try {
//            time  = DateUtils.dateFormat(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        String sql =    "SELECT DISTINCT value  FROM iot_data_"+gatewayId+"  WHERE  equipmentIndexName = '瞬时风速'  and equipmentSpecificName =~/"+name+"/and time >='"+time+"'GROUP BY time(2m)";
//        String sql1 =    "SELECT DISTINCT value  FROM iot_data_"+gatewayId+"  WHERE  equipmentIndexName = '有功功率'  and equipmentSpecificName =~/"+name+"/ and time >='"+time+"'GROUP BY time(2m)";
//        List<IndicatorsDto> indicatorsDtoList = influxDButils.getListDataAll(sql,IndicatorsDto.class);
//        List<IndicatorsDto> indicatorsDtoLists = influxDButils.getListDataAll(sql1,IndicatorsDto.class);
//        LinkedHashMap<String, String> collect =  indicatorsDtoList.stream().collect(Collectors.toMap(IndicatorsDto::getTime, IndicatorsDto::getDistinct,(key1, ky2)-> (String) key1,LinkedHashMap::new));
//        LinkedHashMap<String, String> collects = indicatorsDtoLists.stream().collect(Collectors.toMap(IndicatorsDto::getTime, IndicatorsDto::getDistinct,(key1, ky2)-> (String) key1,LinkedHashMap::new));
//        Collection<String> values = collect.values();
//        Collection<String> valuess = collects.values();
//        Set<String> keySet = collect.keySet();
//        Set<String> keySets = collects.keySet();
//        List<  Map<String,Object>> seriesData = new ArrayList<>();
//        Map<String,Object> map = new HashMap<>();
//        Map<String,Object> map1 = new HashMap<>();
//        Map<String,Object> map2 = new HashMap<>();
//        map1.put("data", values);
//        map2.put("data", valuess);
//        seriesData.add(map1);
//        seriesData.add(map2);
//        map.put("seriesData", seriesData);
//        map.put("axisData",keySet.size()>keySets.size()?keySet:keySets);
//        return map;
//    }


//    public  Map<String,Object> getDetailsWindSpeeds(String gatewayId,String name){
//        Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
//        String time = "";
//        try {
//            time  = DateUtils.dateFormat(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        String sql =    "SELECT equipmentSpecificName   FROM indicators_"+gatewayId+"  WHERE  equipmentNumber = '"+name+"' limit 1";
//        List<IndicatorsDto> indicatorsDtoList = influxDButils.getListDataAll(sql,IndicatorsDto.class);
//        name = indicatorsDtoList.get(0).getEquipmentSpecificName();
//        StringBuffer param = new StringBuffer();
//        String[] split = name.replace("#", "").split("/");
//        for (int i = 0; i < split.length; i++) {
//            param .append(" and equipmentSpecificName =~/"+split[i]+"/") ;
//        }
//
//        String sql1 =    "SELECT DISTINCT value  FROM iot_data_"+gatewayId+"  WHERE  equipmentIndexName = '有功功率'"+param+"  and time >='"+time+"'GROUP BY time(2m)";
//        List<IndicatorsDto> indicatorsDtoLists = influxDButils.getListDataAll(sql1,IndicatorsDto.class);
//        LinkedHashMap<String, String> collects = indicatorsDtoLists.stream().collect(Collectors.toMap(IndicatorsDto::getTime, IndicatorsDto::getDistinct,(key1, ky2)-> (String) key1,LinkedHashMap::new));
//        Collection<String> valuess = collects.values();
//        Set<String> keySets = collects.keySet();
//        List<  Map<String,Object>> seriesData = new ArrayList<>();
//        Map<String,Object> map = new HashMap<>();
//        Map<String,Object> map2 = new HashMap<>();
//        map2.put("data", valuess);
//        seriesData.add(map2);
//        map.put("seriesData", seriesData);
//        map.put("axisData",keySets);
//        return map;
//    }
//



   // @Scheduled(cron = "0 */5 * * * ?")
//    private void schedTaskData(){
//
//        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(BaseEntity::getIsDelete,false);
//        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
//        long timeInMillis = new Date().getTime();
//        for (StationBasic stationBasic : stationBasics) {
//            if (stationBasic.getStationType().equals("FDZ")){
//                timingTemporarysSorageData(stationBasic.getFanGatewayId(),timeInMillis);
//            }
//            if (stationBasic.getStationType().equals("JZSGFDZ")){
//                schedSolarPower(stationBasic.getBoosterGatewayId(),timeInMillis);
//            }
//        }
//    }

   // @Scheduled(cron = "0 59 23 * * ?")
//    private void deleteSchedData(){
//        QueryWrapper<TemporaryData> wrapper = new QueryWrapper<>();
//        temporaryDataMapper.delete(wrapper);
//        String sort = alarmEventMapper.getLastDataBySort(null);
//        LambdaQueryWrapper<AlarmEvent> params = new LambdaQueryWrapper<>();
//        params.notIn(AlarmEvent::getSort,sort);
//        alarmEventMapper.delete(params);
//    }


  //  @Scheduled(cron = "0 */5 * * * ?")
//    private void schedAlarmEventData(){
//        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(BaseEntity::getIsDelete,false);
//        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
//        long currentsort = new Date().getTime();
//        for (StationBasic stationBasic : stationBasics) {
//            schedAddAlarmEventData(stationBasic.getBoosterGatewayId(),stationBasic.getSequenceNbr().toString(),stationBasic.getStationName(),currentsort);
//        }
//    }



//    public  void schedAddAlarmEventData(String gatewayId,String stationId,String stationName,long currentsort){
//        String sql =  "SELECT * FROM indicators_"+gatewayId+" WHERE   systemType = '光字牌'  and value = 'false'";
//        List<IndicatorsDto> indicatorsDtoList = influxDButils.getListDataAll(sql,IndicatorsDto.class);
//        List<AlarmEvent> newAlarmEvents = new ArrayList<>();
//        List<String> alarmsNames = new ArrayList<>();
//
//        for (IndicatorsDto indicatorsDto : indicatorsDtoList) {
//            AlarmEvent alarmEvent = new AlarmEvent();
//            alarmEvent.setEventDesc(indicatorsDto.getEquipmentIndexName());
//            try {
//                Date date = DateUtils.dateParse(indicatorsDto.getCreatedTime(), DateUtils.DATE_TIME_PATTERN);
//                alarmEvent.setEventTime(date);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            alarmEvent.setStationId(stationId);
//            alarmEvent.setStationName(stationName);
//            alarmEvent.setGatewayId(gatewayId);
//            alarmEvent.setCreatedTime(new Date());
//            alarmEvent.setAlarmGroupName("运行告警");
//            alarmEvent.setEventMovement(indicatorsDto.getValue());
//            alarmEvent.setSort(currentsort);
//            newAlarmEvents.add(alarmEvent);
//            alarmsNames.add(indicatorsDto.getEquipmentIndexName());
//        }
//        alarmsNames.sort(Comparator.naturalOrder());
//        String newAlarms = String.join(",", alarmsNames);
//
//        String sort = alarmEventMapper.getLastDataBySort(gatewayId);
//        List<String> oldAlarmEvents = alarmEventMapper.getOldAlarmsBySort(gatewayId, sort);
//        oldAlarmEvents.sort(Comparator.naturalOrder());
//        String oldName = String.join(",", oldAlarmEvents);
//
//        if (!newAlarms.equals(oldName)) {
//            for (String oldAlarmEvent : oldAlarmEvents) {
//                if (newAlarms.contains(oldAlarmEvent)) {
//
//                } else {
//                    AlarmEvent alarmEvent = new AlarmEvent();
//                    alarmEvent.setStationId(stationId);
//                    alarmEvent.setStationName(stationName);
//                    alarmEvent.setEventDesc(oldAlarmEvent);
//                    alarmEvent.setEventTime(new Date());
//                    alarmEvent.setGatewayId(gatewayId);
//                    alarmEvent.setAlarmGroupName("运行告警");
//                    alarmEvent.setCreatedTime(new Date());
//                    alarmEvent.setEventMovement("false");
//                    alarmEvent.setSort(currentsort);
//                    newAlarmEvents.add(alarmEvent);
//                }
//            }
//        }
//        alarmEventService.saveBatch(newAlarmEvents);
//
//    }




//    public  void timingTemporarysSorageData(String gatewayId,long timeInMillis){
//        String sql =  "SELECT * FROM indicators_"+gatewayId+" WHERE  equipmentIndexName = '瞬时风速' ";
//        String sql1 =  "SELECT * FROM indicators_"+gatewayId+" WHERE  equipmentIndexName = '有功功率'";
//        List<IndicatorsDto> indicatorsDtoList = influxDButils.getListDataAll(sql,IndicatorsDto.class);
//        List<IndicatorsDto> indicatorsDtoLists = influxDButils.getListDataAll(sql1,IndicatorsDto.class);
//        List<TemporaryData> temporaryDatas = new ArrayList<>();
//        List<TemporaryData> temporaryDatass = new ArrayList<>();
//        String time = "";
//        try {
//            time   = DateUtils.dateFormat(new Date(), DateUtils.MINUTE_PATTERN);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//    //    long timeInMillis = new Date().getTime();
//        for (IndicatorsDto indicatorsDto : indicatorsDtoList) {
//            try {
//                TemporaryData temporaryData = new TemporaryData();
//                temporaryData.setBatchNo(timeInMillis);
//                temporaryData.setCreatedTime(time.split(" ")[1]);
//                temporaryData.setEquipmentIndexName(indicatorsDto.getEquipmentIndexName());
//                temporaryData.setGatewayId(indicatorsDto.getGatewayId());
//                temporaryData.setValue(Float.valueOf(indicatorsDto.getValue()));
//                temporaryData.setEquipmentNumber(indicatorsDto.getEquipmentNumber());
//                temporaryDatas.add(temporaryData);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        for (IndicatorsDto indicatorsDto : indicatorsDtoLists) {
//            try {
//                TemporaryData temporaryData = new TemporaryData();
//                temporaryData.setBatchNo(timeInMillis);
//                temporaryData.setCreatedTime(time.split(" ")[1]);
//                temporaryData.setEquipmentIndexName(indicatorsDto.getEquipmentIndexName());
//                temporaryData.setGatewayId(indicatorsDto.getGatewayId());
//                temporaryData.setValue(Float.valueOf(indicatorsDto.getValue()));
//                temporaryData.setEquipmentNumber(indicatorsDto.getEquipmentNumber());
//                temporaryDatass.add(temporaryData);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        temporaryDataService.saveBatch(temporaryDatas);
//        temporaryDataService.saveBatch(temporaryDatass);
//    }

//    public  void schedSolarPower(String gatewayId,long timeInMillis){
//        String sql =  "SELECT * FROM indicators_"+gatewayId+" WHERE  displayName = '总辐射累计' ";
//        String sql1 =  "SELECT * FROM indicators_"+gatewayId+" WHERE  displayName = '有功功率'";
//        List<IndicatorsDto> indicatorsDtoList = influxDButils.getListDataAll(sql,IndicatorsDto.class);
//        List<IndicatorsDto> indicatorsDtoLists = influxDButils.getListDataAll(sql1,IndicatorsDto.class);
//        List<TemporaryData> temporaryDatas = new ArrayList<>();
//        List<TemporaryData> temporaryDatass = new ArrayList<>();
//        String time = "";
//        try {
//            time   = DateUtils.dateFormat(new Date(), DateUtils.MINUTE_PATTERN);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//     //   long timeInMillis = new Date().getTime();
//        for (IndicatorsDto indicatorsDto : indicatorsDtoList) {
//            try {
//                TemporaryData temporaryData = new TemporaryData();
//                temporaryData.setBatchNo(timeInMillis);
//                temporaryData.setCreatedTime(time.split(" ")[1]);
//                temporaryData.setEquipmentIndexName(indicatorsDto.getDisplayName());
//                temporaryData.setGatewayId(indicatorsDto.getGatewayId());
//                temporaryData.setValue(Float.valueOf(indicatorsDto.getValue()));
//                temporaryData.setEquipmentNumber(indicatorsDto.getEquipmentNumber());
//                temporaryDatas.add(temporaryData);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        for (IndicatorsDto indicatorsDto : indicatorsDtoLists) {
//            try {
//                TemporaryData temporaryData = new TemporaryData();
//                temporaryData.setBatchNo(timeInMillis);
//                temporaryData.setCreatedTime(time.split(" ")[1]);
//                temporaryData.setEquipmentIndexName(indicatorsDto.getDisplayName());
//                temporaryData.setGatewayId(indicatorsDto.getGatewayId());
//                temporaryData.setValue(Float.valueOf(indicatorsDto.getValue()));
//                temporaryData.setEquipmentNumber(indicatorsDto.getEquipmentNumber());
//                temporaryDatass.add(temporaryData);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        temporaryDataService.saveBatch(temporaryDatas);
//        temporaryDataService.saveBatch(temporaryDatass);
//    }


//    public List<Map<String,Object>>  getStatusMonitoring(String gatewayId,String equipNum,String systemName){
//        String sql =   "SELECT * FROM indicators_"+gatewayId+" WHERE equipmentNumber = '"+equipNum+"' and equipmentIndexName =~/实时故障/";
//        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//        String type = listData.get(0).getEquipmentSpecificName().substring(0,5);
//        List<SystemEnumDto> statusMonitoring = systemEnumMapper.getStatusMonitoring(type, systemName);
//        List<Map<String,Object>> statusMaps = new ArrayList<>();
//        for (SystemEnumDto systemEnumDto : statusMonitoring) {
//            Map<String, Object> statusMap = new HashMap<>();
//            statusMap.put("title1",systemEnumDto.getEnumDesc());
//            for (IndicatorsDto listDatum : listData) {
//                if (listDatum.getEquipmentSpecificName().contains(systemEnumDto.getCode()) &&
//                        systemEnumDto.getEunmValue().equals(listDatum.getValue())){
//                    statusMap.put("state","1");
//                }else {
//                    statusMap.put("state","0");
//                }
//            }
//            statusMaps.add(statusMap);
//        }
//        return  statusMaps;
//    }


//    public List<Map<String,Object>>  getStatusGzp(String gatewayId,String systemType,String frontModule,String equipNum){
//        String sql =   "    SELECT displayName  , value as state,equipmentIndexName   FROM indicators_"+gatewayId+" WHERE  frontModule =~/"+frontModule+"/ and systemType = '"+systemType+"'";
//        if (null != equipNum){
//            sql =   "    SELECT displayName  , value as state,equipmentIndexName  FROM indicators_"+gatewayId+" WHERE  frontModule =~/"+frontModule+"/ and systemType = '"+systemType+"' and equipmentNumber ='"+equipNum+"'";
//        }
//        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//
//        List<Map<String,Object>> statusMaps = new ArrayList<>();
//            for (IndicatorsDto listDatum : listData) {
//                Map<String, Object> statusMap = new HashMap<>();
//                statusMap.put("data",StringUtils.isEmpty(listDatum.getDisplayName())?listDatum.getEquipmentIndexName():listDatum.getDisplayName());
//                statusMap.put("state",listDatum.getState().equals("false")? 1:0);
//                statusMap.put("status",listDatum.getState().equals("false")? 1:0);
//                statusMap.put("title",listDatum.getState().equals("false")?"断":"通");
//                statusMaps.add(statusMap);
//            }
//        return  statusMaps;
//    }


//    public List<Map<String,Object>>  getAnalogQuantity (String gatewayId,String frontModule,String systemType){
//        String sql =   "    SELECT *  FROM indicators_"+gatewayId+" WHERE  frontModule =~/"+frontModule+"/ and systemType = '"+systemType+"' and displayName != ''";
//        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//
//        List<Map<String,Object>> statusMaps = new ArrayList<>();
//        for (IndicatorsDto listDatum : listData) {
//            Map<String, Object> statusMap = new HashMap<>();
//            statusMap.put("title",listDatum.getValue().equals("")? 0: keepTwoDecimalPlaces(listDatum.getValue())+"  "+listDatum.getUnit() == null?"":listDatum.getUnit());
//            statusMap.put("title1",listDatum.getDisplayName());
//            statusMaps.add(statusMap);
//        }
//        return  statusMaps;
//    }



//    public void getStatusJDX(String gatewayId, String stationId,String frontModule){
//        String sql =   " SELECT * FROM indicators_"+gatewayId+"  WHERE frontModule =~/"+frontModule+"/ and displayName =~/合位$/";
//        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//        List<Map<String,Object>> statusMaps = new ArrayList<>();
//
//        Map<String, List<IndicatorsDto>> collect = listData.stream().collect(Collectors.groupingBy(IndicatorsDto::getFrontModule,LinkedHashMap::new,Collectors.toList()));
//        for (String s : collect.keySet()) {
//            Map<String, Object> statusMap = new HashMap<>();
//            if (frontModule.equals("前光")){
//                String sql1 =   " SELECT * FROM indicators_"+gatewayId+"  WHERE frontModule =~/"+s+"/ and systemType =~/模拟量/";
//                List<IndicatorsDto> value = influxDButils.getListData(sql1, IndicatorsDto.class);
//                for (IndicatorsDto indicatorsDto : value) {
//                    Double aDouble = Double.valueOf(indicatorsDto.getValue());
//                    statusMap.put(indicatorsDto.getDisplayName()+"Value",String.format("%.2f",aDouble));
//                }
//            }
//            List<IndicatorsDto> indicatorsDtos = collect.get(s);
//            for (IndicatorsDto indicatorsDto : indicatorsDtos) {
//                if (indicatorsDto.getDisplayName().contains("合位")){
//                    statusMap.put("type",indicatorsDto.getValue());
//                    statusMap.put("status",indicatorsDto.getValue().equals("false")?"0":"1");
//                    statusMap.put("position",indicatorsDto.getDisplayName().split("_")[0]+"开关位置");
//                }
//
//            }
//            statusMap.put("title",s.substring(3));
//            statusMap.put("power","有功 (kW)");
//            statusMap.put("windSpeed","风速 (m/s)");
//            statusMaps.add(statusMap);
//        }
//
//        IPage<Map<String,Object>> result = new Page<>();
//        result.setRecords(statusMaps);
//        result.setCurrent(1);
//        result.setTotal(statusMaps.size());
//        try {
//            emqKeeper.getMqttClient().publish(stationId+"/fxqTree",JSON.toJSONString(result).getBytes(),0,false);
//        } catch (MqttException e) {
//            log.info("消息发送失败");
//            e.printStackTrace();
//        }
//    }

//    public void getListByFJ(String gatewayId,String werks,String stationId){
//        String sql = " SELECT * FROM indicators_"+gatewayId+" WHERE equipmentIndexName ='瞬时风速' ";
//        String sql1 = " SELECT * FROM indicators_"+gatewayId+" WHERE equipmentIndexName ='有功功率'";
//        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//        List<IndicatorsDto> listData1 = influxDButils.getListData(sql1, IndicatorsDto.class);
//        TpriDmpDatabook tpriDmpDatabook = tpriDmpDatabookServiceImpl.getTpriDmpDatabookByDataName("风机");
//        List<Map<String,Object>> dataMaps = sjglZsjZsbtzServiceImpl.sjglZsjZsbtzMapper.getStationInfoMapByStationWerks(werks, tpriDmpDatabook.getDataid().toString());
//       int i = 0;
//        for (Map<String, Object> dataMap : dataMaps) {
//            List<String> numList = Arrays.asList(dataMap.get("equipNum").toString().split(","));
//            List<Map<String,Object>> statusMaps = new ArrayList<>();
//            for (IndicatorsDto listDatum : listData) {
//                for (IndicatorsDto indicatorsDto : listData1) {
//                    if (listDatum.getEquipmentNumber().equals(indicatorsDto.getEquipmentNumber())){
//                        listDatum.setValueLabel(indicatorsDto.getValue());
//                    }
//                }
//
//                for (String num : numList) {
//                    if (Integer.parseInt(num) == Integer.parseInt(listDatum.getEquipmentNumber())){
//                        Map<String,Object>  map = new HashMap<>();
//                        map.put("title",listDatum.getEquipmentNumber());
//                        map.put("windSpeed",listDatum.getValue());
//                        map.put("power",listDatum.getValueLabel());
//                        statusMaps.add(map);
//                    }
//                }
//            }
//            IPage<Map<String,Object>> result = new Page<>();
//            result.setRecords(statusMaps);
//            result.setCurrent(1);
//            result.setTotal(statusMaps.size());
//            i += 1;
//            try {
//                emqKeeper.getMqttClient().publish(stationId+"/fj/group"+i,JSON.toJSONString(result).getBytes(),0,false);
//            } catch (MqttException e) {
//                log.info("消息发送失败");
//                e.printStackTrace();
//            }
//        }
//
//    }



    public List<Map<String, String>> getBoosterStationInfo(String stationId) {
        StationBasic stationBasic = getOneByStationNumber(stationId);
        List<Map<String, String>> boosterStationInfo = new ArrayList<>();
        if ("夏造风电站".equals(stationBasic.getStationName())) {
             boosterStationInfo = monitorFanIndicatorregionMapper.getBoosterStationInfo2(stationBasic.getBoosterGatewayId());
        } else {
             boosterStationInfo = monitorFanIndicatorregionMapper.getBoosterStationInfoNormal(stationBasic.getBoosterGatewayId());
        }
        return boosterStationInfo;
    }

//    public ResultsData runningPageByStationId(int current, int size, String stationId) {
//        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
//        String baseSql = "SELECT equipmentNumber, value, equipmentIndexName FROM \"indicators_%s\" where equipmentIndexName = '%s' or equipmentIndexName = '%s' or equipmentIndexName = '%s' or equipmentIndexName = '%s'";
//        String windSql = String.format(baseSql, stationBasic.getFanGatewayId(), "风向角", "有功功率", "瞬时风速", "日发电量");
//        List<IndicatorsDto> allList = influxDButils.getListDataAll(windSql,IndicatorsDto.class);
//        List<IndicatorsDto> windSqlList = new ArrayList<>();
//        List<IndicatorsDto> powerSqlList = new ArrayList<>();
//        List<IndicatorsDto> windSpeedSqlList = new ArrayList<>();
//        List<IndicatorsDto> electricitySqlList = new ArrayList<>();
//        allList.forEach(item -> {
//            if ("风向角".equals(item.getEquipmentIndexName())) {
//                windSqlList.add(item);
//            } if ("有功功率".equals(item.getEquipmentIndexName())) {
//                item.setValue(String.format("%.2f",Double.parseDouble(item.getValue())/1000));
//                powerSqlList.add(item);
//            } if ("瞬时风速".equals(item.getEquipmentIndexName())) {
//                windSpeedSqlList.add(item);
//            } if ("日发电量".equals(item.getEquipmentIndexName())) {
//                electricitySqlList.add(item);
//            }
//        });
//        Map<String, String> powerSqlMap = powerSqlList.stream().collect(Collectors.toMap(IndicatorsDto::getEquipmentNumber, IndicatorsDto::getValue));
//        Map<String, String> windSpeedSqlMap = windSpeedSqlList.stream().collect(Collectors.toMap(IndicatorsDto::getEquipmentNumber, IndicatorsDto::getValue));
//        Map<String, String> electricitySqlMap = electricitySqlList.stream().collect(Collectors.toMap(IndicatorsDto::getEquipmentNumber, IndicatorsDto::getValue));
//        ArrayList<Map<String, String>> resultList = new ArrayList<>();
//        windSqlList.forEach(item -> {
//            HashMap<String, String> stringStringHashMap = new HashMap<>();
//            stringStringHashMap.put("equipmentNumber", item.getEquipmentNumber());
//            stringStringHashMap.put("wind", item.getValue());
//            stringStringHashMap.put("power", powerSqlMap.get(item.getEquipmentNumber()));
//            stringStringHashMap.put("windSpeed", windSpeedSqlMap.get(item.getEquipmentNumber()));
//            stringStringHashMap.put("electricity", String.format("%.4f",Double.valueOf(electricitySqlMap.get(item.getEquipmentNumber()))));
//            resultList.add(stringStringHashMap);
//        });
//        //构建平台数据
//        DataGridMock DataGridMock = new DataGridMock(current, resultList.size(), false, current, resultList);
//        ColModel colModelEquipmentNumber = new ColModel("equipmentNumber", "equipmentNumber", "风机编码", "风机编码", "dataGrid", "equipmentNumber");
//        ColModel colModelPower = new ColModel("power", "power", "有功功率", "有功功率", "dataGrid", "power");
//        ColModel colModelWindSpeed = new ColModel("windSpeed", "windSpeed", "风速", "风速", "dataGrid", "windSpeed");
//        ColModel colModelWind = new ColModel("wind", "wind", "风向", "风向", "dataGrid", "wind");
//        ColModel colModelElectricity = new ColModel("electricity", "electricity", "日发电量", "日发电量", "dataGrid", "electricity");
//        List<ColModel> listColModel = Arrays.asList(colModelEquipmentNumber, colModelPower, colModelWindSpeed, colModelWind, colModelElectricity);
//        ResultsData resultsData = new ResultsData(DataGridMock, listColModel);
//        return resultsData;
//    }




    public ResultsData getAlarmEventList(int current, int size,String stationId) {

        List<AlarmEventDto> alarmEventList = alarmEventMapper.getAlarmEventList(null, stationId);

        // List<AlarmEventDto> sorrtedAlarmEventList = alarmEventList.stream().sorted(Comparator.comparing(AlarmEventDto::getCreatedTime).reversed()).collect(Collectors.toList());
        ArrayList<Map<String, String>> resultList = new ArrayList<>();
        alarmEventList.forEach(item -> {
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("stationName", item.getStationName());
            stringStringHashMap.put("eventDesc", item.getEventDesc());
            stringStringHashMap.put("alarmGroupName", item.getAlarmGroupName());
            stringStringHashMap.put("eventTime", item.getEventTime());
            stringStringHashMap.put("eventMovement", item.getEventMovement());
            resultList.add(stringStringHashMap);
        });
        //构建平台数据
        DataGridMock DataGridMock = new DataGridMock(current, resultList.size(), false, current, resultList);
        ColModel colModelStationName = new ColModel("stationName", "stationName", "名称", "名称", "dataGrid", "stationName");
        ColModel colModelEventDesc = new ColModel("eventDesc", "eventDesc", "事件描述", "事件描述", "dataGrid", "eventDesc");
        ColModel colModelAlarmGroupName = new ColModel("alarmGroupName", "alarmGroupName", "事件告警组", "事件告警组", "dataGrid", "alarmGroupName");
        ColModel colModelEventTime = new ColModel("eventTime", "eventTime", "事件发生时间", "事件发生时间", "dataGrid", "eventTime");
        ColModel colModelEventMovement = new ColModel("eventMovement", "eventMovement", "事件动作描述", "事件动作描述", "dataGrid", "eventMovement");
        List<ColModel> listColModel = Arrays.asList(colModelStationName, colModelEventDesc, colModelAlarmGroupName, colModelEventTime, colModelEventMovement);
        ResultsData resultsData = new ResultsData(DataGridMock, listColModel);
        return resultsData;
    }


//    public ResultsData getElectricQuantityList(int current, int size,String gatewayId,String stationType) {
//
//        String sql = " SELECT * FROM indicators_" + gatewayId + " WHERE frontModule ='电量表计' and displayName != ''  and displayName != '检修状态' ";
//        List<IndicatorsDto> windSqlList = influxDButils.getListDataAll(sql, IndicatorsDto.class);
//        Map<String, List<IndicatorsDto>> maps = windSqlList.stream().collect(Collectors.groupingBy(IndicatorsDto::getSystemType));
//        ArrayList<Map<String, String>> resultList = new ArrayList<>();
//        for (Map.Entry<String, List<IndicatorsDto>> stringListEntry : maps.entrySet()) {
//            HashMap<String, String> stringStringHashMap = new HashMap<>();
//            stringStringHashMap.put("name", stringListEntry.getKey());
//            for (IndicatorsDto indicatorsDto : stringListEntry.getValue()) {
//                stringStringHashMap.put(ElectricQuantity.getCode(indicatorsDto.getDisplayName()), String.format("%.2f",ObjectUtils.isEmpty(indicatorsDto.getValue())?0.0:Double.parseDouble(indicatorsDto.getValue())));
//            }
//            resultList.add(stringStringHashMap);
//        }
//        //构建平台数据
//        DataGridMock DataGridMock = new DataGridMock(current, resultList.size(), false, current, resultList);
//        ColModel colModelEventMovement = new ColModel("name", "name", "测量点", "测量点", "dataGrid", "name");
//        ColModel colModelStationName = new ColModel("zxzyg", "zxzyg", "正向总有功", "正向总有功", "dataGrid", "zxzyg");
//        ColModel colModelEventDesc = new ColModel("fxzyg", "fxzyg", "反向总有功", "反向总有功", "dataGrid", "fxzyg");
//        ColModel colModelAlarmGroupName = new ColModel("zxzwg", "zxzwg", "正向总无功", "正向总无功", "dataGrid", "zxzwg");
//        ColModel colModelEventTime = new ColModel("fxzwg", "fxzwg", "反向总无功", "反向总无功", "dataGrid", "fxzwg");
//        if (null != stationType){
//         colModelEventMovement = new ColModel("name", "name", "测量点", "测量点", "dataGrid", "name");
//         colModelStationName = new ColModel("zgxwg", "zgxwg", "总感性无功", "总感性无功", "dataGrid", "zgxwg");
//         colModelEventDesc = new ColModel("zzxwg", "zzxwg", "总正向有功", "总正向有功", "dataGrid", "zzxwg");
//         colModelAlarmGroupName = new ColModel("zrxwg", "zrxwg", "总容性无功", "总容性无功", "dataGrid", "zrxwg");
//         colModelEventTime = new ColModel("zfxyg", "zfxyg", "总反向有功", "总反向有功", "dataGrid", "zfxyg");
//        }
//        List<ColModel> listColModel = Arrays.asList(colModelEventMovement, colModelStationName, colModelEventDesc, colModelAlarmGroupName, colModelEventTime);
//        ResultsData resultsData = new ResultsData(DataGridMock, listColModel);
//        return resultsData;
//    }


//    public void getAnalogQuantityInfo(String gatewayId, String stationId, String routeName) {
//        if (StringUtils.isNotEmpty(gatewayId)) {
//            Map<String, String> map = monitorFanIndicatorregionMapper.getMajorBoosterStationInfoBySort(gatewayId, routeName);
//                String sql = String.format("SELECT equipmentIndexName, value, frontModule, unit, displayName FROM \"indicators_%s\" WHERE systemType = '%s' and frontModule =~/%s/ ", gatewayId, "模拟量", map.get("boosterName"));
//                if ("1主变高压侧".equals(map.get("boosterName")) || "1主变低压侧".equals(map.get("boosterName"))) {
//                    sql = String.format("SELECT equipmentIndexName, value, frontModule, unit, displayName FROM \"indicators_%s\" WHERE systemType = '%s' and (frontModule =~/1主变低压侧/ or frontModule =~/1主变高压侧/ )", gatewayId, "模拟量");
//                    List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//                    // 主变高压侧
//                    Map<String, String> zbGYC = listData.stream().filter(t -> t.getFrontModule().contains("1主变高压侧")).collect(Collectors.toMap(IndicatorsDto::getDisplayName, IndicatorsDto::getValue));
//                    List<Map<String, String>> zbList = new ArrayList<>();
//
//                    listData.stream().filter(t -> t.getFrontModule().contains("1主变低压侧")).forEach(item -> {
//                        HashMap<String, String> zbMap = new HashMap<>();
//                        zbMap.put("title", item.getDisplayName());
//                        zbMap.put("grade1", keepTwoDecimalPlaces(item.getValue()));
//                        zbMap.put("grade2", keepTwoDecimalPlaces(zbGYC.getOrDefault(item.getDisplayName(), "0.0")));
//                        if (StringUtils.isNotEmpty(item.getUnit())) {
//                            zbMap.put("title", String.format("%s(%s)", item.getDisplayName(), item.getUnit()));
//                        }
//                        zbList.add(zbMap);
//                    });
//                    IPage<Map<String, String>> zbResult = new Page<>();
//                    zbResult.setRecords(zbList);
//                    zbResult.setCurrent(1);
//                    zbResult.setTotal(zbList.size());
//                    try {
//                        log.info("主变消息内容：{}", JSON.toJSONString(zbResult));
//                        emqKeeper.getMqttClient().publish(String.format("%s/%s/%s", stationId, routeName, "mnl"), JSON.toJSONString(zbResult).getBytes(), 2, false);
//                    } catch (MqttException e) {
//                        log.info("消息发送失败");
//                        e.printStackTrace();
//                    }
//                } else {
//                    List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//                    ArrayList<Map<String, String>> resultList = new ArrayList<>();
//                    listData.forEach(item -> {
//                        HashMap<String, String> stringStringHashMap = new HashMap<>();
//                        stringStringHashMap.put("title", item.getDisplayName());
//                        stringStringHashMap.put("value", keepTwoDecimalPlaces(item.getValue()));
//                        if (StringUtils.isNotEmpty(item.getUnit())) {
//                            stringStringHashMap.put("title", String.format("%s(%s)", item.getDisplayName(), item.getUnit()));
//                        }
//                        resultList.add(stringStringHashMap);
//                    });
//
//                    IPage<Map<String, String>> result = new Page<>();
//                    result.setRecords(resultList);
//                    result.setCurrent(1);
//                    result.setTotal(resultList.size());
//                    try {
//                        log.info("消息内容：{}", JSON.toJSONString(result));
//                        emqKeeper.getMqttClient().publish(String.format("%s/%s/%s", stationId, routeName, "mnl"), JSON.toJSONString(result).getBytes(),2,false);
//                    } catch (MqttException e) {
//                        log.info("消息发送失败");
//                        e.printStackTrace();
//                    }
//                }
//        }
//    }

//    public void getMajorAnalogQuantityByPage(String gatewayId, String stationId) {
//        if (StringUtils.isNotEmpty(gatewayId)) {
////            List<Map<String, String>> boosterStationInfo = monitorFanIndicatorregionMapper.getMajorBoosterStationInfo(gatewayId, "DESC", 3);
//
//            String xianSql = String.format("SELECT equipmentIndexName, value, frontModule, unit, displayName FROM \"indicators_%s\" WHERE systemType = '模拟量' and (frontModule = '220kVⅠ母PT' or frontModule = '35kVⅠ母PT')", gatewayId);
//            List<IndicatorsDto> xianData = influxDButils.getListData(xianSql, IndicatorsDto.class);
//            HashMap<String, Object> resultMap = new HashMap<>();
//            xianData.forEach(item -> {
//                if ("220kVⅠ母PT".equals(item.getFrontModule())) {
//                    resultMap.put("220" + item.getDisplayName(), keepTwoDecimalPlaces(item.getValue()));
//                } else if ("35kVⅠ母PT".equals(item.getFrontModule())) {
//                    resultMap.put("35" + item.getDisplayName(), keepTwoDecimalPlaces(item.getValue()));
//                }
//            });
//
//            String xyxSql = String.format("SELECT value, displayName FROM \"indicators_%s\" WHERE systemType = '模拟量' and frontModule = '夏雩线' and (displayName = 'Ia' or displayName = 'P' or displayName = 'Q' or displayName = 'Ux')", gatewayId);
//            List<IndicatorsDto> xyxSqlData = influxDButils.getListData(xyxSql, IndicatorsDto.class);
//            xyxSqlData.forEach(item -> resultMap.put("xyx" + item.getDisplayName(), keepTwoDecimalPlaces(item.getValue())));
//
//            String dlbjSql = String.format("SELECT value, displayName FROM \"indicators_%s\" WHERE systemType = '模拟量' and frontModule = '电量表计'", gatewayId);
//            List<IndicatorsDto> dlbjSqlData = influxDButils.getListData(dlbjSql, IndicatorsDto.class);
//            // 正向总有功正向总无功需要计算
//            dlbjSqlData.forEach(item -> {
//                if ("正向总有功".equals(item.getDisplayName())) {
//                    resultMap.put("2000S1", keepTwoDecimalPlaces(String.valueOf((Double.parseDouble(item.getValue())/1000))));
//                } else if ("正向总无功".equals(item.getDisplayName())) {
//                    resultMap.put("2000S2", keepTwoDecimalPlaces(String.valueOf((Double.parseDouble(item.getValue())/1000))));
//                }
//            });
//
//            String zb1Sql = String.format("SELECT * FROM \"indicators_%s\" WHERE  frontModule = '1主变' and systemType = '模拟量'  and (displayName = '档位' or displayName = '油面温1' or displayName = '油面温2' or displayName = '绕组温度' ) ", gatewayId);
//            List<IndicatorsDto> zb1SqlData = influxDButils.getListData(zb1Sql, IndicatorsDto.class);
//            resultMap.put("value1", "0.0");
//            resultMap.put("value2", "0.0");
//            resultMap.put("value3", "0.0");
//            resultMap.put("value4", "0.0");
//            zb1SqlData.forEach(item -> {
//                if ("档位".equals(item.getDisplayName())) {
//                    resultMap.put("value4", ObjectUtils.isEmpty(item.getValue())?"0":String.format("%.0f",Double.parseDouble(item.getValue())));
//                } else if ("油面温1".equals(item.getDisplayName())) {
//                    resultMap.put("value1", ObjectUtils.isEmpty(item.getValue())?"0.0":String.format("%.1f",Double.parseDouble(item.getValue())));
//                } else if ("油面温2".equals(item.getDisplayName())) {
//                    resultMap.put("value2", ObjectUtils.isEmpty(item.getValue())?"0.0":String.format("%.1f",Double.parseDouble(item.getValue())));
//                } else if ("绕组温度".equals(item.getDisplayName())) {
//                    resultMap.put("value3", ObjectUtils.isEmpty(item.getValue())?"0.0":String.format("%.1f",Double.parseDouble(item.getValue())));
//                }
//            });
//
//            // 主线路图上各个路线名称
//            resultMap.put("xyx", "夏雩线");
//            resultMap.put("zbgy", "1主变高压侧");
//            resultMap.put("220mpt", "220kVⅠ母PT");
//            resultMap.put("jd1", "集电Ⅰ线");
//            resultMap.put("jd2", "集电Ⅱ线");
//            resultMap.put("jd3", "集电Ⅲ线");
//            resultMap.put("jd4", "集电Ⅳ线");
//            resultMap.put("zbdy", "1主变低压侧");
//            resultMap.put("dy1", "待用Ⅰ线");
//            resultMap.put("35mpt", "35kVⅠ母PT");
//            resultMap.put("1jdb", "1接地变");
//            resultMap.put("1svg", "1SVG");
//            resultMap.put("2svg", "2SVG");
//
//            resultMap.put("xzsvg", "夏造 SVG");
//            resultMap.put("xzaggavc", "夏造 AGGAVC");
//            resultMap.put("xzgyxh", "夏造 公用信号");
//            resultMap.put("xzjzlp", "夏造 交直流屏");
//
//            //下方重复列表数据
//            List<Map<String, String>> boosterStationInfo = monitorFanIndicatorregionMapper.getMajorBoosterStationInfo(gatewayId, "ASC", 10);
//            ArrayList<Map<String, String>> resultList = new ArrayList<>();
//            for (Map<String, String> map : boosterStationInfo) {
//                String sql = String.format("SELECT equipmentIndexName, value, frontModule, unit, displayName FROM \"indicators_%s\" WHERE systemType = '%s' and frontModule =~/%s/ and (displayName = 'Ia' or displayName = 'P'  or displayName = 'Q') ", gatewayId, "模拟量", map.get("boosterName"));
//                List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//
//                HashMap<String, String> stringStringHashMap = new HashMap<>();
//                stringStringHashMap.put("value1", "0.0");
//                stringStringHashMap.put("value2", "0.0");
//                stringStringHashMap.put("value3", "0.0");
//                listData.forEach(item -> {
//                    if (item.getDisplayName().equals("Ia")) {
//                        stringStringHashMap.put("value1", keepTwoDecimalPlaces(item.getValue()));
//                    }
//                    if (item.getDisplayName().equals("P")) {
//                        stringStringHashMap.put("value2", keepTwoDecimalPlaces(item.getValue()));
//                    }
//                    if (item.getDisplayName().equals("Q")) {
//                        stringStringHashMap.put("value3", keepTwoDecimalPlaces(item.getValue()));
//                    }
//                });
//                resultList.add(stringStringHashMap);
//            }
//            resultMap.put("records", resultList);
//            resultMap.put("current", 1);
//            resultMap.put("size", resultList.size());
//
//            // 开关信息
//            Map<String, Object> switchUrl = getSwitchUrl(gatewayId, null);
//            resultMap.putAll(switchUrl);
//
//            List<Map<String, Object>> finallyResultList = Collections.singletonList(resultMap);
//            // 主屏下方重复列表数据
//            IPage<Map<String, Object>> resultPage = new Page<>();
//            resultPage.setRecords(finallyResultList);
//            resultPage.setCurrent(1);
//            resultPage.setTotal(finallyResultList.size());
//            try {
//                log.info("消息内容：{}", JSON.toJSONString(resultPage));
//                emqKeeper.getMqttClient().publish(String.format("%s/%s/%s", stationId, "major", "data"), JSON.toJSONString(resultPage).getBytes(), 0, false);
//            } catch (MqttException e) {
//                log.info("消息发送失败");
//                e.printStackTrace();
//            }
//        }
//    }
//
//
//    public void getMajorAnalogQuantityByPageByTHGF(String gatewayId, String stationId) {
//        if (StringUtils.isNotEmpty(gatewayId)) {
//            // 10kVⅡ段母线数据
//            String xianSql = String.format("SELECT equipmentIndexName, value, frontModule, unit, displayName FROM \"indicators_%s\" WHERE systemType = '模拟量' and frontModule = '35kVⅠ母PT'", gatewayId);
//            List<IndicatorsDto> xianData = influxDButils.getListData(xianSql, IndicatorsDto.class);
//            HashMap<String, Object> resultMap = new HashMap<>();
//            xianData.forEach(item -> resultMap.put(item.getDisplayName(), keepTwoDecimalPlaces(item.getValue())));
//
//
//            String xyxSql = String.format("SELECT value, displayName FROM \"indicators_%s\" WHERE systemType = '模拟量' and frontModule = '35kV前万线' and (displayName = 'Ia' or displayName = 'P' or displayName = 'Q' ", gatewayId);
//            List<IndicatorsDto> xyxSqlData = influxDButils.getListData(xyxSql, IndicatorsDto.class);
//            xyxSqlData.forEach(item -> resultMap.put("35qwx" + item.getDisplayName(), keepTwoDecimalPlaces(item.getValue())));
//
//            // 主线路图上各个路线名称
//            resultMap.put("35qwx", "35kV前万线");
//            resultMap.put("35qg1x", "35kV前光Ⅰ线");
//            resultMap.put("35qg2x", "35kV前光Ⅱ线");
//            resultMap.put("1svg", "1SVG");
//            resultMap.put("1zyb", "1站用变");
//            resultMap.put("35mxpt", "35kV母线PT");
//
//            resultMap.put("thsvg", "泰和SVG");
//            resultMap.put("thglyc", "泰和功率预测");
//            resultMap.put("thgyxh", "泰和公用信号");
//            resultMap.put("thjzlp", "泰和交直流屏");
//
//            //下方重复列表数据
//            List<Map<String, String>> boosterStationInfo = monitorFanIndicatorregionMapper.getMajorBoosterStationInfo(gatewayId, "ASC", 5);
//            ArrayList<Map<String, String>> resultList = new ArrayList<>();
//            for (Map<String, String> map : boosterStationInfo) {
//                String sql = String.format("SELECT equipmentIndexName, value, frontModule, unit, displayName FROM \"indicators_%s\" WHERE systemType = '%s' and frontModule =~/%s/ and (displayName = 'Ia' or displayName = 'P'  or displayName = 'Q') ", gatewayId, "模拟量", map.get("boosterName"));
//                List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//
//                HashMap<String, String> stringStringHashMap = new HashMap<>();
//                stringStringHashMap.put("value1", "0.0");
//                stringStringHashMap.put("value2", "0.0");
//                stringStringHashMap.put("value3", "0.0");
//                listData.forEach(item -> {
//                    if (item.getDisplayName().equals("Ia")) {
//                        stringStringHashMap.put("value1", keepTwoDecimalPlaces(item.getValue()));
//                    }
//                    if (item.getDisplayName().equals("P")) {
//                        stringStringHashMap.put("value2", keepTwoDecimalPlaces(item.getValue()));
//                    }
//                    if (item.getDisplayName().equals("Q")) {
//                        stringStringHashMap.put("value3", keepTwoDecimalPlaces(item.getValue()));
//                    }
//                });
//                resultList.add(stringStringHashMap);
//            }
//            resultMap.put("records", resultList);
//            resultMap.put("current", 1);
//            resultMap.put("size", resultList.size());
//
//            // 开关信息
//            Map<String, Object> switchUrl = getSwitchUrl(gatewayId, null);
//            resultMap.putAll(switchUrl);
//
//            List<Map<String, Object>> finallyResultList = Collections.singletonList(resultMap);
//            // 主屏下方重复列表数据
//            IPage<Map<String, Object>> resultPage = new Page<>();
//            resultPage.setRecords(finallyResultList);
//            resultPage.setCurrent(1);
//            resultPage.setTotal(finallyResultList.size());
//            try {
//                log.info("消息内容：{}", JSON.toJSONString(resultPage));
//                emqKeeper.getMqttClient().publish(String.format("%s/%s/%s", stationId, "major", "data"), JSON.toJSONString(resultPage).getBytes(),0,false);
//            } catch (MqttException e) {
//                log.info("消息发送失败");
//                e.printStackTrace();
//            }
//        }
//    }


//    public void getSwitchUrlAll(StationBasic stationBasic){
//        String gatewayId = stationBasic.getBoosterGatewayId();
//
//        String sql = "SELECT * FROM indicators_"+gatewayId+" WHERE systemType = '开关' and  displayName =~/合位$/";
//        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//        Set<String> names = new HashSet<>();
//
//        for (IndicatorsDto listDatum : listData) {
//            names.add(listDatum.getFrontModule());
//        }
//
//        for (String name : names) {
//            getSwitchUrl(gatewayId,name);
//        }
//
//    }


//    public Map<String, Object> getSwitchUrl(String gatewayId,String equipName ){
//        String sql = "SELECT * FROM indicators_" + gatewayId + " WHERE systemType =~/开关/" + " and displayName =~/合位$/";
//        String sql1 = "SELECT * FROM indicators_" + gatewayId + " WHERE systemType =~/开关/" + " and displayName =~/远方就地开关$/";
//        String sql2 = "SELECT * FROM indicators_" + gatewayId + " WHERE systemType =~/开关/" + " and displayName =~/接地刀位置$/";
//        if (StringUtils.isNotEmpty(equipName)) {
//             sql = "SELECT * FROM indicators_"+gatewayId+" WHERE systemType =~/开关/ and frontModule =~ /"+equipName+"/ and displayName =~/合位$/";
//             sql1 = "SELECT * FROM indicators_"+gatewayId+" WHERE systemType =~/开关/ and frontModule =~ /"+equipName+"/ and displayName =~/远方就地开关$/";
//             sql2 = "SELECT * FROM indicators_"+gatewayId+" WHERE systemType =~/开关/ and frontModule =~ /"+equipName+"/ and displayName =~/接地刀位置$/";
//        }
//        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//        List<IndicatorsDto> listDatas = influxDButils.getListData(sql1, IndicatorsDto.class);
//        List<IndicatorsDto> listDatass = influxDButils.getListData(sql2, IndicatorsDto.class);
//        Map<String, Object> photoUrls = new HashMap<>();
//
//        for (IndicatorsDto datass : listDatass) {
//            String url = "";
//            String[] urls = datass.getPictureName().split(",");
//            if (datass.getValue().equals("false")){
//                url =pictureUrl+urls[0];
//            }else {
//                url =pictureUrl+ urls[1];;
//            }
//            photoUrls.put(datass.getDisplayName().split("_")[0]+"jddwz",url);
//        }
//
//        for (IndicatorsDto data : listDatas) {
//            String url = "";
//            String[] urls = data.getPictureName().split(",");
//            if (StringUtils.isNotEmpty(data.getValue()) && data.getValue().equals("false")){
//                url =pictureUrl+urls[1];
//            }else {
//                url =pictureUrl+ urls[0];;
//            }
//            if (data.getDisplayName().split("_").length > 2){
//                photoUrls.put(KGName.getCode(data.getDisplayName().split("_")[1]),url);
//            }else {
//                photoUrls.put(data.getDisplayName().split("_")[0]+"yfjdkgurl",url);
//            }
//        }
//
//        for (IndicatorsDto listDatum : listData) {
//            String url = "";
//            if (listDatum.getDisplayName().contains("手车工作位置")){
//                String[] split = listDatum.getPictureName().split(":");
//                if (listDatum.getValue().equals("false")){
//                    String[] split1 = split[0].split(",");
//                    photoUrls.put(listDatum.getDisplayName().split("_")[0]+"scsurl",pictureUrl+split1[0]);
//                    photoUrls.put(listDatum.getDisplayName().split("_")[0]+"scxurl",pictureUrl+split1[1]);
//                }else {
//                    String[] split1 = split[1].split(",");
//                    photoUrls.put(listDatum.getDisplayName().split("_")[0]+"scsurl",pictureUrl+split1[0]);
//                    photoUrls.put(listDatum.getDisplayName().split("_")[0]+"scxurl",pictureUrl+split1[1]);
//                }
//            }else {
//                if (listDatum.getValue().equals("false")){
//                    url =pictureUrl+ listDatum.getPictureName();
//                }else {
//                    url =pictureUrl+ listDatum.getPictureName().replace("green", "red");
//                }
//                photoUrls.put(listDatum.getDisplayName().split("_")[0]+"url",url);
//            }
//        }
//        return photoUrls;
//
//    }


//    public HashMap<String, Object> getyw(String gatewayId){
//        HashMap<String, Object> resultMap = new HashMap<>();
//        String zb1Sql = String.format("SELECT * FROM \"indicators_%s\" WHERE  frontModule = '1主变' and systemType = '模拟量'  and (displayName = '档位' or displayName = '油面温1' or displayName = '油面温2' or displayName = '绕组温度' ) ", gatewayId);
//        List<IndicatorsDto> zb1SqlData = influxDButils.getListData(zb1Sql, IndicatorsDto.class);
//        // TODO: 2023/7/14 数据未整理  --->  油面温1   油面温2   绕组温度
//        resultMap.put("value1", "0.0");
//        resultMap.put("value2", "0.0");
//        resultMap.put("value3", "0.0");
//        resultMap.put("value4", "0.0");
//        zb1SqlData.forEach(item -> {
//            if ("档位".equals(item.getDisplayName())) {
//                resultMap.put("value4", item.getValue());
//            } else if ("油面温1".equals(item.getDisplayName())) {
//                resultMap.put("value1", item.getValue());
//            } else if ("油面温2".equals(item.getDisplayName())) {
//                resultMap.put("value2", item.getValue());
//            } else if ("绕组温度".equals(item.getDisplayName())) {
//                resultMap.put("value3", item.getValue());
//            }
//        });
//        return resultMap;
//    }



//    public HashMap<String, Object> getEquipInfoByEquipNum(String gatewayId ,String equipmentNumber){
//        HashMap<String, Object> resultMap = new HashMap<>();
//        String sql = "SELECT * FROM indicators_"+gatewayId+" WHERE equipmentNumber ='"+equipmentNumber +"' limit 1  ";
//        List<IndicatorsDto> list = influxDButils.getListData(sql, IndicatorsDto.class);
//        if (!ValidationUtil.isEmpty(list)){
//            resultMap.put("equipmentSpecificName",list.get(0).getEquipmentSpecificName());
//            resultMap.put("equipmentIndexName",list.get(0).getEquipmentSpecificName());
//            resultMap.put("equipmentInfoName",list.get(0).getEquipmentSpecificName().substring(5).replace("/"," "));
//            resultMap.put("status",list.get(0).getValue().equals("false")?"异常":"正常运行");
//        }
//        return resultMap;
//    }

    public Map<String, Object> getStatisticsInfo(String gatewayId ,String equipmentIndexName){
        return     temporaryDataMapper.getStatisticsInfo(gatewayId,equipmentIndexName);
    }



//    public List<Map<String,Object>>  getEquipmentNum (String gatewayId,String frontModule,String equipmentNumber){
//        String sql =   "    SELECT  equipmentNumber, equipmentSpecificName   FROM indicators_"+gatewayId+" WHERE   frontModule = '"+frontModule+"' and equipmentNumber !=''";
//        if (null != equipmentNumber){
//            sql =   "    SELECT  equipmentNumber, equipmentSpecificName   FROM indicators_"+gatewayId+" WHERE  equipmentNumber =~/"+equipmentNumber+"/ and frontModule = '"+frontModule+"'";
//        }
//        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//        LinkedHashSet<IndicatorsDto>  data = new LinkedHashSet<>(listData);
//        List<Map<String,Object>> statusMaps = new ArrayList<>();
//        for (IndicatorsDto listDatum : data) {
//            Map<String, Object> statusMap = new HashMap<>();
//            statusMap.put("equipmentNumber",listDatum.getEquipmentNumber());
//            statusMap.put("equipmentSpecificName",listDatum.getEquipmentSpecificName().substring(5).replace("/"," "));
//            statusMaps.add(statusMap);
//        }
//        return  statusMaps;
//    }

    public String keepTwoDecimalPlaces(String value) {
        String s = "0.00";
        if (!ObjectUtils.isEmpty(value)) {
            try {
                s = String.format("%.2f", Double.parseDouble(value));
            } catch (Exception ex) {

            }
        }
        return s;
    }


//    public HashMap<String, Object> SpeedIndicator(String gatewayId ,String equipmentNumber,String equipmentIndexName){
//        HashMap<String, Object> resultMap = new HashMap<>();
//        String sql = "SELECT * FROM indicators_"+gatewayId+" WHERE equipmentNumber ='"+equipmentNumber +"' and equipmentIndexName = '"+equipmentIndexName+"'";
//       log.info("执行sql"+sql);
//        List<IndicatorsDto> list = influxDButils.getListData(sql, IndicatorsDto.class);
//        if (!ValidationUtil.isEmpty(list)){
//            resultMap.put("value",String.format("%.2f",Double.parseDouble(list.get(0).getValue())));
//        }
//        return resultMap;
//    }


//    public void getEquipSwitchStatus(StationBasic stationBasic ){
//        String gatewayId = stationBasic.getFanGatewayId();
//        Long stationId = stationBasic.getSequenceNbr();
//        String sql = "SELECT * FROM indicators_"+gatewayId+" WHERE  equipmentIndexName =~/合闸/";
//        List<IndicatorsDto> list = influxDButils.getListData(sql, IndicatorsDto.class);
//
//        if (!ValidationUtil.isEmpty(list)){
//            Map<String, List<IndicatorsDto>> collect = list.stream().collect(Collectors.groupingBy(IndicatorsDto::getEquipmentNumber));
//            for (String s : collect.keySet()) {
//                HashMap<String, Object> resultMap = new HashMap<>();
//                collect.get(s).stream().forEach(e->{
//                    String picturl = "";
//                    if (e.getValue().equals("false")){
//                        picturl = pictureUrl+"dlg-h-red.png";
//                    }else {
//                        picturl = pictureUrl+"dlg-h-green.png";
//                    }
//                if(e.getEquipmentIndexName().endsWith("断路器合闸")){
//                    resultMap.put(e.getEquipmentIndexName().substring(0,3),picturl);
//                    }else {
//                    resultMap.put("gy",picturl);
//                }
//                });
//                IPage<Map<String, Object>> result = new Page<>();
//                List<Map<String, Object>> data = new ArrayList<>();
//                data.add(resultMap);
//                result.setRecords(data);
//                result.setCurrent(1);
//                result.setTotal(100);
//                try {
//                    emqKeeper.getMqttClient().publish(stationId+"/xbjg/"+s,JSON.toJSONString(result).getBytes(),0,false);
//                } catch (MqttException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        }
//
//    }



//    public ResultsData collectingBox(String gatewayId ,int current,int size){
//
//        ArrayList<Map<String, Object>> resultList = new ArrayList<>();
//        String sql = "SELECT * FROM indicators_"+gatewayId+" WHERE equipmentIndexName =~/路电流/   ";
//        String sql1 = "SELECT * FROM indicators_"+gatewayId+" WHERE equipmentIndexName =~/平均电流/ ";
//        List<IndicatorsDto> list = influxDButils.getListData(sql, IndicatorsDto.class);
//        List<IndicatorsDto> list1 = influxDButils.getListData(sql1, IndicatorsDto.class);
//        if (!ValidationUtil.isEmpty(list)){
//            Map<String, List<IndicatorsDto>> collect = list.stream().collect(Collectors.groupingBy(IndicatorsDto::getEquipmentNumber));
//            for (String s : collect.keySet()) {
//                List<IndicatorsDto> indicatorsDtos = collect.get(s);
//                HashMap<String, Object> resultMap = new HashMap<>();
//                Double avageValue =  0.0;
//                avageValue =indicatorsDtos.stream().filter(e -> !ObjectUtils.isEmpty(e.getValue())).mapToDouble(l->Double.parseDouble((String) l.getValue())).average().getAsDouble();
//                avageValue = Double.valueOf(String.format("%.2f", avageValue));
//                resultMap.put("avg",avageValue);
//                String[] name = s.split("-");
//                resultMap.put("zz","#"+name[0]+"子阵");
//                resultMap.put("nbq","逆变器"+name[1]);
//                resultMap.put("hlx","#"+name[2]+"汇流箱");
//                double lsv = 0.00;
//                if(!ValidationUtil.isEmpty(list1)){
//                    List<IndicatorsDto> dtos = list1.stream().filter(e -> e.getEquipmentNumber().equals(s)).collect(Collectors.toList());
//                    if (!ValidationUtil.isEmpty(dtos)){
//                        for (IndicatorsDto indicatorsDto : indicatorsDtos) {
//                            lsv=  lsv + Math.pow(Double.parseDouble(indicatorsDto.getValue()) - Double.parseDouble(dtos.get(0).getValue()), 2);
//                        }
//                    }
//                    lsv=    Math.sqrt(lsv)/Double.parseDouble(dtos.get(0).getValue());
//                }
//
//
//                resultMap.put("lsv",String.format("%.2f", lsv));
//                resultList.add(resultMap);
//            }
//        }
//        //构建平台数据
//        DataGridMock DataGridMock = new DataGridMock(current, resultList.size(), false, current, resultList);
//        ColModel colModelEventMovement = new ColModel("zz", "zz", "子阵", "子阵", "dataGrid", "zz");
//        ColModel colModelStationName = new ColModel("nbq", "nbq", "逆变器", "逆变器", "dataGrid", "nvq");
//        ColModel colModelEventDesc = new ColModel("hlx", "hlx", "汇流箱", "汇流箱", "dataGrid", "hlx");
//        ColModel colModelAlarmGroupName = new ColModel("avg", "avg", "支路电流平均值", "支路电流平均值", "dataGrid", "avg");
//        ColModel colModelEventTime = new ColModel("lsl", "lsv", "支路电流离散率", "支路电流离散率", "dataGrid", "lsv");
//        List<ColModel> listColModel = Arrays.asList(colModelEventMovement, colModelStationName, colModelEventDesc, colModelAlarmGroupName, colModelEventTime);
//        ResultsData resultsData = new ResultsData(DataGridMock, listColModel);
//        return resultsData;
//    }


//    public List<Map<String, Object>> solarPowerOperation(String gatewayId) {
//        String sql = "SELECT * FROM indicators_"+gatewayId+" WHERE equipmentIndexName = '有功功率' or  equipmentIndexName = '逆变器效率'  or equipmentIndexName ='总直流功率'  or equipmentIndexName ='日发电量'  or equipmentIndexName ='总发电量'   ";
//        List<IndicatorsDto> list = influxDButils.getListData(sql, IndicatorsDto.class);
//        List<IndicatorsDto> collect = list.stream().filter(e -> StringUtils.isNotEmpty(e.getEquipmentNumber())).collect(Collectors.toList());
//        Map<String, List<IndicatorsDto>> collects = collect.stream().collect(Collectors.groupingBy(IndicatorsDto::getEquipmentNumber));
//        List<Map<String, Object>> result = new  ArrayList();
//        for (String s : collects.keySet()){
//            List<IndicatorsDto> indicatorsDtos = collects.get(s);
//            Map<String, Object> map = new HashMap<>();
//            map.put("name",s);
//            map.put("type","兆能");//此处暂时未提供数据 待定 暂写死值
//            map.put("status","1");//此处暂时未提供数据 待定 暂写死值
//            indicatorsDtos.forEach(e->{
//                switch (e.getEquipmentIndexName()){
//                    case "总直流功率":
//                        map.put("sr",keepTwoDecimalPlaces(e.getValue()));
//                        break;
//                    case "有功功率":
//                        map.put("sc",keepTwoDecimalPlaces(e.getValue()));
//                        break;
//                    case "逆变器效率":
//                        map.put("efficiency",keepTwoDecimalPlaces(e.getValue()));
//                        break;
//                    case "日发电量":
//                        map.put("dayNum",keepTwoDecimalPlaces(e.getValue()));
//                        break;
//                    case "总发电量":
//                        map.put("yearNum",keepTwoDecimalPlaces(e.getValue()));
//                        break;
//                }
//            });
//            result.add(map);
//        }
//        return result;
//        }

//    public Map<String, Object> hlWindSpeeds(String gatewayId, String equipNum) {
//        Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
//        String time = "";
//        try {
//            time  = DateUtils.dateFormat(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        String[] equipNumber = equipNum.split("-");
//        String sql =   "SELECT  time ,equipmentIndexName ,value FROM iot_data_"+gatewayId+" WHERE time >'"+time+"'  and equipmentSpecificName =~/"+equipNumber[0]+"子阵/ and equipmentSpecificName =~/逆变器"+equipNumber[1]+"/  and equipmentSpecificName =~/"+Integer.parseInt(equipNumber[2])+"汇流箱/  and equipmentIndexName =~/路电流/";
//        String timeSql =   "SELECT   DISTINCT value FROM iot_data_"+gatewayId+" WHERE time >'"+time+"'  and equipmentSpecificName =~/"+equipNumber[0]+"子阵/ and equipmentSpecificName =~/逆变器"+equipNumber[1]+"/  and equipmentSpecificName =~/"+Integer.parseInt(equipNumber[2])+"汇流箱/  and equipmentIndexName =~/路电流/ group by time(2m)";
//        List<IndicatorsDto> dataList = influxDButils.getListData(sql, IndicatorsDto.class);
//        List<IndicatorsDto> timeList = influxDButils.getListDataAll(timeSql, IndicatorsDto.class);
//
//        Map<String, List<IndicatorsDto>> timeMap = timeList.stream().collect(Collectors.groupingBy(IndicatorsDto::getTime, LinkedHashMap::new, Collectors.toList()));
//        Map<String, List<IndicatorsDto>> data = dataList.stream().collect(Collectors.groupingBy(IndicatorsDto::getEquipmentIndexName, LinkedHashMap::new, Collectors.toList()));
//        List<  Map<String,Object>> seriesData = new ArrayList<>();
//        for (String s : data.keySet()) {
//            Map<String,Object> map = new HashMap<>();
//            List<String> value = data.get(s).stream().map(IndicatorsDto::getValue).collect(Collectors.toList());
//            map.put("data",value);
//            seriesData.add(map);
//        }
//        Map<String,Object> map = new HashMap<>();
//        map.put("seriesData", seriesData);
//        map.put("axisData",timeMap.keySet());
//        return map;
//    }


//    public void getListByNbq(String gatewayId,String werks,String stationId){
//        String sql = " SELECT * FROM indicators_"+gatewayId+" WHERE equipmentIndexName ='总直流功率' and frontModule = '逆变器'";
//        String sql1 = " SELECT * FROM indicators_"+gatewayId+" WHERE equipmentIndexName ='有功功率' and  frontModule = '逆变器'";
//        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
//        List<IndicatorsDto> listData1 = influxDButils.getListData(sql1, IndicatorsDto.class);
//        // 将两组数据合并成一个集合中 将总直流功率数据 放入 另一个集合的valueLable中
//        for (IndicatorsDto listDatum : listData) {
//            for (IndicatorsDto indicatorsDto : listData1) {
//                if (indicatorsDto.getEquipmentNumber().equals(listDatum.getEquipmentNumber())){
//                    indicatorsDto.setValueLabel(listDatum.getValue());
//                }
//            }
//        }
//        List< Map<String, String>> maps = new ArrayList<>();
//        Set<String> nums = new HashSet<>();
//        //此处组装数据 每一个Map代表一个逆变器
//        for (IndicatorsDto indicatorsDto : listData1) {
//           int num = Integer.parseInt(indicatorsDto.getEquipmentNumber().substring(0, 2));
//            nums.add(String.valueOf(num));
//            Map<String, String> map = new HashMap<>();
//            String equipNum = indicatorsDto.getEquipmentNumber();
//            String number = equipNum.substring(equipNum.length() - 1);
//            map.put("titie",String.valueOf(num));
//            map.put("titie"+number,equipNum);
//            map.put("value"+number,indicatorsDto.getValue());
//            map.put("valueLabel"+number,indicatorsDto.getValueLabel());
//            maps.add(map);
//        }
//        TpriDmpDatabook tpriDmpDatabook = tpriDmpDatabookServiceImpl.getTpriDmpDatabookByDataName("集电线");
//        List<Map<String,Object>> dataMaps = sjglZsjZsbtzServiceImpl.sjglZsjZsbtzMapper.getStationInfoMapByStationGFWerks(werks, tpriDmpDatabook.getDataid().toString());
//        int i = 0;
//        //逆变器需要根据所属集电线分类组装 下面循环是将同一子阵下的不同逆变器组装为消息数据
//        for (Map<String, Object> dataMap : dataMaps) {
//            List<Map<String,String>> statusMaps = new ArrayList<>();
//            String equipNum = dataMap.get("equipNum").toString();
//            for (String num : nums) {
//                Map<String, String> map = new HashMap<>();
//                map.put("titie","#"+num);
//                for (Map<String, String> stringMap : maps) {
//                    if (stringMap.get("titie").equals(num)){
//                        map.putAll(stringMap);
//                    }
//                }
//                if (equipNum.contains(num)){
//                    statusMaps.add(map);
//                }
//            }
//            IPage<Map<String,String>> result = new Page<>();
//            result.setRecords(statusMaps);
//            result.setCurrent(1);
//            result.setTotal(statusMaps.size());
//            i += 1;
//            try {
//                emqKeeper.getMqttClient().publish(stationId+"/fj/group"+i,JSON.toJSONString(result).getBytes(),0,false);
//            } catch (MqttException e) {
//                log.info("消息发送失败");
//                e.printStackTrace();
//            }
//        }
//
//    }




//    @Override
//    public Map<String, Object> partofWaring3D(String stationId, String equipNum) {
//        Map<String,Object> resultMap=new HashMap<>();
//        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
//        String querySql = "SELECT * FROM indicators_"+stationBasic.getFanGatewayId()+" WHERE equipmentNumber = '"+equipNum+"' and equipmentIndexName =~/实时故障/";
//        List<IndicatorsDto> indicatorsDtoList  = influxDButils.getListData(querySql,IndicatorsDto.class);
//        //获取风机型号
//        String type = indicatorsDtoList.get(0).getEquipmentSpecificName().substring(0,5);
//        List<String> sytemNames =Arrays.asList("发电机系统","机舱与塔筒系统","变流与主控系统","偏航与液压系统","叶轮系统");
//        List<SystemEnum> systemEnumListAll = systemEnumMapper.selectList(new QueryWrapper<SystemEnum>().isNotNull("system_name"));
//        sytemNames.forEach(name->{
//            resultMap.put(name,false);
//            List<SystemEnum> systemEnumList = systemEnumListAll.stream().filter(systemEnum -> systemEnum.getSyetemName().equals(name)).collect(Collectors.toList());
//            outer:for(SystemEnum systemEnum:systemEnumList) {
//                for (IndicatorsDto indicatorsDto : indicatorsDtoList) {
//                    if (indicatorsDto.getEquipmentSpecificName().contains(systemEnum.getCode()) && indicatorsDto.getValue().equals(systemEnum.getEunmValue())) {
//                        resultMap.put(name, true);
//                        break outer;
//                    }
//                }
//            }
//        });
//        return resultMap;
//    }

    public void  sendMqttByRanking( List< Map<String,Object>> list,String code,String topic){

        //发送全国数据消息
        List<Map<String, Object>> maps = mapListToSort(list);
        List<Map<String, Object>> resultList = maps.stream().limit(5).collect(Collectors.toList());
        IPage<Map<String,Object>> result = new Page<>();
        result.setRecords(resultList);
        result.setCurrent(1);
        result.setTotal(resultList.size());
        try {
            emqKeeper.getMqttClient().publish(topic+"/"+code,JSON.toJSONString(result).getBytes(),0,false);
        } catch (MqttException e) {
            e.printStackTrace();
        }


        //先发送区域消息
        List<StationCacheInfoDto> listStationCacheInfoDto = commonServiceImpl.getListStationCacheInfoDto();
        Map<String, List<StationCacheInfoDto>> belongAreaList = listStationCacheInfoDto.stream().collect(Collectors.groupingBy(StationCacheInfoDto::getAreaCode));
        for (String s : belongAreaList.keySet()) {
            List<String> ids = belongAreaList.get(s).stream().map(StationCacheInfoDto::getFanGatewayId).collect(Collectors.toList());
            String idStrings = String.join(",", ids);
            List<Map<String, Object>> dataList = list.stream().filter(e -> idStrings.contains(e.get("gateWayId").toString())).collect(Collectors.toList());
            List<Map<String, Object>> data =  mapListToSort(dataList).stream().limit(5).collect(Collectors.toList());
            IPage<Map<String,Object>> resultMap = new Page<>();
            resultMap.setRecords(data);
            resultMap.setCurrent(1);
            resultMap.setTotal(data.size());
            try {
                emqKeeper.getMqttClient().publish(topic+"/"+code+"/"+s,JSON.toJSONString(resultMap).getBytes(),0,false);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

    }

        List< Map<String,Object>>   mapListToSort(List< Map<String,Object>> list){

            list.stream().sorted((o1,o2)->{
                double o1Num = Double.parseDouble(o1.get("value").toString());
                double o2Num = Double.parseDouble(o2.get("value").toString());
                if ((o1Num-o2Num)<0){
                    return -1;
                }else   if ((o1Num-o2Num)>0){
                    return 1;
                }else {
                    return 0;
                }
            });
            return list;
     }


    public Map<String, Object>  generatingCapacity (String gatewayId,String query){
//        String querySql = " SELECT * FROM indicators_"+gatewayId+" WHERE equipmentIndexName=~/发电量/";
//        if (null != query){
//            querySql = querySql + " "+  query;
//        }
//        List<IndicatorsDto> queryList  = influxDButils.getListData(querySql,IndicatorsDto.class);
//        Map<String, List<IndicatorsDto>> maps = queryList.stream().collect(Collectors.groupingBy(IndicatorsDto::getEquipmentIndexName));
//        Map<String, Object> hashMap = new HashMap<>();
//        for (String s : maps.keySet()) {
//            List<IndicatorsDto> indicatorsDtos = maps.get(s);
//            Double  totalvalue =indicatorsDtos.stream().filter(obj -> !ObjectUtils.isEmpty(obj.getValue())).mapToDouble(l->Double.parseDouble(l.getValue())).sum();
//            hashMap.put(s,totalvalue);
//        }
//        return hashMap;
        Map<String, List<String>> queryCondtion = new HashMap<>();
        queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("日发电量", "月发电量", "年发电量"));
        queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(gatewayId));
        Map<String, String> likeQuerCondtion = new HashMap<>();
        if(query!=null){
            queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName,CommonConstans.taiHeGenIndicator);
        }
        List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
        Double powerOfDay = 0.0000;
        Double powerOfMonth = 0.0000;
        Double powerOfAnnual = 0.0000;
        if(result!=null) 
        {
            if(ObjectUtils.isEmpty(query)){
                powerOfDay = powerOfDay + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量"));
                powerOfMonth = powerOfMonth + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量"));
                powerOfAnnual = powerOfAnnual + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量"));
            }else {
                powerOfDay = powerOfDay + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay));
                powerOfMonth = powerOfMonth + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth));
                powerOfAnnual = powerOfAnnual + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear));
            }

        }
  
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("日发电量",powerOfDay);
        hashMap.put("月发电量",powerOfMonth);
        hashMap.put("年发电量",powerOfAnnual);
        return hashMap;
    }

    public String getEquipCount(String gatewayId, String stationType) {
        Map<String, List<String>> queryCondtion1 = new HashMap<>();
        if (stationType.equals("FDZ")) {
            queryCondtion1.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("有功功率"));
        } else {
            queryCondtion1.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("运行"));
        }
        queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(gatewayId));
        List<ESEquipments> equipNumList = commonServiceImpl.getListDataByCondtions(queryCondtion1, null, ESEquipments.class);
        if (!CollectionUtils.isEmpty(equipNumList)) {
            return equipNumList.size() + "";
        }
        return "0";
    }

    public Double keepFourdecimalPlaces(Double param) {
        return Double.valueOf(String.format("%.4f", param));
    }


}




