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

import com.alibaba.fastjson.JSON;
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.DateUtils;
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.MonitorFanIndicator;
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.dto.*;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.SjglZsjZsbtz;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.TemporaryData;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.TpriDmpDatabook;
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.utils.InfluxDButils;
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.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: tw
 * @createDate: 2023/7/3
 */
@Service
@EnableScheduling
@Slf4j
public class MonitorFanIndicatorImpl implements IMonitorFanIndicator {

    @Autowired
    private MonitorFanIndicatorMapper monitorFanIndicatorregionMapper;

    @Autowired
    private StationBasicMapper stationBasicMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    InfluxDButils influxDButils;

    @Autowired
    SystemEnumMapper systemEnumMapper;


    @Autowired
    SjglZsjZsbtzServiceImpl sjglZsjZsbtzServiceImpl;

    @Autowired
    TpriDmpDatabookServiceImpl tpriDmpDatabookServiceImpl;

    @Autowired
    TemporaryDataMapper temporaryDataMapper;

    @Autowired
    TemporaryDataServiceImpl temporaryDataService;

    @Autowired
    EmqKeeper emqKeeper;


    @Override
    public void UpdateMonitorFanIndicator(List<IndexDto> list) {

        monitorFanIndicatorregionMapper.UpdateMonitorFanIndicator(list);


    }

