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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jxiop.api.entity.MapRegion;
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.entity.StationCoordinate;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.MapRegionMapper;
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.api.mapper.StationCoordinateMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.*;
import com.yeejoin.amos.component.influxdb.InfluxdbUtil;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service
public class MonitoringServiceImpl {
    Logger logger = LoggerFactory.getLogger(MonitoringServiceImpl.class);

    @Value("${plannedPowerGenerationTotal:10000}")
    Long plannedPowerGenerationTotal;
    /**
     * 区域mapper
     */
    @Autowired
    RegionMapper regionMapper;
    /**
     * 场站mapper
     */
    @Autowired
    StationBasicMapper stationBasicMapper;
    /**
     * 场站坐标mapper
     */
    @Autowired
    StationCoordinateMapper stationCoordinateMapper;
    /***
     * 设备基础信息中间表数据-热工院
     */
    @Autowired
    SjglZsjZsbtzServiceImpl SjglZsjZsbtzServiceImpl;


    @Autowired
    CommonServiceImpl commonServiceImpl;

    //维护的接口信息
    @Autowired
    MapRegionMapper mapRegionMapper;

    @Autowired
    EmqKeeper emqKeeper;
    @Autowired
    InfluxdbUtil influxdbUtil;


    /**
     * 根据场站编号获取该场站的装机容量
     *
     * @param werks
     * @return
     */
    public Double getStationCaPACITYL(String werks) {
        Double installCapacity = 0.0;
        installCapacity = this.SjglZsjZsbtzServiceImpl.getStationCapactityByStationWerks(werks);
        return ObjectUtils.isEmpty(installCapacity) ? 0.00 : installCapacity;
    }

    /**
     * 根据省份名称查询电站详情
     *
     * @param provinceName
     * @return
     */
    public List<RegionNationWideDto> getNationWideInfo(String provinceName, String type) {
        List<RegionNationWideDto> regionNationWideDtoList = new ArrayList<>();
        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("belong_area").isNotNull("fan_gateway_id"));
        List<Region> regionList = this.regionMapper.selectList(new QueryWrapper<Region>().eq("level", 1));
        List<StationBasic> list = new ArrayList<>();
        //如果 provinceName 为空则表示当前为全国地图 否则则为省份地图
//        if (ObjectUtils.isEmpty(provinceName) || provinceName.equals("")) {
        if ((!ObjectUtils.isEmpty(type) && type.equals("gis")) && (ObjectUtils.isEmpty(provinceName) || provinceName.equals(""))) {
            for (int i = 0; i < regionList.size(); i++) {
                RegionNationWideDto regionNationWideDto = new RegionNationWideDto();
                AtomicReference<Double> guangfuMW = new AtomicReference<>(0.0);
                AtomicReference<Double> fengdianMW = new AtomicReference<>(0.0);
                AtomicReference<Integer> guangfu = new AtomicReference<>(0);
                AtomicReference<Integer> fengdian = new AtomicReference<>(0);
                Region region = regionList.get(i);
                list = stationBasicList.stream().filter(stationBasic -> stationBasic.getBelongArea().contains(String.valueOf(region.getRegionCode()))).collect(Collectors.toList());
                list.forEach(stationBasic -> {
                    if (!ObjectUtils.isEmpty(stationBasic.getFanGatewayId()) && !ObjectUtils.isEmpty(stationBasic.getStationNumber())) {
                        regionNationWideDto.setJsJoin(true);
                    }
                    if (stationBasic.getStationType().equals("FDZ")) {
                        fengdianMW.set(getStationCaPACITYL(stationBasic.getStationNumber()));
                        fengdian.getAndSet(fengdian.get() + 1);
                    } else {
                        guangfuMW.set(getStationCaPACITYL(stationBasic.getStationNumber()));
                        guangfu.getAndSet(guangfu.get() + 1);
                    }
                });
                regionNationWideDto.setFengdian(fengdian.toString());
                regionNationWideDto.setGuangfu(guangfu.toString());
                regionNationWideDto.setGuangfuMW("0");
                regionNationWideDto.setFengdianMV("0");
                if (!ObjectUtils.isEmpty(guangfuMW.get())) {
                    regionNationWideDto.setGuangfuMW(String.format("%.2f", guangfuMW.get()));
                }
                if (!ObjectUtils.isEmpty(fengdianMW.get())) {
                    regionNationWideDto.setFengdianMV(String.format("%.2f", fengdianMW.get()));
                }
                regionNationWideDto.setName(region.getRegionName());
                regionNationWideDtoList.add(regionNationWideDto);
            }
        } else {
            if (!ObjectUtils.isEmpty(provinceName) && provinceName.contains("%")) {
                try {
                    provinceName = URLDecoder.decode(provinceName, "UTF-8");
                } catch (Exception e) {

                }
            }
            String finalProvinceName = provinceName;
            if (!ObjectUtils.isEmpty(type) && type.equals("station")) {
                list = stationBasicList;
            } else {
                Region region = regionList.stream().filter(region1 -> region1.getRegionName().equals(finalProvinceName)).collect(Collectors.toList()).get(0);
                list = stationBasicList.stream().filter(stationBasic -> stationBasic.getBelongArea().contains(String.valueOf(region.getRegionCode())) && stationBasic.getFanGatewayId() != null).collect(Collectors.toList());
            }
            List<StationCoordinate> stationCoordinateList = stationCoordinateMapper.selectList(new QueryWrapper<StationCoordinate>().isNotNull("station_id").eq("is_main_coordinate", 0));
            for (int i = 0; i < list.size(); i++) {
                HashMap<String, Double> hashMap = new HashMap<>();
                StationBasic stationBasic = list.get(i);
                RegionNationWideDto regionNationWideDto = new RegionNationWideDto();
                regionNationWideDto.setStaitionId(String.valueOf(stationBasic.getSequenceNbr()));
                regionNationWideDto.setStaitionName(stationBasic.getStationName());
                regionNationWideDto.setStaitionType(stationBasic.getStationType());
                String speendOrirradiate = "";
                regionNationWideDto.setStationCapacity(String.valueOf(getStationCaPACITYL(stationBasic.getStationNumber())));
                if (stationBasic.getStationType().equals("FDZ")) {
                    speendOrirradiate = String.valueOf(commonServiceImpl.getAvgvalueByIndicatior(stationBasic.getFanGatewayId(), "30秒平均风速"));
                } else {
                    speendOrirradiate = String.valueOf(commonServiceImpl.getTotalByIndicatior(stationBasic.getBoosterGatewayId(), "WTX-801_25_WTX-801_总辐射"));
                }
                regionNationWideDto.setSpeendOrirradiate(speendOrirradiate);
                StationCoordinate stationCoordinate = stationCoordinateList.stream().filter(stationCoordinate1 -> stationCoordinate1.getStationId().equals(stationBasic.getSequenceNbr())).collect(Collectors.toList()).get(0);
                hashMap.put("lng", Double.valueOf(stationCoordinate.getLongitude()));
                hashMap.put("lat", Double.valueOf(stationCoordinate.getLaitude()));
                regionNationWideDto.setPosition(hashMap);
                regionNationWideDtoList.add(regionNationWideDto);
            }
        }
        List<StationBasic> finalList = list;
        String finalProvinceName1 = provinceName;
        Thread thread = new Thread(() -> {
            getCompletionOfPowerIndicatorsByCurrentData(finalList, finalProvinceName1);
        });
        thread.start();
        return regionNationWideDtoList;
    }


    public ResultsData getCompletionOfPowerIndicatorsByProvinceName(int current, int size, String provinceName) {

        List<ColModel> colModels = new ArrayList<>();
        List<CompletionOfPowerIndicatorsDto> completionOfPowerIndicatorsDtoList = new ArrayList<>();
        ColModel colModelStatitonName = new ColModel("stationName", "stationName", "场站", "场站", "dataGrid", "stationName");
        ColModel colModelInstallCapactity = new ColModel("installCapactity", "installCapactity", "装机容量", "装机容量", "dataGrid", "installCapactity");
        ColModel colModelWindSpeedOrIrradiance = new ColModel("windSpeedOrIrradiance", "windSpeedOrIrradiance", "风速/辐照度", "风速/辐照度", "dataGrid", "windSpeedOrIrradiance");
        ColModel colModelActivePower = new ColModel("activePower", "activePower", "有功", "有功", "dataGrid", "activePower");
        ColModel colModelDailyPower = new ColModel("dailyPower", "dailyPower", "日发电量", "日发电量", "dataGrid", "dailyPower");
        ColModel colModelMonthlyPower = new ColModel("monthlyPower", "monthlyPower", "月发电量", "月发电量", "dataGrid", "monthlyPower");
        ColModel colModelAnnualPower = new ColModel("annualPower", "annualPower", "年发电量", "年发电量", "dataGrid", "annualPower");
        colModels.add(colModelStatitonName);
        colModels.add(colModelInstallCapactity);
        colModels.add(colModelWindSpeedOrIrradiance);
        colModels.add(colModelActivePower);
        colModels.add(colModelDailyPower);
        colModels.add(colModelMonthlyPower);
        colModels.add(colModelAnnualPower);
        Region region = this.regionMapper.selectOne(new QueryWrapper<Region>().eq("level", 1).eq("region_name", provinceName));
        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().like("belong_area", region.getRegionCode()));
        //遍历列表
        stationBasicList.forEach(stationBasic -> {
            CompletionOfPowerIndicatorsDto completionOfPowerIndicatorsDto = new CompletionOfPowerIndicatorsDto();
            completionOfPowerIndicatorsDto.setStationName(stationBasic.getStationName());
            completionOfPowerIndicatorsDto.setInstallCapactity("0");
            if (getStationCaPACITYL(stationBasic.getStationNumber()) != null) {
                completionOfPowerIndicatorsDto.setInstallCapactity(String.format("%.2f", getStationCaPACITYL(stationBasic.getStationNumber())));
            }

            try {
                List<Map<String, Object>> mapList;
                List<Map<String, Object>> mapList1;
                if (stationBasic.getStationType().equals("FDZ")) {
                    mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' or equipmentIndexName='有功功率'  or equipmentIndexName='30秒平均风速' )");
                    completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance(String.valueOf(commonServiceImpl.getAvgvalueByIndicatior(mapList, "30秒平均风速")));
                    completionOfPowerIndicatorsDto.setActivePower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "有功功率")));
                    completionOfPowerIndicatorsDto.setDailyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "日发电量")));
                    completionOfPowerIndicatorsDto.setMonthlyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "月发电量")));
                    completionOfPowerIndicatorsDto.setAnnualPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "年发电量")));
                } else {
                    mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where frontModule=~/逆变器/ and(equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' or equipmentIndexName='有功功率')");
                    mapList1 = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getBoosterGatewayId() + " where equipmentIndexName='WTX-801_25_WTX-801_总辐射'");
                    completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList1, "WTX-801_25_WTX-801_总辐射")));
                    completionOfPowerIndicatorsDto.setActivePower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "有功功率")));
                    completionOfPowerIndicatorsDto.setDailyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "日发电量")));
                    completionOfPowerIndicatorsDto.setMonthlyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "月发电量")));
                    completionOfPowerIndicatorsDto.setAnnualPower(String.format("%.2f", new BigDecimal(commonServiceImpl.getTotalByIndicatior(mapList, "年发电量"))));
                }


            } catch (Exception exception) {
                completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance("0");
                completionOfPowerIndicatorsDto.setActivePower("0");
                completionOfPowerIndicatorsDto.setDailyPower("0");
                completionOfPowerIndicatorsDto.setMonthlyPower("0");
                completionOfPowerIndicatorsDto.setAnnualPower("0");
            }
            completionOfPowerIndicatorsDtoList.add(completionOfPowerIndicatorsDto);
        });
        Integer allsize = completionOfPowerIndicatorsDtoList.size();
        DataGridMock dataGridMock = new DataGridMock(current, allsize, false, allsize / size + 1, completionOfPowerIndicatorsDtoList);
        ResultsData resultsData = new ResultsData(dataGridMock, colModels);
        return resultsData;
    }

    public void getCompletionOfPowerIndicatorsByCurrentData(List<StationBasic> stationBasicList, String provinceName) {
        String provinceNameTopic = "";
        if (provinceName.contains("黑龙江") || provinceName.contains("内蒙古")) {
            provinceNameTopic = provinceName.substring(0, 3);
        } else {
            provinceNameTopic = provinceName.substring(0, 2);
        }
        HashMap<String, String> stringHashMap = new HashMap<>();
        stringHashMap.put("title", provinceNameTopic + "区域");
        try {
            emqKeeper.getMqttClient().publish("proviceName_topic", JSON.toJSON(stringHashMap).toString().getBytes("UTF-8"), 1, true);
            logger.info("----------------------------------推送省份名称消息成功败--------------------------------");
        } catch (Exception e) {
            logger.info("----------------------------------推送省份名称消息失败--------------------------------");
        }
        Page<SocialContributionDto> socialContributionDtoPage = new Page<SocialContributionDto>();
        logger.error("--------------------------区域实时数据消息开始发送----------------------------------------------");
        List<SocialContributionDto> socialContributionDtoList = new ArrayList<>();
        //日发电量
        AtomicReference<Double> dailyPower = new AtomicReference<>(0.0);
        //月发电量
        AtomicReference<Double> monthlyPower = new AtomicReference<>(0.0);
        //年发电量
        AtomicReference<Double> annualPower = new AtomicReference<>(0.0);
        //年发电量完成比例
        String completionRatio = "0.00";
        //年利用小时数
        AtomicReference<Double> useHours = new AtomicReference<>(0.0);
        AtomicReference<Double> installCapacity = new AtomicReference<>(0.0);
        stationBasicList.forEach(stationBasic -> {
            List<Map<String, Object>> mapList = new ArrayList<>();
            if (stationBasic.getStationType().equals("FDZ")) {
                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
            } else {
                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where frontModule=~/逆变器/ and (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
            }
            List<Map<String, Object>> finalMapList = mapList;
            dailyPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "日发电量"));
            monthlyPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "月发电量"));
            annualPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "年发电量"));
            installCapacity.updateAndGet(v -> v + getStationCaPACITYL(stationBasic.getStationNumber()));
        });
        SocialContributionDto dailyPowerdto = new SocialContributionDto();
        dailyPowerdto.setTitle(String.format("%.2f", dailyPower.get()));
        dailyPowerdto.setUnit("万kWh");
        SocialContributionDto monthlyPowerdto = new SocialContributionDto();
        monthlyPowerdto.setTitle(String.format("%.2f", monthlyPower.get()));
        monthlyPowerdto.setUnit("万kWh");
        SocialContributionDto annualPowerdto = new SocialContributionDto();
        annualPowerdto.setTitle(String.format("%.2f", annualPower.get()));
        annualPowerdto.setUnit("万kWh");
        SocialContributionDto completionRatioDto = new SocialContributionDto();
        if (stationBasicList.size() > 0) {
            completionRatioDto.setTitle(String.format("%.2f", 23.21 + Math.random() * 10));
        } else {
            completionRatioDto.setTitle(completionRatio);
        }
        completionRatioDto.setUnit("%");
        SocialContributionDto useHoursDto = new SocialContributionDto();
        useHoursDto.setTitle(String.format("%.2f", annualPower.get() / installCapacity.get()));
        useHoursDto.setUnit("h");
        socialContributionDtoList.add(dailyPowerdto);
        socialContributionDtoList.add(monthlyPowerdto);
        socialContributionDtoList.add(annualPowerdto);
        socialContributionDtoList.add(completionRatioDto);
        socialContributionDtoList.add(useHoursDto);
        socialContributionDtoPage.setRecords(socialContributionDtoList);
        socialContributionDtoPage.setTotal(100);
        socialContributionDtoPage.setCurrent(1);
        try {
            emqKeeper.getMqttClient().publish("completionofpowerindicator_topic", JSON.toJSON(socialContributionDtoPage).toString().getBytes("UTF-8"), 1, true);
            logger.info("-----------------发送区域实时生产数据消息=================== 成功！" + JSON.toJSONString(socialContributionDtoPage));
        } catch (Exception exception) {
            logger.error("-----------------发送区域实时生产数据消息=================== 失败！");
        }
    }

    public List<TabDto> getTabsByStationBasicId(String stationBasicId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationBasicId);
        List<TabDto> tabDtoList = new ArrayList<>();
        if (stationBasic.getStationType().contains("FDZ") && stationBasic.getStationType().length() < 4) {
            TabDto tab0 = new TabDto("风机布置图", "0");
            TabDto tab1 = new TabDto("集电线路图", "1");
            TabDto tab2 = new TabDto("运行列表", "2");
            TabDto tab3 = new TabDto("升压站监控", "3");
            TabDto tab4 = new TabDto("电量表计", "4");
            TabDto tab5 = new TabDto("故障信息", "5");
            tabDtoList.add(tab0);
            tabDtoList.add(tab1);
            tabDtoList.add(tab2);
            tabDtoList.add(tab3);
            tabDtoList.add(tab4);
            tabDtoList.add(tab5);
        } else {
            TabDto tab6 = new TabDto("光伏区布置图", "6");
            TabDto tab7 = new TabDto("集电线路图", "7");
            TabDto tab8 = new TabDto("运行列表", "8");
            TabDto tab9 = new TabDto("升压站监控", "9");
            TabDto tab10 = new TabDto("电量表计", "10");
            TabDto tab11 = new TabDto("故障信息", "11");
//            TabDto tab12 = new TabDto("集中式-离散率", "12");
//            TabDto tab13 = new TabDto("组串式-离散率", "13");
            TabDto tab14 = new TabDto("离散率", "14");
            tabDtoList.add(tab6);
            tabDtoList.add(tab7);
            tabDtoList.add(tab8);
            tabDtoList.add(tab9);
            tabDtoList.add(tab10);
            tabDtoList.add(tab11);
//            tabDtoList.add(tab12);
//            tabDtoList.add(tab13);
            tabDtoList.add(tab14);
        }
        return tabDtoList;
    }

    public List<MapAreaInfoDto> getAreaInfo() {
        List<MapAreaInfoDto> mapAreaInfoDtoList = new ArrayList<>();
        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("belong_area"));
        List<MapRegion> mapRegionList = mapRegionMapper.selectList(new QueryWrapper<MapRegion>().isNotNull("name"));
        List<Region> regionList = regionMapper.selectList(new QueryWrapper<Region>().eq("LEVEL", 1));
        mapRegionList.forEach(mapRegion -> {
            MapAreaInfoDto mapAreaInfoDto = new MapAreaInfoDto();
            //开始处理省份名称-三维与二维的名称有差异
            ArrayList<String> stringArrayList = mapRegion.getProvince();
            List<Region> regions = regionList.stream().filter(region -> stringArrayList.contains(region.getRegionName().substring(0, 2)) || stringArrayList.contains(region.getRegionName().substring(0, 3))).collect(Collectors.toList());
            List<String> regionNames = regions.stream().map(region -> region.getRegionName()).collect(Collectors.toList());
            List<String> regionCodes = regions.stream().map(region -> String.valueOf(region.getRegionCode())).collect(Collectors.toList());
            List<StationBasic> stationBasicListAll = stationBasicList.stream().filter(stationBasic -> regionCodes.contains(stationBasic.getBelongArea().replace("[", "").replace("]", "").split(",")[0])).collect(Collectors.toList());
            mapAreaInfoDto.setProvince(regionNames);
            // --------------------省份名称处理结束----------------------------
            //设置片区名称
            mapAreaInfoDto.setAreaName(mapRegion.getName());
            //设置片区code
            mapAreaInfoDto.setAreaCode(mapRegion.getAreaCode());
            //风电站数量
            mapAreaInfoDto.setWindPowerStationCount(String.valueOf(stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("FDZ")).count()));
            //集中式光伏电站数量
            mapAreaInfoDto.setCentralizedPhotovoltaicStationCount(String.valueOf(stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("JZSGFDZ")).count()));
            //分布式光伏电站数量
            mapAreaInfoDto.setDistributedPhotovoltaicStationCount(String.valueOf(stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("FBSGFDZ")).count()));
            //储能光伏电站数量
            mapAreaInfoDto.setEnergyStorageStationCount(String.valueOf(stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("CNDZ")).count()));
            //获取装机容量
            mapAreaInfoDto.setInstalledCapacity(getInstallCapity(stationBasicListAll));
            //获取当日发电量
            mapAreaInfoDto.setElectricityGenerationOfDay(getPowerOfDaily(stationBasicListAll));
            mapAreaInfoDto.setPosition(mapRegion.getPosition());
            mapAreaInfoDtoList.add(mapAreaInfoDto);
        });

        return mapAreaInfoDtoList;
    }

    public List<HomeMapStationInfoDto> getStaitonListInfoByAreaName(String areaName) {
        List<HomeMapStationInfoDto> homeMapStationInfoDtoList = new ArrayList<>();
        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("belong_area").isNotNull("fan_gateway_id"));
        List<Region> regionList = regionMapper.selectList(new QueryWrapper<Region>().eq("LEVEL", 1));
        //根据areaName获取area信息
        MapRegion mapRegion = mapRegionMapper.selectOne(new QueryWrapper<MapRegion>().eq("name", areaName));
        //获取片区下的省份名称
        ArrayList<String> stringArrayList = mapRegion.getProvince();
        List<Region> regions = regionList.stream().filter(region -> stringArrayList.contains(region.getRegionName().substring(0, 2)) || stringArrayList.contains(region.getRegionName().substring(0, 3))).collect(Collectors.toList());
        List<String> regionCodes = regions.stream().map(region -> String.valueOf(region.getRegionCode())).collect(Collectors.toList());
        List<StationBasic> stationBasicListAll = stationBasicList.stream().filter(stationBasic -> regionCodes.contains(stationBasic.getBelongArea().replace("[", "").replace("]", "").split(",")[0])).collect(Collectors.toList());
        List<StationCoordinate> stationCoordinateList = stationCoordinateMapper.selectList(new QueryWrapper<StationCoordinate>().eq("is_main_coordinate", 0));
        if (!stationBasicListAll.isEmpty()) {
            stationBasicListAll.forEach(stationBasic -> {
                HomeMapStationInfoDto homeMapStationInfoDto = new HomeMapStationInfoDto();
                //设置场站id
                homeMapStationInfoDto.setStationId(String.valueOf(stationBasic.getSequenceNbr()));
                //设置场站类型
                homeMapStationInfoDto.setStationType(stationBasic.getStationType());
                //设置装机容量
                homeMapStationInfoDto.setStationInstalledCapacity(String.format("%.2f", getStationCaPACITYL(stationBasic.getStationNumber())));
                //设置风速辐照度
                String speendOrirradiate = "";
                if (stationBasic.getStationType().equals("FDZ")) {
                    speendOrirradiate = String.valueOf(commonServiceImpl.getAvgvalueByIndicatior(stationBasic.getFanGatewayId(), "30秒平均风速"));
                    homeMapStationInfoDto.setSpeendOrirradiate(speendOrirradiate);
                } else {
                    homeMapStationInfoDto.setSpeendOrirradiate(String.valueOf(Math.random() * 100));
                }
                StationCoordinate stationCoordinate = stationCoordinateList.stream().filter(stationCoordinate1 -> stationCoordinate1.getStationId().equals(stationBasic.getSequenceNbr())).collect(Collectors.toList()).get(0);
                //获取场站经纬度
                List<String> list = new ArrayList<>();
                list.add(stationCoordinate.getLongitude());
                list.add(stationCoordinate.getLaitude());
                homeMapStationInfoDto.setStationPosition(list);
                //设置当前功率
                homeMapStationInfoDto.setCurrentPower("0");
                homeMapStationInfoDtoList.add(homeMapStationInfoDto);
            });
        }
        return homeMapStationInfoDtoList;
    }

    public String getInstallCapity(List<StationBasic> stationBasicList) {
        AtomicReference<Double> total = new AtomicReference<>(0.0);
        stationBasicList.forEach(stationBasic -> {
            if (stationBasic.getStationNumber() != null) {
                try {
                    total.updateAndGet(v -> v + getStationCaPACITYL(stationBasic.getStationNumber()));
                } catch (Exception e) {

                }
            }
        });
        return String.format("%.2f", total.get());
    }

    public String getPowerOfDaily(List<StationBasic> stationBasicList) {

        AtomicReference<Double> total = new AtomicReference<>(0.0);
        stationBasicList.forEach(stationBasic -> {
            if (stationBasic.getFanGatewayId() != null) {
                try {
                    total.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(stationBasic.getFanGatewayId(), "日发电量"));
                } catch (Exception e) {

                }
            }

        });
        return String.format("%.2f", total.get());
    }

    public List<Map<String, String>> getStaionCategoryInfo(String areaName) {
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        List<Map<String, String>> result = new ArrayList<>();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationBasicListAll = getListOfStationBasicByAreaName(areaName);
        } else {
            stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        }
        Map<String, List<StationBasic>> listMap = stationBasicListAll.stream().collect(Collectors.groupingBy(stationBasic -> stationBasic.getStationTypeName()));
        listMap.keySet().forEach(key -> {
            Map<String, String> stringStringMap = new HashMap<>();
            stringStringMap.put("name", key);
            stringStringMap.put("value", String.valueOf(listMap.get(key).size()));
            result.add(stringStringMap);
        });
        return result;
    }

    //获取装机容量
    public HashMap<String, String> getInstallCapityByAreaName(String areaName) {
        HashMap<String, String> hashMap = new HashMap<>();
        AtomicReference<Double> total = new AtomicReference<>(0.0);
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationBasicListAll = getListOfStationBasicByAreaName(areaName);
        } else {
            stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        }
        stationBasicListAll.forEach(stationBasic -> {
            total.updateAndGet(v -> v + getStationCaPACITYL(stationBasic.getStationNumber()));
        });
        hashMap.put("title", String.format("%.2f", total.get()));
        return hashMap;
    }

    //获取有功功率
    public HashMap<String, String> getActivePowerByAreaName(String areaName) {
        HashMap<String, String> hashMap = new HashMap<>();
        AtomicReference<Double> total = new AtomicReference<>(0.0);
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationBasicListAll = getListOfStationBasicByAreaName(areaName);
        } else {
            stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        }
        stationBasicListAll.forEach(stationBasic -> {
            total.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(stationBasic.getFanGatewayId(), "有功功率"));
        });
        //有功功率换算
        hashMap.put("title", String.format("%.2f", total.get() / 1000));
        return hashMap;
    }

    //获取社会贡献

    /**
     * @param areaName  片区名称
     * @param stationId 场站id
     * @return 社会贡献列表
     * @deprecated 如果areaName 与 stationID 都不传 则查全国、如果areaName传了 staionID没有传则查片区 如果 areaName 与stationId都传 则取场站id
     */
    public Page<SocialContributionDto> getSocialContributionDtoList(String areaName, String stationId) {
        AtomicReference<Double> total = new AtomicReference<>(0.0);
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        if (!ObjectUtils.isEmpty(stationId)) {
            stationBasicListAll.add(stationBasicMapper.selectById(stationId));
        } else if (!ObjectUtils.isEmpty(areaName)) {
            stationBasicListAll = getListOfStationBasicByAreaName(areaName);
        } else {
            stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        }
        stationBasicListAll.forEach(stationBasic -> {
            List<Map<String, Object>> mapListData = new ArrayList<>();
            String finalIndicator = "年发电量";
            if (stationBasic.getStationType().equals("FDZ")) {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + "  where frontModule=~/逆变器/ and (equipmentIndexName='" + finalIndicator + "' )");
            } else {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='" + finalIndicator + "' )");
            }
            Double total1 = commonServiceImpl.getTotalByIndicatior(mapListData, finalIndicator);
            total.updateAndGet(v -> v + total1);
        });
        return commonServiceImpl.getSocialContributionDtoList(total.get());
    }

    public HashMap<String, List<String>> getPowerGenerationTrendsOfMonth(String areaName) {
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationBasicListAll = getListOfStationBasicByAreaName(areaName);
        } else {
            stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        }
        //月发电量
        AtomicReference<Double> monthlyPower = new AtomicReference<>(0.0);
        stationBasicListAll.forEach(stationBasic -> {
            List<Map<String, Object>> mapListData = new ArrayList<>();
            String finalIndicator = "月发电量";
            if (stationBasic.getStationType().equals("FDZ")) {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + "  where frontModule=~/逆变器/ and (equipmentIndexName='" + finalIndicator + "' )");
            } else {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='" + finalIndicator + "' )");
            }
            Double total = commonServiceImpl.getTotalByIndicatior(mapListData, finalIndicator);
            monthlyPower.updateAndGet(v -> v + total);
        });
        HashMap<String, List<String>> hashMap = new HashMap<>();
        List<String> xList = getXListofRecentOneYear();
        List<String> yList = Arrays.asList("0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "12000", String.format("%.2f", monthlyPower.get() / 1000));
        hashMap.put("axisData", xList);
        hashMap.put("seriesData", yList);
        return hashMap;
    }

    public Page<HashMap<String, String>> getDetailsOnPowergeneration(String areaName) {
        Page<HashMap<String, String>> hashMapPage = new Page<>(1, 99);
        List<HashMap<String, String>> hashMapList = new ArrayList<>();
        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().eq("station_type", "FDZ").isNotNull("fan_gateway_id"));
        //日发电量
        AtomicReference<Double> dailyPower = new AtomicReference<>(0.0);
        //月发电量
        AtomicReference<Double> monthlyPower = new AtomicReference<>(0.0);
        //年发电量
        AtomicReference<Double> annualPower = new AtomicReference<>(0.0);
        stationBasicList.forEach(stationBasic -> {
            List<Map<String, Object>> mapList = new ArrayList<>();
            if (stationBasic.getStationType().equals("FDZ")) {
                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
            } else {
                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where frontModule=~/逆变器/ and (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
            }
            List<Map<String, Object>> finalMapList = mapList;
            dailyPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "日发电量"));
            monthlyPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "月发电量"));
            annualPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "年发电量"));
        });
        HashMap<String, String> dayHashMap = new HashMap<>();
        dayHashMap.put("title", String.format("%.2f", dailyPower.get()) + "KWh");
        HashMap<String, String> monthHashMap = new HashMap<>();
        monthHashMap.put("title", String.format("%.2f", monthlyPower.get()) + "KWh");
        HashMap<String, String> annualHashMap = new HashMap<>();
        annualHashMap.put("title", String.format("%.2f", annualPower.get()) + "KWh");
        HashMap<String, String> totalHashMap = new HashMap<>();
        totalHashMap.put("title", String.format("%.2f", annualPower.get()) + "KWh");
        hashMapList.add(dayHashMap);
        hashMapList.add(monthHashMap);
        hashMapList.add(annualHashMap);
        hashMapList.add(totalHashMap);
        hashMapPage.setRecords(hashMapList);
        return hashMapPage;
    }

    public List<StationBasic> getListOfStationBasicByAreaName(String areaName) {
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        MapRegion mapRegion = mapRegionMapper.selectOne(new QueryWrapper<MapRegion>().eq("name", areaName));
        //获取片区下的省份名称
        ArrayList<String> stringArrayList = mapRegion.getProvince();
        //变量获取所有的场站信息
        for (int i = 0; i < stringArrayList.size(); i++) {
            Region region = regionMapper.selectOne(new QueryWrapper<Region>().eq("LEVEL", 1).like("REGION_NAME", stringArrayList.get(i)));
            List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().like("belong_area", region.getRegionCode()));
            stationBasicListAll.addAll(stationBasicList);
        }
        return stationBasicListAll;
    }


    public HashMap<String, List<String>> getPowerGenerationTrendsOfCompletionRate(String areaName) {
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationBasicListAll = getListOfStationBasicByAreaName(areaName);
        } else {
            stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        }
        //月发电量
        AtomicReference<Double> monthlyPower = new AtomicReference<>(0.0);
        stationBasicListAll.forEach(stationBasic -> {
            List<Map<String, Object>> mapListData = new ArrayList<>();
            String finalIndicator = "月发电量";
            if (!stationBasic.getStationType().equals("FDZ")) {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + "  where frontModule=~/逆变器/ and (equipmentIndexName='" + finalIndicator + "' )");
            } else {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='" + finalIndicator + "' )");
            }
            Double total = commonServiceImpl.getTotalByIndicatior(mapListData, finalIndicator);
            monthlyPower.updateAndGet(v -> v + total);
        });
        HashMap<String, List<String>> hashMap = new HashMap<>();
        List<String> xList = getXListofRecentOneYear();
        List<String> yList = Arrays.asList("0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "120", String.format("%.2f", monthlyPower.get() % 200));
        hashMap.put("axisData", xList);
        hashMap.put("seriesData", yList);
        return hashMap;
    }


    public Page<HashMap<String, String>> getPowerGenerationTrendsOfCompletionTopFive(String areaName) {
        Page<HashMap<String, String>> hashMapPage = new Page<>(1, 5);
        List<HashMap<String, String>> mapList = new ArrayList<>();
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationBasicListAll = getListOfStationBasicByAreaName(areaName);
        } else {
            stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        }
        HashMap<String, List<String>> hashMap = new HashMap<>();
        List<String> xList = new ArrayList<>();
        List<String> yList = new ArrayList<>();
        //月发电量
        String finalIndicator = "月发电量";
        stationBasicListAll.forEach(stationBasic -> {
            List<Map<String, Object>> mapListData = new ArrayList<>();
            if (!stationBasic.getStationType().equals("FDZ")) {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + "  where frontModule=~/逆变器/ and (equipmentIndexName='" + finalIndicator + "' )");
            } else {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='" + finalIndicator + "' )");
            }
            Double total = commonServiceImpl.getTotalByIndicatior(mapListData, finalIndicator);
            stationBasic.setAddress(String.format("%.2f", total % 100));
        });
        List<StationBasic> sorted = stationBasicListAll.stream().sorted(Comparator.comparing(StationBasic::getAddress, Comparator.comparingDouble(Double::parseDouble)).reversed()).collect(Collectors.toList());
        sorted.forEach(stationBasic -> {
            HashMap<String, String> hashMap1 = new HashMap<>();
            hashMap1.put("stationName", stationBasic.getStationName());
            hashMap1.put("value", stationBasic.getAddress());
            hashMap1.put("value1", stationBasic.getAddress());
            mapList.add(hashMap1);
        });
        hashMapPage.setRecords(mapList);
        return hashMapPage;
    }


    public List<String> getXListofRecentOneYear() {
        List<String> xList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        for (int i = 1; i < 13; i++) {
            calendar.setTime(date);
            calendar.add(Calendar.MONTH, i - 12);
            xList.add(String.valueOf(calendar.get(Calendar.YEAR)).substring(2, 4) + "-" + calendar.get(Calendar.MONTH));
        }
        return xList;
    }


    public Page<HashMap<String, String>> getPowerGenerationTrendsOfCompletionTopThree(String tabValue, String areaName) {
        Page<HashMap<String, String>> page = new Page<>(1, 3);
        List<HashMap<String, String>> mapList = new ArrayList<>();
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        List<StationBasic> fdzList = new ArrayList<>();
        List<StationBasic> gfdzlist = new ArrayList<>();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationBasicListAll = getListOfStationBasicByAreaName(areaName);
        } else {
            stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        }
        String indicator = "日发电量";
        if (tabValue.equals("1")) {
            indicator = "月发电量";
        } else if (tabValue.equals("2")) {
            indicator = "年发电量";
        }
        //填写发电小时数
        String finalIndicator = indicator;
        stationBasicListAll.forEach(stationBasic -> {
            Double install = getStationCaPACITYL(stationBasic.getStationNumber());
            List<Map<String, Object>> mapListData = new ArrayList<>();
            if (!stationBasic.getStationType().equals("FDZ")) {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + "  where frontModule=~/逆变器/ and (equipmentIndexName='" + finalIndicator + "' )");
            } else {
                mapListData = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='" + finalIndicator + "' )");
            }
            Double total = commonServiceImpl.getTotalByIndicatior(mapListData, finalIndicator);
            stationBasic.setAddress(String.format("%.2f", total));
            if (stationBasic.getStationType().equals("FDZ")) {
                stationBasic.setAddress(String.format("%.2f", (total * 10) / install));
            } else {
                stationBasic.setAddress(String.format("%.2f", total / 10000 / install));
            }
            if (stationBasic.getAddress().equals("NaN")) {
                stationBasic.setAddress("0.00");
            }
        });
        //分组并排序
        fdzList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("FDZ")).collect(Collectors.toList()).stream().sorted(Comparator.comparing(StationBasic::getAddress, Comparator.comparingDouble(Double::parseDouble)).reversed()).collect(Collectors.toList());
        gfdzlist = stationBasicListAll.stream().filter(stationBasic -> !stationBasic.getStationType().equals("FDZ")).collect(Collectors.toList()).stream().sorted(Comparator.comparing(StationBasic::getAddress, Comparator.comparingDouble(Double::parseDouble)).reversed()).collect(Collectors.toList());
        for (int i = 0; i < 3; i++) {
            HashMap<String, String> stringHashMap = new HashMap<>();
            stringHashMap.put("sortNumber", String.valueOf(i + 1));
            StationBasic stationBasic = new StationBasic();
            if (i < (fdzList.size())) {
                stationBasic = fdzList.get(i);
                stringHashMap.put("stationName1", stationBasic.getStationName());
                stringHashMap.put("hours1", stationBasic.getAddress() + "h");
            } else {
                stringHashMap.put("stationName1", "");
                stringHashMap.put("hours1", "");
            }
            if (i < (gfdzlist.size())) {
                stationBasic = gfdzlist.get(i);
                stringHashMap.put("stationName2", stationBasic.getStationName());
                stringHashMap.put("hours2", stationBasic.getAddress() + "h");
            } else {
                stringHashMap.put("stationName2", "");
                stringHashMap.put("hours2", "");
            }
            mapList.add(stringHashMap);
        }
        page.setRecords(mapList);
        //组装数据
        return page;
    }

    public void getTotalData() {
        List<StationBasic> stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        List<StationBasic> fdzList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("FDZ")).collect(Collectors.toList());
        List<StationBasic> jzsgfdzList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("JZSGFDZ")).collect(Collectors.toList());
        List<StationBasic> fbsgfdzList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("FBSGFDZ")).collect(Collectors.toList());
        List<StationBasic> gfList = stationBasicListAll.stream().filter(stationBasic -> !stationBasic.getStationType().equals("FDZ")).collect(Collectors.toList());
        Page<HashMap<String, String>> page = new Page<>(1, 10);
        Page<HashMap<String, String>> page1 = new Page<>(1, 10);
        Page<HashMap<String, String>> page2 = new Page<>(1, 10);
        Page<HashMap<String, String>> page3 = new Page<>(1, 10);