    @Override
    public ResultsData getNationWideInfo(int current, int size, String stationBasicId, String equipmentNumber) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationBasicId);
        String gateway = stationBasic.getFanGatewayId();
        Page<IndexDto> page = new Page<IndexDto>();
        page.setCurrent(current);
        page.setSize(size);
        String table = gateway;
        StringBuffer querysql = new StringBuffer("SELECT createdTime ,equipmentNumber,gatewayId,address,valueLabel,equipmentSpecificName,value FROM indicators_%s  WHERE isAlarm='1'   and value!='0.0'  and  gatewayId=  %s ORDER BY time  desc   LIMIT %d OFFSET %d  ");
        StringBuffer querysqlcount = new StringBuffer("SELECT count(value) FROM indicators_%s  WHERE isAlarm='1'   and value!='0.0'  and  gatewayId=   %s ");
        if (StringUtils.isNotEmpty(equipmentNumber)) {
            String date = "'%s'  and equipmentNumber = '%s' ";
            gateway = String.format(date, gateway, equipmentNumber);
        } else {
            gateway = String.format("'%s'", gateway);
        }
        String querysqln = String.format(querysql.toString(), table, gateway, (int) page.getSize(), (int) (page.getCurrent() - 1) * page.getSize());
        String querysqlcountn = String.format(querysqlcount.toString(), table, gateway);
        //每个分机的指标数据
        List<IndexDto> list = influxDButils.getListData(querysqln, IndexDto.class);
        List<IndexDto> list1 = influxDButils.getListData(querysqlcountn, IndexDto.class);
        page.setRecords(list);
        //构建平台数据
        DataGridMock DataGridMock = new DataGridMock(current, list1 != null ? list1.get(0).getCount() : 0, false, current, list);
        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();
        Page<IndexDto> page = new Page<IndexDto>();
        page.setCurrent(current);
        page.setSize(size);
        String table = gateway;
        StringBuffer querysql = new StringBuffer("SELECT createdTime ,gatewayId,address,valueLabel,equipmentSpecificName,value FROM iot_data_%s  WHERE isAlarm='1'   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  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, (int) page.getSize(), (int) (page.getCurrent() - 1) * page.getSize());
        String querysqlcountn = String.format(querysqlcount.toString(), table, gateway);
        //每个分机的指标数据
        List<IndexDto> list = influxDButils.getListData(querysqln, IndexDto.class);
        List<IndexDto> list1 = influxDButils.getListData(querysqlcountn, IndexDto.class);
        page.setRecords(list);
        //构建平台数据
        DataGridMock DataGridMock = new DataGridMock(current, list1 != null ? list1.get(0).getCount() : 0, false, current, list);
        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 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, 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, unit FROM \"indicators_%s\" WHERE equipmentNumber = '%s' and frontModule =~/%s/", stationBasic.getFanGatewayId(), equipNum, frontModule);
        }
        List<IndexDto> influxDBList = influxDButils.getListData(sql, IndexDto.class);
        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());
        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("通讯中断");
            }
        });

        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());
        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("通讯中断");
            }
        });
        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) {
        StationBasic stationBasic = getOneByStationNumber(stationId);
        String sql = String.format("SELECT equipmentNumber, equipmentSpecificName, equipmentIndexName  FROM \"indicators_%s\" WHERE equipmentNumber = '%s' 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);
            return influxDBList.get(0);
        }
        return new 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 null;
    }


    public  Map<String,Object> getDetailsWindSpeedAll(String gatewayId){
        List<Map<String, String>> 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<>();

        for (Map<String, String> stringStringMap : list) {
            if (stringStringMap.get("equipmentIndexName").equals("有功功率")){
                values.add(stringStringMap.get("value"));
            }else {
                valueList.add(stringStringMap.get("value"));
                time.add(stringStringMap.get("createdTime"));
            }
        }

        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);
        map2.put("data", valueList);
        seriesData.add(map1);
        seriesData.add(map2);
        map.put("seriesData", seriesData);
        map.put("axisData",time);

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





    @Scheduled(cron = "0 */5 * * * ?")
    private void schedTaskData(){

        LambdaQueryWrapper<StationBasic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseEntity::getIsDelete,false);
        List<StationBasic> stationBasics = stationBasicMapper.selectList(wrapper);
        for (StationBasic stationBasic : stationBasics) {
            timingTemporarysSorageData(stationBasic.getFanGatewayId());
        }
    }

    @Scheduled(cron = "0 57 23 * * ?")
    private void deleteTemporaryData(){
        QueryWrapper<TemporaryData> wrapper = new QueryWrapper<>();
        temporaryDataMapper.delete(wrapper);
    }






    public  void timingTemporarysSorageData(String gatewayId){
        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 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 sql =   "    SELECT displayName  , value as state   FROM indicators_"+gatewayId+" WHERE  frontModule =~/"+frontModule+"/ and systemType = '"+systemType+"'";
        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",statusMap.get("displayName"));
                statusMap.put("title",statusMap.get("displayName"));
                statusMap.put("state",statusMap.get("state").equals("true")? 1:0);
                statusMap.put("title",statusMap.get("state").equals("true")?"断":"通");
                statusMaps.add(statusMap);
            }
        return  statusMaps;
    }



    public void getStatusJDX(String gatewayId, String dataName, String werks,String stationId){
        String sql =   " SELECT * FROM indicators_"+gatewayId+"  WHERE frontModule =~/集电线路/ and systemType = '光字牌'";
        List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
        TpriDmpDatabook tpriDmpDatabookByDataName = tpriDmpDatabookServiceImpl.getTpriDmpDatabookByDataName(dataName);
        List<SjglZsjZsbtz> sjglZsjZsbtzList = sjglZsjZsbtzServiceImpl.getSjglZsjZsbtzList(tpriDmpDatabookByDataName.getDataid(), werks);
        List<Map<String,Object>> statusMaps = new ArrayList<>();

        Map<String, List<IndicatorsDto>> collect = listData.stream().collect(Collectors.groupingBy(IndicatorsDto::getFrontModule));
        for (String s : collect.keySet()) {
            Map<String, Object> statusMap = new HashMap<>();
            String[] split = s.replace("#", "").replace("保护测控装置", "").split("集电线路");
            for (SjglZsjZsbtz listDatum : sjglZsjZsbtzList) {

                statusMap.put("title",listDatum.getSbmc().replace("风机系统",""));
                String[] strings = listDatum.getSbbm().split(" ");
                if (Integer.parseInt(strings[1]) == Integer.parseInt(split[0])) {
                    String sql1 =   " SELECT * FROM indicators_"+gatewayId+" WHERE  displayName = '"+split[1]+"断路器合位'";
                    List<IndicatorsDto> listData1 = influxDButils.getListData(sql1, IndicatorsDto.class);
                    statusMap.put("type",listData1.get(0).getValue());
                    statusMap.put("position",split[1]+"开关位置");
                }
                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("power",listDatum.getValue());
                        map.put("windSpeed",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 = monitorFanIndicatorregionMapper.getBoosterStationInfo(stationBasic.getFanGatewayId());
        return boosterStationInfo;
    }

    public ResultsData runningPageByStationId(int current, int size, String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        String baseSql = "SELECT equipmentNumber, value FROM \"indicators_%s\" where equipmentIndexName = '%s'";
        String windSql = String.format(baseSql, stationBasic.getFanGatewayId(), "风向角");
        List<IndicatorsDto> windSqlList = influxDButils.getListDataAll(windSql,IndicatorsDto.class);
        String powerSql = String.format(baseSql, stationBasic.getFanGatewayId(), "有功功率");
        List<IndicatorsDto> powerSqlList = influxDButils.getListDataAll(powerSql,IndicatorsDto.class);
        Map<String, String> powerSqlMap = powerSqlList.stream().collect(Collectors.toMap(IndicatorsDto::getEquipmentNumber, IndicatorsDto::getValue));
        String windSpeedSql = String.format(baseSql, stationBasic.getFanGatewayId(), "瞬时风速");
        List<IndicatorsDto> windSpeedSqlList = influxDButils.getListDataAll(windSpeedSql,IndicatorsDto.class);
        Map<String, String> windSpeedSqlMap = windSpeedSqlList.stream().collect(Collectors.toMap(IndicatorsDto::getEquipmentNumber, IndicatorsDto::getValue));

        String electricitySql = String.format(baseSql, stationBasic.getFanGatewayId(), "日发电量");
        List<IndicatorsDto> electricitySqlList = influxDButils.getListDataAll(electricitySql,IndicatorsDto.class);
        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", 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 void getAnalogQuantityInfo(String gatewayId, String stationId) {
        List<Map<String, String>> boosterStationInfo = monitorFanIndicatorregionMapper.getBoosterStationInfo(gatewayId);
        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/ ", gatewayId, "模拟量", map.get("boosterName"));
            List<IndicatorsDto> listData = influxDButils.getListData(sql, IndicatorsDto.class);
            listData.forEach(item -> {
                if (StringUtils.isNotEmpty(item.getUnit())) {
                    item.setDisplayName(String.format("%s(%s)", item.getDisplayName(), item.getUnit()));
                }
            });
            IPage<IndicatorsDto> result = new Page<>();
            result.setRecords(listData);
            result.setCurrent(1);
            result.setTotal(listData.size());
            try {
                emqKeeper.getMqttClient().publish(String.format("%s/%s/%s", stationId, map.get("boosterCode"), "mnl"), JSON.toJSONString(result).getBytes(),0,false);
            } catch (MqttException e) {
                log.info("消息发送失败");
                e.printStackTrace();
            }
        }
    }
}