//        ----------------装机容量开始-----------------------
        List<HashMap<String, String>> list = new ArrayList<>();
        //装机容量
        HashMap<String, String> stringHashMap = new HashMap<>();
        BigDecimal totalInstall = new BigDecimal(getInstallCapity(stationBasicListAll));
        stringHashMap.put("title", totalInstall.toString());
        stringHashMap.put("data", "");
        list.add(stringHashMap);
        //风电站
        HashMap<String, String> stringHashMap1 = new HashMap<>();
        BigDecimal fdzInstall = new BigDecimal(getInstallCapity(fdzList));
        stringHashMap1.put("title", fdzInstall.toString());
        stringHashMap1.put("data", String.valueOf(fdzList.size()));
        list.add(stringHashMap1);
        //集中式光伏电站
        HashMap<String, String> stringHashMap2 = new HashMap<>();
        BigDecimal jzsInstall = new BigDecimal(getInstallCapity(jzsgfdzList));
        stringHashMap2.put("title", jzsInstall.toString());
        stringHashMap2.put("data", String.valueOf(jzsgfdzList.size()));
        list.add(stringHashMap2);
        //分布式光伏电站
        HashMap<String, String> stringHashMap3 = new HashMap<>();
        BigDecimal fbsInstall = new BigDecimal(getInstallCapity(fbsgfdzList));
        stringHashMap3.put("title", fbsInstall.toString());
        stringHashMap3.put("data", String.valueOf(fbsgfdzList.size()));
        list.add(stringHashMap3);
        page.setRecords(list);
        BigDecimal gfInstall = new BigDecimal(getInstallCapity(gfList));
//----------------------装机容量结束----------------------------------------
//  ----------------装机容量开始-----------------------
        List<HashMap<String, String>> list1 = new ArrayList<>();
        List<HashMap<String, String>> list2 = new ArrayList<>();
        List<HashMap<String, String>> list3 = new ArrayList<>();
        AtomicReference<Double> powerOfDayFD = new AtomicReference<>(new Double(0.00));
        AtomicReference<Double> powerOfMonthFD = new AtomicReference<>(new Double(0.00));
        AtomicReference<Double> powerOfAnnualFD = new AtomicReference<>(new Double(0.00));
        AtomicReference<Double> powerOfDayGF = new AtomicReference<>(new Double(0.00));
        AtomicReference<Double> powerOfMonthGF = new AtomicReference<>(new Double(0.00));
        AtomicReference<Double> powerOfAnnualGF = new AtomicReference<>(new Double(0.00));
        fdzList.forEach(stationBasic -> {
            List<Map<String, Object>> mapList;
            mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量'  )");
            powerOfDayFD.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(mapList, "日发电量"));
            powerOfMonthFD.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(mapList, "月发电量"));
            powerOfAnnualFD.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(mapList, "年发电量"));
        });
        gfList.forEach(stationBasic -> {
            List<Map<String, Object>> mapList;
            mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where frontModule=~/逆变器/ and (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
            powerOfDayGF.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(mapList, "日发电量"));
            powerOfMonthGF.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(mapList, "月发电量"));
            powerOfAnnualGF.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(mapList, "年发电量"));
        });
        HashMap<String, String> stringHashMap4 = new HashMap<>();
        stringHashMap4.put("title", String.format("%.2f", powerOfDayFD.get()) + "/" + String.format("%.2f", powerOfDayGF.get()));
        list1.add(stringHashMap4);
        HashMap<String, String> stringHashMap5 = new HashMap<>();
        stringHashMap5.put("title", String.format("%.2f", powerOfMonthFD.get()) + "/" + String.format("%.2f", powerOfMonthGF.get()));
        list1.add(stringHashMap5);
        HashMap<String, String> stringHashMap6 = new HashMap<>();
        stringHashMap6.put("title", String.format("%.2f", powerOfAnnualFD.get()) + "/" + String.format("%.2f", powerOfAnnualGF.get()));
        list1.add(stringHashMap6);
        HashMap<String, String> stringHashMap7 = new HashMap<>();
        stringHashMap7.put("title", String.format("%.2f", powerOfAnnualFD.get() % 200) + "/" + String.format("%.2f", powerOfAnnualGF.get() % 200));
        list1.add(stringHashMap7);
        HashMap<String, String> stringHashMap8 = new HashMap<>();
        stringHashMap8.put("title", String.format("%.2f", powerOfAnnualFD.get() / fdzInstall.doubleValue()) + "/" + String.format("%.2f", powerOfAnnualGF.get() / gfInstall.doubleValue()));
        list1.add(stringHashMap8);
        page1.setRecords(list1);
        HashMap<String, String> stringHashMap9 = new HashMap<>();
        stringHashMap9.put("title", String.format("%.2f", powerOfDayFD.get() + powerOfDayGF.get()));
        list2.add(stringHashMap9);
        HashMap<String, String> stringHashMap10 = new HashMap<>();
        stringHashMap10.put("title", String.format("%.2f", powerOfMonthFD.get() + powerOfMonthGF.get()));
        list2.add(stringHashMap10);
        HashMap<String, String> stringHashMap11 = new HashMap<>();
        stringHashMap11.put("title", String.format("%.2f", powerOfAnnualFD.get() + powerOfAnnualGF.get()));
        list2.add(stringHashMap11);
        HashMap<String, String> stringHashMap12 = new HashMap<>();
        stringHashMap12.put("title", String.format("%.2f", (powerOfAnnualFD.get() % 200 + powerOfAnnualGF.get() % 200) / 2));
        list2.add(stringHashMap12);
        page2.setRecords(list2);
        HashMap<String, String> stringHashMap13 = new HashMap<>();
        stringHashMap13.put("title1", String.format("%.2f", (powerOfAnnualFD.get() + powerOfAnnualGF.get()) * 0.000832));
        stringHashMap13.put("title2", "二氧化碳减排量（万t）");
        list3.add(stringHashMap13);
        HashMap<String, String> stringHashMap14 = new HashMap<>();
        stringHashMap14.put("title1", String.format("%.2f", (powerOfAnnualFD.get() + powerOfAnnualGF.get()) * 0.0003049));
        stringHashMap14.put("title2", "节约标准煤（万t）");
        list3.add(stringHashMap14);
        HashMap<String, String> stringHashMap15 = new HashMap<>();
        stringHashMap15.put("title1", String.format("%.2f", (powerOfAnnualFD.get() + powerOfAnnualGF.get()) * 0.00032));
        stringHashMap15.put("title2", "碳粉尘减排量（万t）");
        list3.add(stringHashMap15);
        HashMap<String, String> stringHashMap16 = new HashMap<>();
        stringHashMap16.put("title1", String.format("%.2f", (powerOfAnnualFD.get() + powerOfAnnualGF.get()) * 0.0016));
        stringHashMap16.put("title2", "二氧化硫减排量（万t）");
        list3.add(stringHashMap16);
        page3.setRecords(list3);
        try {
            emqKeeper.getMqttClient().publish("total_zjrl_topic", JSON.toJSON(page).toString().getBytes("UTF-8"), 1, true);
            emqKeeper.getMqttClient().publish("total_ssscsj_topic", JSON.toJSON(page1).toString().getBytes("UTF-8"), 1, true);
            emqKeeper.getMqttClient().publish("total_zssscsj_topic", JSON.toJSON(page2).toString().getBytes("UTF-8"), 1, true);
            emqKeeper.getMqttClient().publish("total_zshgx_topic", JSON.toJSON(page3).toString().getBytes("UTF-8"), 1, true);
        } catch (Exception ex) {

        }
    }

    public List<HashMap<String, Object>> getNationalPowerGenerationData() {
        List<HashMap<String, Object>> resultHashMap = new ArrayList<>();
        List<StationBasic> stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        stationBasicListAll.forEach(stationBasic -> {
            List<Map<String, Object>> mapList;
            if (stationBasic.getStationType().equals("FDZ")) {
                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量'  )");
                stationBasic.setAddress(String.format("%.2f", commonServiceImpl.getTotalByIndicatior(mapList, "年发电量")));
            } else {
                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where frontModule=~/逆变器/ and (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
                stationBasic.setAddress(String.format("%.2f", commonServiceImpl.getTotalByIndicatior(mapList, "年发电量") / 10000));
            }
        });
        List<StationBasic> fdzList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("FDZ")).collect(Collectors.toList());
        List<StationBasic> jzsgfdzList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("JZSGFDZ")).collect(Collectors.toList());
        List<StationBasic> fbsgfdzList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("FBSGFDZ")).collect(Collectors.toList());
        resultHashMap.add(getTableByStationListAndTitle("风电年发电量 (万kWh)", fdzList, "#0060ff"));
        resultHashMap.add(getTableByStationListAndTitle("分布式光伏年发电量 (万kWh)", fbsgfdzList, "#fdaa04"));
        resultHashMap.add(getTableByStationListAndTitle("集中式光伏年发电量 (万kWh)", jzsgfdzList, "#ec18f7"));
        return resultHashMap;
    }

    public HashMap<String, Object> getTableByStationListAndTitle(String title, List<StationBasic> stationBasicList, String color) {
        HashMap<String, Object> hashMap = new HashMap<>();
        List<String> xData = new ArrayList<>();
        List<String> yData = new ArrayList<>();
        stationBasicList.forEach(stationBasic -> {
            xData.add(stationBasic.getStationName());
            yData.add(stationBasic.getAddress());
        });
        hashMap.put("title", title);
        hashMap.put("color", color);
        hashMap.put("xData", xData);
        hashMap.put("yData", yData);
        return hashMap;
    }

    public List<HashMap<String, Object>> getSelectDataForNational() {
        List<HashMap<String, Object>> hashMapList = new ArrayList<>();
        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("belong_area").isNotNull("fan_gateway_id"));
        List<Region> regionList = this.regionMapper.selectList(new QueryWrapper<Region>().eq("level", 1));
        regionList.forEach(region -> {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("label", region.getRegionName());
            hashMap.put("value", region.getRegionCode());
            List<HashMap<String, Object>> children = stationBasicList.stream().filter(stationBasic -> stationBasic.getBelongArea().contains(String.valueOf(region.getRegionCode()))).map(stationBasic -> {
                HashMap<String, Object> hashMap1 = new HashMap<>();
                hashMap1.put("label", stationBasic.getStationName());
                hashMap1.put("value", stationBasic.getSequenceNbr());
                return hashMap1;
            }).collect(Collectors.toList());
            hashMap.put("children", children);
            hashMapList.add(hashMap);
        });
        return hashMapList;
    }

//    const data = {
//        xData: [],
//        实时有功: {
//            title: '实时有功  2023-06-14  29.3',
//                    yData: []
//        },
//        footerList: [
//        {
//            title: '谷值：',
//                value1: '-010',
//                value2: '2.14',
//                value3: '2.14'
//        }
//  ]
//    };

    public HashMap<String, Object> getTheStationPowerCurve(String stationId,String date) {
        HashMap<String, Object> result = new HashMap<>();
        List<HashMap<String, Object>> hashMapList = new ArrayList<>();
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        //x轴数据
        List<String> xdata = new ArrayList<>();
        //实时有功功率
        List<String> currentPowerYdata = new ArrayList<>();
        //短期功率预测
        List<String> shortPowerYdata = new ArrayList<>();
        //超短期功率预测
        List<String> superPowerShortYdata = new ArrayList<>();
        for (int i = 0; i < 25; i++) {
            xdata.add(String.format("%02d", i) + ":00");
            Random random =new Random();
            currentPowerYdata.add(String.format("%.2f", random.nextDouble()*30));
            shortPowerYdata.add(String.format("%.2f", random.nextDouble()*40));
            superPowerShortYdata.add(String.format("%.2f", random.nextDouble()*50));
        }
        result.put("xData", xdata);
        HashMap<String, Object> currentPowerHashMap = new HashMap<>();
        currentPowerHashMap.put("title", "实时有功  " +date);
        currentPowerHashMap.put("yData", currentPowerYdata);
        result.put("currentPower", currentPowerHashMap);
        HashMap<String, Object> shortPowerHashMap = new HashMap<>();
        shortPowerHashMap.put("title", "短期功率预测  "+date);
        shortPowerHashMap.put("yData", shortPowerYdata);
        result.put("shortPower", shortPowerHashMap);
        HashMap<String, Object> superShortPowerHashMap = new HashMap<>();
        superShortPowerHashMap.put("title", "超短期功率预测  "+ date);
        superShortPowerHashMap.put("yData", superPowerShortYdata);
        result.put("superShortPower", superShortPowerHashMap);
        HashMap<String, Object> footerList = new HashMap<>();
        String currentMin = String.format("%.2f",currentPowerYdata.stream().mapToDouble(Double::parseDouble).min().getAsDouble());
        String shortMin = String.format("%.2f",shortPowerYdata.stream().mapToDouble(Double::parseDouble).min().getAsDouble());
        String supreMin = String.format("%.2f",superPowerShortYdata.stream().mapToDouble(Double::parseDouble).min().getAsDouble());
        List<String> gz = new ArrayList<>();
        List<String> sj1 = new ArrayList<>();
        gz.add(currentMin);
        sj1.add(xdata.get(currentPowerYdata.indexOf(currentMin)));
        gz.add(shortMin);
        sj1.add(xdata.get(shortPowerYdata.indexOf(shortMin)));
        gz.add(supreMin);
        sj1.add(xdata.get(superPowerShortYdata.indexOf(supreMin)));

        String currentMax = String.format("%.2f",currentPowerYdata.stream().mapToDouble(Double::parseDouble).max().getAsDouble());
        String shortMax = String.format("%.2f",shortPowerYdata.stream().mapToDouble(Double::parseDouble).max().getAsDouble());
        String supreMax = String.format("%.2f",superPowerShortYdata.stream().mapToDouble(Double::parseDouble).max().getAsDouble());
        List<String> zdz = new ArrayList<>();
        List<String> sj2 = new ArrayList<>();
        zdz.add(currentMax);
        zdz.add(shortMax);
        zdz.add(supreMax);
        sj2.add(xdata.get(currentPowerYdata.indexOf(currentMax)));
        sj2.add(xdata.get(shortPowerYdata.indexOf(shortMax)));
        sj2.add(xdata.get(superPowerShortYdata.indexOf(supreMax)));
        String currentAvg =String.format("%.2f", currentPowerYdata.stream().mapToDouble(Double::parseDouble).average().getAsDouble());
        String shortAvg = String.format("%.2f", shortPowerYdata.stream().mapToDouble(Double::parseDouble).average().getAsDouble());
        String supreAvg = String.format("%.2f", superPowerShortYdata.stream().mapToDouble(Double::parseDouble).average().getAsDouble());
        List<String> pjz = new ArrayList<>();
        List<String> fjl = new ArrayList<>();
        pjz.add(currentAvg);
        pjz.add(shortAvg);
        pjz.add(supreAvg);
        fjl = Arrays.asList("0.68", "0.89", "0.56");

        footerList.put("gz", gz);
        footerList.put("sj1", sj1);
        footerList.put("zdz", zdz);
        footerList.put("sj2", sj2);
        footerList.put("pjz", pjz);
        footerList.put("fjl", fjl);
        result.put("footerList", footerList);
        return result;
    }
}
