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

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.druid.sql.visitor.functions.If;
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.extension.plugins.pagination.Page;
import com.sun.imageio.plugins.common.I18NImpl;
import com.yeejoin.amos.boot.module.jxiop.api.entity.*;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.*;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESEquipments;
import com.yeejoin.amos.boot.module.jxiop.biz.constants.CommonConstans;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.*;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IndicatorData;
import com.yeejoin.amos.boot.module.jxiop.biz.tdmapper.IndicatorDataMapper;
//import com.yeejoin.amos.component.influxdb.InfluxdbUtil;
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;
    @Autowired
    StationPlanMapper stationPlanMapper;
    /**
     * 场站坐标mapper
     */
    @Autowired
    StationCoordinateMapper stationCoordinateMapper;
    /***
     * 设备基础信息中间表数据-热工院
     */
    @Autowired
    SjglZsjZsbtzServiceImpl SjglZsjZsbtzServiceImpl;


    @Autowired
    CommonServiceImpl commonServiceImpl;

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

    @Autowired
    EmqKeeper emqKeeper;
    //    @Autowired
//    InfluxdbUtil influxdbUtil;
    @Autowired
    IndicatorDataMapper indicatorDataMapper;


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

    public List<RegionNationWideDto> getNationWideInfo(String provinceName, String type) {
        List<RegionNationWideDto> regionNationWideDtoList = new ArrayList<>();
        List<StationCacheInfoDto> stationCacheInfoDtoList = commonServiceImpl.getListStationCacheInfoDto();
        List<Region> regionList = this.regionMapper.selectList(new QueryWrapper<Region>().eq("level", 1));
        List<StationCacheInfoDto> 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();
                Region region = regionList.get(i);
                list = stationCacheInfoDtoList.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getBelongProvince().equals(region.getRegionName())).collect(Collectors.toList());
                List<StationCacheInfoDto> fdlist = list.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getStationType().equals("FDZ")).collect(Collectors.toList());
                List<StationCacheInfoDto> gflist = list.stream().filter(stationCacheInfoDto -> !stationCacheInfoDto.getStationType().equals("FDZ")).collect(Collectors.toList());
                if (list.size() > 0) {
                    regionNationWideDto.setJsJoin(true);
                } else {
                    regionNationWideDto.setJsJoin(false);
                }
                regionNationWideDto.setFengdian(String.valueOf(fdlist.size()));
                regionNationWideDto.setGuangfu(String.valueOf(gflist.size()));
                regionNationWideDto.setGuangfuMW(String.format(CommonConstans.Twodecimalplaces, gflist.stream().mapToDouble(stationCacheInfoDto -> Double.parseDouble(stationCacheInfoDto.getInstalledCapacity())).sum()));
                regionNationWideDto.setFengdianMV(String.format(CommonConstans.Twodecimalplaces, fdlist.stream().mapToDouble(stationCacheInfoDto -> Double.parseDouble(stationCacheInfoDto.getInstalledCapacity())).sum()));
                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 = stationCacheInfoDtoList;
            } else {
                list = stationCacheInfoDtoList.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getBelongProvince().equals(finalProvinceName)).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<>();

                StationCacheInfoDto stationCacheInfoDto = list.get(i);
                RegionNationWideDto regionNationWideDto = new RegionNationWideDto();
                regionNationWideDto.setStaitionId(String.valueOf(stationCacheInfoDto.getStationId()));
                regionNationWideDto.setStaitionName(stationCacheInfoDto.getStationName());
                regionNationWideDto.setStaitionType(stationCacheInfoDto.getStationType());
                String speendOrirradiate = "";
                regionNationWideDto.setStationCapacity(stationCacheInfoDto.getInstalledCapacity());
                if (stationCacheInfoDto.getStationType().equals("FDZ")) {
                    //用于组装-es查询条件
                    Map<String, List<String>> queryCondtion = new HashMap<>();
                    queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("30秒平均风速"));
                    queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getFanGatewayId()));
                    List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                    speendOrirradiate = String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getAvagerByEquipmentIndxName(result, "30秒平均风速"));
                } else {
                    Map<String, List<String>> queryCondtion = new HashMap<>();
                    queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("WTX-801_25_WTX-801_总辐射"));
                    queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getBoosterGatewayId()));
                    List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                    speendOrirradiate = String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, "WTX-801_25_WTX-801_总辐射"));
                }
                regionNationWideDto.setSpeendOrirradiate(speendOrirradiate);
                StationCoordinate stationCoordinate = stationCoordinateList.stream().filter(stationCoordinate1 -> String.valueOf(stationCoordinate1.getStationId()).equals(stationCacheInfoDto.getStationId())).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<StationCacheInfoDto> finalList = list;
        String finalProvinceName1 = provinceName;
        Thread thread = new Thread(() -> {
            getCompletionOfPowerIndicatorsByCurrentData(finalList, finalProvinceName1);
        });
        thread.start();
        return regionNationWideDtoList;
    }

    //    @Scheduled(cron = "0/60 * * * * ? ")
    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);
        List<StationCacheInfoDto> stationCacheInfoDtoList = commonServiceImpl.getListStationCacheInfoDto();
        List<StationCacheInfoDto> stationCacheInfoDtos = stationCacheInfoDtoList.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getBelongProvince().equals(provinceName)).collect(Collectors.toList());
        if (ObjectUtils.isEmpty(stationCacheInfoDtos)) {
            DataGridMock dataGridMock = new DataGridMock(current, 0, false, 1, null);
            ResultsData resultsData = new ResultsData(dataGridMock, colModels);
            return resultsData;
        }
        //日发电量
        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";
        //年利用小时数
        List<StationPlan> fdzPlans = new ArrayList<>();
        int year = Calendar.getInstance().get(Calendar.YEAR);
        List<String> fdz = stationCacheInfoDtos.stream().map(StationCacheInfoDto::getStationId).collect(Collectors.toList());
        LambdaQueryWrapper<StationPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StationPlan::getYear, String.valueOf(year));
        queryWrapper.in(StationPlan::getStationBasicId, fdz);

        fdzPlans = stationPlanMapper.selectList(queryWrapper);
        double value = fdzPlans.stream().mapToDouble(StationPlan::getValue).sum();

        AtomicReference<Double> useHours = new AtomicReference<>(0.0);
        AtomicReference<Double> installCapacity = new AtomicReference<>(0.0);
        AtomicReference<Double> fdzInstallCapacity = new AtomicReference<>(0.0);
        AtomicReference<Double> gfzinstallCapacity = new AtomicReference<>(0.0);
        //年发电量
        AtomicReference<Double> fdzannualPower = new AtomicReference<>(0.0);
        AtomicReference<Double> gfzannualPower = new AtomicReference<>(0.0);
        //遍历列表
        stationCacheInfoDtos.forEach(stationCacheInfoDto -> {
            CompletionOfPowerIndicatorsDto completionOfPowerIndicatorsDto = new CompletionOfPowerIndicatorsDto();
            completionOfPowerIndicatorsDto.setStationName(stationCacheInfoDto.getStationName());
            completionOfPowerIndicatorsDto.setInstallCapactity(stationCacheInfoDto.getInstalledCapacity());
            try {
                if (stationCacheInfoDto.getStationType().equals("FDZ")) {
                    //用于组装-es查询条件
                    Map<String, List<String>> queryCondtion = new HashMap<>();
                    Map<String, List<String>> queryCondtion1 = new HashMap<>();
                    queryCondtion1.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值"));
                    queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getBoosterGatewayId()));
                    List<ESEquipments> result1 = commonServiceImpl.getListDataByCondtions(queryCondtion1, null, ESEquipments.class);

                    queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("30秒平均风速", "日发电量", "月发电量", "年发电量"));
                    queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getFanGatewayId()));
                    List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                    completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getAvagerByEquipmentIndxName(result, "30秒平均风速")));
                    completionOfPowerIndicatorsDto.setActivePower(String.format(CommonConstans.Twodecimalplaces, (commonServiceImpl.getSumByEquipmentIndxName(result1, "220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值"))));
                    completionOfPowerIndicatorsDto.setDailyPower(String.format(CommonConstans.Fourdecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
                    completionOfPowerIndicatorsDto.setMonthlyPower(String.format(CommonConstans.Fourdecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量")));
                    completionOfPowerIndicatorsDto.setAnnualPower(String.format(CommonConstans.Fourdecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));
                    dailyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
                    monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量")));
                    annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));
                    fdzannualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));
                    fdzInstallCapacity.updateAndGet(v -> v + Double.parseDouble(stationCacheInfoDto.getInstalledCapacity()));
                } else {
                    Map<String, List<String>> queryCondtion = new HashMap<>();
                    queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, CommonConstans.taiHeGenIndicator);
                    queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getBoosterGatewayId()));
                    Map<String, List<String>> queryCondtion1 = new HashMap<>();
                    queryCondtion1.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("WTX-801_25_WTX-801_总辐射", "南瑞光差保护_313P"));
                    queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getBoosterGatewayId()));
                    List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class, null);
                    List<ESEquipments> result1 = commonServiceImpl.getListDataByCondtions(queryCondtion1, null, ESEquipments.class);
                    completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result1, "WTX-801_25_WTX-801_总辐射")));
                    completionOfPowerIndicatorsDto.setActivePower(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result1, "南瑞光差保护_313P") * CommonConstans.kwToMv));
                    completionOfPowerIndicatorsDto.setDailyPower(String.format(CommonConstans.Fourdecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay)));
                    completionOfPowerIndicatorsDto.setMonthlyPower(String.format(CommonConstans.Fourdecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth)));
                    completionOfPowerIndicatorsDto.setAnnualPower(String.format(CommonConstans.Fourdecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear)));
                    dailyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay)));
                    monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth)));
                    annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear)));
                    gfzannualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear)));
                    gfzinstallCapacity.updateAndGet(v -> v + Double.parseDouble(stationCacheInfoDto.getInstalledCapacity()));
                }
            } catch (Exception exception) {
                completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance("0");
                completionOfPowerIndicatorsDto.setActivePower("0");
                completionOfPowerIndicatorsDto.setDailyPower("0");
                completionOfPowerIndicatorsDto.setMonthlyPower("0");
                completionOfPowerIndicatorsDto.setAnnualPower("0");
            }
            completionOfPowerIndicatorsDtoList.add(completionOfPowerIndicatorsDto);
        });
        Page<SocialContributionDto> socialContributionDtoPage = new Page<SocialContributionDto>();
        List<SocialContributionDto> socialContributionDtoList = new ArrayList<>();
        completionRatio = String.format(CommonConstans.Twodecimalplaces, (annualPower.get() * 100) / value);
        SocialContributionDto dailyPowerdto = new SocialContributionDto();
        dailyPowerdto.setTitle(String.format(CommonConstans.Fourdecimalplaces, dailyPower.get()));
        dailyPowerdto.setUnit("万kWh");
        SocialContributionDto monthlyPowerdto = new SocialContributionDto();
        monthlyPowerdto.setTitle(String.format(CommonConstans.Fourdecimalplaces, monthlyPower.get()));
        monthlyPowerdto.setUnit("万kWh");
        SocialContributionDto annualPowerdto = new SocialContributionDto();
        annualPowerdto.setTitle(String.format(CommonConstans.Fourdecimalplaces, annualPower.get()));
        annualPowerdto.setUnit("万kWh");
        SocialContributionDto completionRatioDto = new SocialContributionDto();
        completionRatioDto.setTitle(completionRatio);
        completionRatioDto.setUnit("%");
        SocialContributionDto useHoursDto = new SocialContributionDto();
        useHoursDto.setTitle(String.format(CommonConstans.Twodecimalplaces, (fdzannualPower.get() * CommonConstans.wkwhToMv / fdzInstallCapacity.get() + gfzannualPower.get() * CommonConstans.wkwhToMv / gfzinstallCapacity.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);
        Integer allsize = completionOfPowerIndicatorsDtoList.size();
        DataGridMock dataGridMock = new DataGridMock(current, allsize, false, allsize / size + 1, completionOfPowerIndicatorsDtoList);
        ResultsData resultsData = new ResultsData(dataGridMock, colModels);
        try {
            emqKeeper.getMqttClient().publish(provinceName + "_completion_of_powerindicator_list_topic", JSON.toJSON(resultsData).toString().getBytes("UTF-8"), 1, true);
            emqKeeper.getMqttClient().publish(provinceName + "_completion_of_powerindicator_topic", JSON.toJSON(socialContributionDtoPage).toString().getBytes("UTF-8"), 1, true);
            logger.info("-----------------发送区域实时生产数据消息=================== 成功！" + JSON.toJSONString(socialContributionDtoPage));
        } catch (Exception exception) {
            logger.error("-----------------发送区域实时生产数据消息=================== 失败！");
        }
        return resultsData;
    }


    public void getCompletionOfPowerIndicatorsByCurrentData(List<StationCacheInfoDto> 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(provinceName + "_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";
//        //年利用小时数
//        int year = Calendar.getInstance().get(Calendar.YEAR);
//        List<String> fdz = stationBasicList.stream().map(StationCacheInfoDto::getStationId).collect(Collectors.toList());
//        LambdaQueryWrapper<StationPlan> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(StationPlan::getYear, String.valueOf(year));
//        queryWrapper.in(StationPlan::getStationBasicId, fdz);
//        List<StationPlan> fdzPlans = stationPlanMapper.selectList(queryWrapper);
//        double value = fdzPlans.stream().mapToDouble(StationPlan::getValue).sum();
//
//        AtomicReference<Double> useHours = new AtomicReference<>(0.0);
//        AtomicReference<Double> installCapacity = new AtomicReference<>(0.0);
//        AtomicReference<Double> fdzInstallCapacity = new AtomicReference<>(0.0);
//        AtomicReference<Double> gfzinstallCapacity = new AtomicReference<>(0.0);
//        //年发电量
//        AtomicReference<Double> fdzannualPower = new AtomicReference<>(0.0);
//        AtomicReference<Double> gfzannualPower = new AtomicReference<>(0.0);
//        stationBasicList.forEach(stationCacheInfoDto -> {
//            Map<String, List<String>> queryMap = new HashMap<>();
//            queryMap.put("equipmentIndexName.keyword", Arrays.asList("日发电量", "月发电量", "年发电量"));
//            queryMap.put("gatewayId.keyword", Arrays.asList(stationCacheInfoDto.getFanGatewayId()));
//            if ("FDZ".equals(stationCacheInfoDto.getStationType())) {
//                Map<String, List<String>> queryCondtion = new HashMap<>();
//                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("日发电量", "月发电量", "年发电量"));
//                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getFanGatewayId()));
//                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
//                dailyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
//                monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量")));
//                annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));
//                fdzannualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));
//                fdzInstallCapacity.updateAndGet(v -> v + Double.parseDouble(stationCacheInfoDto.getInstalledCapacity()));
//            } else {
//                Map<String, List<String>> queryCondtion = new HashMap<>();
//                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("日发电量", "月发电量", "年发电量"));
//                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getFanGatewayId()));
//                Map<String, String> likeQuerCondtion = new HashMap<>();
//                likeQuerCondtion.put(CommonConstans.QueryStringFrontMoudle, "逆变器");
//                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class, likeQuerCondtion);
//                dailyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量") * CommonConstans.pvGenPoweActor * CommonConstans.pvGenPoweActorDay));
//                monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量") * CommonConstans.pvGenPoweActor));
//                annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量") * CommonConstans.pvGenPoweActor));
//                gfzannualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量") * CommonConstans.pvGenPoweActor));
//                gfzinstallCapacity.updateAndGet(v -> v + Double.parseDouble(stationCacheInfoDto.getInstalledCapacity()));
//            }
//        });
//        completionRatio = String.format("%.2f", (annualPower.get() * 100) / value);
//        SocialContributionDto dailyPowerdto = new SocialContributionDto();
//        dailyPowerdto.setTitle(String.format(CommonConstans.Twodecimalplaces, dailyPower.get()));
//        dailyPowerdto.setUnit("万kWh");
//        SocialContributionDto monthlyPowerdto = new SocialContributionDto();
//        monthlyPowerdto.setTitle(String.format(CommonConstans.Twodecimalplaces, monthlyPower.get()));
//        monthlyPowerdto.setUnit("万kWh");
//        SocialContributionDto annualPowerdto = new SocialContributionDto();
//        annualPowerdto.setTitle(String.format(CommonConstans.Twodecimalplaces, annualPower.get()));
//        annualPowerdto.setUnit("万kWh");
//        SocialContributionDto completionRatioDto = new SocialContributionDto();
//        completionRatioDto.setTitle(completionRatio);
//        completionRatioDto.setUnit("%");
//        SocialContributionDto useHoursDto = new SocialContributionDto();
//        useHoursDto.setTitle(String.format(CommonConstans.Twodecimalplaces, (fdzannualPower.get() * CommonConstans.wkwhToMv / fdzInstallCapacity.get() + gfzannualPower.get() * CommonConstans.wkwhToMv / gfzinstallCapacity.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, false);
//            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(CommonConstans.Twodecimalplaces, getStationCaPACITYL(stationBasic.getStationNumber())));
                //设置风速辐照度
                List<Map<String, Object>> mapList;
                List<Map<String, Object>> mapList1;
                if (stationBasic.getStationType().equals("FDZ")) {
                    Map<String, List<String>> queryCondtion = new HashMap<>();
                    queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("30秒平均风速"));
                    queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
                    List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                    homeMapStationInfoDto.setSpeendOrirradiate(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getAvagerByEquipmentIndxName(result, "30秒平均风速")));
                    //homeMapStationInfoDto.setCurrentPower(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, "有功功率")));

                    Map<String, List<String>> queryCondtion1 = new HashMap<>();
                    queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                    queryCondtion1.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值"));
                    List<ESEquipments> esEquipmentsList = commonServiceImpl.getListDataByCondtions(queryCondtion1, null, ESEquipments.class);

                    homeMapStationInfoDto.setCurrentPower(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(esEquipmentsList, "220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值")));


                } else {
//                    Map<String, List<String>> queryCondtion = new HashMap<>();
//                    queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("有功功率"));
//                    queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
//                    Map<String, String> shouldQueryCondtion = new HashMap<>();
//                    shouldQueryCondtion.put(CommonConstans.QueryStringFrontMoudle, "逆变器");
//                    List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class, shouldQueryCondtion);
//
//                    homeMapStationInfoDto.setCurrentPower(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, "有功功率")));


                    Map<String, List<String>> queryCondtion2 = new HashMap<>();
                    queryCondtion2.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                    queryCondtion2.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("南瑞光差保护_313P"));
                    List<ESEquipments> esEquipmentsList = commonServiceImpl.getListDataByCondtions(queryCondtion2, null, ESEquipments.class);
                    homeMapStationInfoDto.setCurrentPower(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(esEquipmentsList, "南瑞光差保护_313P")));


                    Map<String, List<String>> queryCondtion1 = new HashMap<>();
                    queryCondtion1.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("WTX-801_25_WTX-801_总辐射"));
                    queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                    List<ESEquipments> result1 = commonServiceImpl.getListDataByCondtions(queryCondtion1, null, ESEquipments.class);
                    homeMapStationInfoDto.setSpeendOrirradiate(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result1, "WTX-801_25_WTX-801_总辐射")));
                }
                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);
                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(CommonConstans.Twodecimalplaces, total.get());
    }

    public String getPowerOfDaily(List<StationBasic> stationBasicList) {
        AtomicReference<Double> total = new AtomicReference<>(0.0);
        stationBasicList.forEach(stationBasic -> {
            if (stationBasic.getFanGatewayId() != null) {
                try {
                    if ("FDZ".equals(stationBasic.getStationType())) {
                        Map<String, List<String>> queryCondtion = new HashMap<>();
                        queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("日发电量"));
                        queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
                        List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                        total.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
                    } else {
                        Map<String, List<String>> queryCondtion = new HashMap<>();
                        queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(CommonConstans.taiHeGenIndicatorDay));
                        queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                        List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                        total.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay)));
                    }
                } catch (Exception e) {

                }
            }
        });
        return String.format(CommonConstans.Twodecimalplaces, total.get());
    }
    //获取社会贡献

    /**
     * @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 = "年发电量";
            Double total1 = 0.00;
            if (!stationBasic.getStationType().equals("FDZ")) {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(CommonConstans.taiHeGenIndicatorYear));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total1 = commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear);
            } else {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(finalIndicator));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total1 = commonServiceImpl.getSumByEquipmentIndxName(result, finalIndicator);
            }
            Double finalTotal = total1;
            total.updateAndGet(v -> v + finalTotal);
        });
        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<>();
            Double total = 0.00;
            String finalIndicator = "月发电量";
            if (!stationBasic.getStationType().equals("FDZ")) {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(finalIndicator));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total = commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth);
            } else {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(finalIndicator));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total = commonServiceImpl.getSumByEquipmentIndxName(result, finalIndicator);
            }
            Double finalTotal = total;
            monthlyPower.updateAndGet(v -> v + finalTotal);
        });
        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", "0", String.format(CommonConstans.Twodecimalplaces, monthlyPower.get()));
        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<StationCacheInfoDto> stationCacheInfoDtoList = new ArrayList<>();
        stationCacheInfoDtoList = commonServiceImpl.getListStationCacheInfoDto();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationCacheInfoDtoList = stationCacheInfoDtoList.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getBelongArea().equals(areaName)).collect(Collectors.toList());
        }

        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().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);
        stationCacheInfoDtoList.forEach( stationCacheInfoDto->{
            if ("FDZ".equals(stationCacheInfoDto.getStationType())) {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("日发电量", "月发电量", "年发电量"));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getFanGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                dailyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
                monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量")));
                annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));
            } else {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, CommonConstans.taiHeGenIndicator);
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getBoosterGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                dailyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay)));
                monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth)));
                annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear)));
            }
        });
        HashMap<String, String> dayHashMap = new HashMap<>();
        dayHashMap.put("title", String.format(CommonConstans.Fourdecimalplaces, dailyPower.get()) + "万KWh");
        HashMap<String, String> monthHashMap = new HashMap<>();
        monthHashMap.put("title", String.format(CommonConstans.Fourdecimalplaces, monthlyPower.get()) + "万KWh");
        HashMap<String, String> annualHashMap = new HashMap<>();
        annualHashMap.put("title", String.format(CommonConstans.Fourdecimalplaces, annualPower.get()) + "万KWh");
        HashMap<String, String> totalHashMap = new HashMap<>();
        totalHashMap.put("title", String.format(CommonConstans.Fourdecimalplaces, 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 = "月发电量";
            Double total = 0.00;
            if (!stationBasic.getStationType().equals("FDZ")) {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(finalIndicator));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total = commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth);
            } else {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(finalIndicator));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total = commonServiceImpl.getSumByEquipmentIndxName(result, finalIndicator);
            }
            Double finalTotal = total;
            monthlyPower.updateAndGet(v -> v + finalTotal);
        });
        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", "0", String.format(CommonConstans.Twodecimalplaces, 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<StationCacheInfoDto> stationCacheInfoDtoList = new ArrayList<>();
        stationCacheInfoDtoList = commonServiceImpl.getListStationCacheInfoDto();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationCacheInfoDtoList = stationCacheInfoDtoList.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getBelongArea().equals(areaName)).collect(Collectors.toList());
        }

        HashMap<String, List<String>> hashMap = new HashMap<>();
        List<String> xList = new ArrayList<>();
        List<String> yList = new ArrayList<>();
        AtomicReference<Double> total = new AtomicReference<>(0.00);
        //月发电量
        String finalIndicator = "月发电量";
        stationCacheInfoDtoList.forEach(stationCacheInfoDto -> {
            List<Map<String, Object>> mapListData = new ArrayList<>();
            if (!stationCacheInfoDto.getStationType().equals("FDZ")) {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(CommonConstans.taiHeGenIndicatorMonth));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getBoosterGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total.set(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth));
            } else {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(finalIndicator));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getFanGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total.set(commonServiceImpl.getSumByEquipmentIndxName(result, finalIndicator));
            }
            stationCacheInfoDto.setAddress(String.format(CommonConstans.Twodecimalplaces, (total.get())*100/getPlanGenByStationIdAndMonth(stationCacheInfoDto.getStationId())));
        });
        List<StationCacheInfoDto> sorted = stationCacheInfoDtoList.stream().sorted(Comparator.comparing(StationCacheInfoDto::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"));
        }
        AtomicReference<String> indicator = new AtomicReference<>("日发电量");
        if (tabValue.equals("1")) {
            indicator.set("月发电量");
        } else if (tabValue.equals("2")) {
            indicator.set("年发电量");
        }
        //填写发电小时数
        stationBasicListAll.forEach(stationBasic -> {
            Double install1 = getStationCaPACITYL(stationBasic.getStationNumber());
            BigDecimal gfInstall = new BigDecimal(String.format("%.2f", install1));
            Double total = 0.00;
            List<Map<String, Object>> mapListData = new ArrayList<>();
            if (!stationBasic.getStationType().equals("FDZ")) {
                indicator.set(CommonConstans.taiHeGenIndicatorDay);
                if (tabValue.equals("1")) {
                    indicator.set(CommonConstans.taiHeGenIndicatorMonth);
                } else if (tabValue.equals("2")) {
                    indicator.set(CommonConstans.taiHeGenIndicatorYear);
                }
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(indicator.get()));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total = commonServiceImpl.getSumByEquipmentIndxName(result, indicator.get());

            } else {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(indicator.get()));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total = commonServiceImpl.getSumByEquipmentIndxName(result, indicator.get());
            }
            stationBasic.setAddress(String.format(CommonConstans.Twodecimalplaces, (total * 10) / gfInstall.doubleValue()));
            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", "0.00h");
            }
            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", "0.00h");
            }
            mapList.add(stringHashMap);
        }
        page.setRecords(mapList);
        //组装数据
        return page;
    }

    public void getTotalData() {
        //计算所有场站年计划完成量
        int year = Calendar.getInstance().get(Calendar.YEAR);
        LambdaQueryWrapper<StationPlan> query = new LambdaQueryWrapper<>();
        query.eq(StationPlan::getYear, String.valueOf(year));
        List<StationPlan> stationPlans = stationPlanMapper.selectList(query);
        double yearValue = stationPlans.stream().mapToDouble(StationPlan::getValue).sum();
        double fdzValue = stationPlans.stream().filter(e -> e.getStationType().equals("FDZ")).mapToDouble(StationPlan::getValue).sum();
        double gfvalue = yearValue - fdzValue;

        //查询风电站年计划完成量
//
//        List<StationCacheInfoDto> listStationCacheInfoDto = commonServiceImpl.getListStationCacheInfoDto();
//        List<String> fdz = listStationCacheInfoDto.stream().filter(e -> e.getStationType().equals("FDZ")).map(StationCacheInfoDto::getStationId).collect(Collectors.toList());
//        LambdaQueryWrapper<StationPlan> queryWrapper =  new LambdaQueryWrapper<>();
//        queryWrapper.eq(StationPlan::getYear,String.valueOf(year));
//        queryWrapper.in(StationPlan::getStationBasicId,fdz);
//        List<StationPlan> fdzPlans = stationPlanMapper.selectList(queryWrapper);
//        double fdzValue =  fdzPlans.stream().mapToDouble(StationPlan::getValue).sum();


        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<>();
        Double powerOfDayFD = 0.0000;
        Double powerOfMonthFD = 0.0000;
        Double powerOfAnnualFD = 0.0000;
        Double powerOfDayGF = 0.0000;
        Double powerOfMonthGF = 0.0000;
        Double powerOfAnnualGF = 0.0000;
        for (int i = 0; i < fdzList.size(); i++) {
            StationBasic stationBasic = fdzList.get(i);
            Map<String, List<String>> queryCondtion = new HashMap<>();
            queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("日发电量", "月发电量", "年发电量"));
            queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
            List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
            powerOfDayFD = powerOfDayFD + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量"));
            powerOfMonthFD = powerOfMonthFD + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量"));
            powerOfAnnualFD = powerOfAnnualFD + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量"));
        }
        for (int i = 0; i < gfList.size(); i++) {
            StationBasic stationBasic = gfList.get(i);
            Map<String, List<String>> queryCondtion = new HashMap<>();
            queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, CommonConstans.taiHeGenIndicator);
            queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
            List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
            powerOfDayGF = powerOfDayGF + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay));
            powerOfMonthGF = powerOfMonthGF + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth));
            powerOfAnnualGF = powerOfAnnualGF + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear));

        }
        HashMap<String, String> stringHashMap4 = new HashMap<>();
        stringHashMap4.put("title", String.format(CommonConstans.Fourdecimalplaces, powerOfDayFD) + "/" + String.format(CommonConstans.Fourdecimalplaces, powerOfDayGF));
        list1.add(stringHashMap4);
        HashMap<String, String> stringHashMap5 = new HashMap<>();
        stringHashMap5.put("title", String.format(CommonConstans.Fourdecimalplaces, powerOfMonthFD) + "/" + String.format(CommonConstans.Fourdecimalplaces, powerOfMonthGF));
        list1.add(stringHashMap5);
        HashMap<String, String> stringHashMap6 = new HashMap<>();
        stringHashMap6.put("title", String.format(CommonConstans.Fourdecimalplaces, powerOfAnnualFD) + "/" + String.format(CommonConstans.Fourdecimalplaces, powerOfAnnualGF));
        list1.add(stringHashMap6);
        HashMap<String, String> stringHashMap7 = new HashMap<>();
        stringHashMap7.put("title", String.format(CommonConstans.Twodecimalplaces, (powerOfAnnualFD * 100) / fdzValue) + "/" + String.format(CommonConstans.Twodecimalplaces, (powerOfAnnualGF * 100) / gfvalue));
        list1.add(stringHashMap7);
        HashMap<String, String> stringHashMap8 = new HashMap<>();
        stringHashMap8.put("title", String.format(CommonConstans.Twodecimalplaces, (powerOfAnnualFD * CommonConstans.wkwhToMv) / fdzInstall.doubleValue()) + "/" + String.format(CommonConstans.Twodecimalplaces, (powerOfAnnualGF * CommonConstans.wkwhToMv) / gfInstall.doubleValue()));
        list1.add(stringHashMap8);
        page1.setRecords(list1);
        HashMap<String, String> stringHashMap9 = new HashMap<>();
        stringHashMap9.put("title", String.format(CommonConstans.Fourdecimalplaces, powerOfDayFD + powerOfDayGF));
        list2.add(stringHashMap9);
        HashMap<String, String> stringHashMap10 = new HashMap<>();
        stringHashMap10.put("title", String.format(CommonConstans.Fourdecimalplaces, powerOfMonthFD + powerOfMonthGF));
        list2.add(stringHashMap10);
        HashMap<String, String> stringHashMap11 = new HashMap<>();
        stringHashMap11.put("title", String.format(CommonConstans.Fourdecimalplaces, powerOfAnnualFD + powerOfAnnualGF));
        list2.add(stringHashMap11);
        HashMap<String, String> stringHashMap12 = new HashMap<>();
        stringHashMap12.put("title", String.format(CommonConstans.Twodecimalplaces, ((powerOfAnnualFD + powerOfAnnualGF) * 100) / yearValue));
        list2.add(stringHashMap12);
        page2.setRecords(list2);
        Double totalAnnual = (powerOfAnnualFD + powerOfAnnualGF);
        HashMap<String, String> stringHashMap13 = new HashMap<>();
        stringHashMap13.put("title1", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.carbonDioxide * CommonConstans.kgToT)));
        stringHashMap13.put("title2", "二氧化碳减排量（t）");
        list3.add(stringHashMap13);
        HashMap<String, String> stringHashMap14 = new HashMap<>();
        stringHashMap14.put("title1", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.standardCoal * CommonConstans.kgToT)));
        stringHashMap14.put("title2", "节约标准煤（t）");
        list3.add(stringHashMap14);
        HashMap<String, String> stringHashMap15 = new HashMap<>();
        stringHashMap15.put("title1", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.toner * CommonConstans.kgToT)));
        stringHashMap15.put("title2", "碳粉尘减排量（t）");
        list3.add(stringHashMap15);
        HashMap<String, String> stringHashMap16 = new HashMap<>();
        stringHashMap16.put("title1", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.sulfurDioxide * CommonConstans.kgToT)));
        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")) {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("年发电量"));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                stationBasic.setAddress(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));
            } else {
                Map<String, List<String>> queryCondtion = new HashMap<>();
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList(CommonConstans.taiHeGenIndicatorYear));
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));

                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                stationBasic.setAddress(String.format(CommonConstans.Twodecimalplaces, commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear)));
            }
        });
        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) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        HashMap<String, Object> result = new HashMap<>();
        List<HashMap<String, Object>> hashMapList = new ArrayList<>();
        List<IndicatorData> indicatorDataList = new ArrayList<>();
        if (stationBasic.getStationType().equals("FDZ")) {
            indicatorDataList = indicatorDataMapper.selectDataByequipmentIndexNameAndtime("220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值", date + " 00:00:00", date + " 23:59:59", stationBasic.getBoosterGatewayId());
        } else {
            indicatorDataList = indicatorDataMapper.selectDataByequipmentIndexNameAndtime("南瑞光差保护_313P", date + " 00:00:00", date + " 23:59:59", stationBasic.getBoosterGatewayId());
        }
        //x轴数据
        List<String> xdata = new ArrayList<>();
        //实时有功功率
        List<String> currentPowerYdata = new ArrayList<>();
        //短期功率预测
        List<String> shortPowerYdata = new ArrayList<>();
        //超短期功率预测
        List<String> superPowerShortYdata = new ArrayList<>();
        if (ObjectUtils.isEmpty(indicatorDataList)) {
            for (int i = 0; i < 25; i++) {
                xdata.add(String.format("%02d", i) + ":00");
                currentPowerYdata.add("0.00");
                shortPowerYdata.add("0.00");
                superPowerShortYdata.add("0.00");
            }
        } else {
            for (int i = 0; i < indicatorDataList.size(); i++) {
                IndicatorData indicatorData = indicatorDataList.get(i);
                xdata.add(DateUtil.format(indicatorData.getCreatedTime(), "HH:mm"));
                currentPowerYdata.add(String.format(CommonConstans.Twodecimalplaces, indicatorData.getValueF()));
                shortPowerYdata.add("0.00");
                superPowerShortYdata.add("0.00");
            }
        }
        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(CommonConstans.Twodecimalplaces, currentPowerYdata.stream().mapToDouble(Double::parseDouble).min().getAsDouble());
//        String shortMin = String.format(CommonConstans.Twodecimalplaces, shortPowerYdata.stream().mapToDouble(Double::parseDouble).min().getAsDouble());
//        String supreMin = String.format(CommonConstans.Twodecimalplaces, 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("0");
        sj1.add("0:00");
        gz.add("0");
        sj1.add("0:00");

        String currentMax = String.format(CommonConstans.Twodecimalplaces, currentPowerYdata.stream().mapToDouble(Double::parseDouble).max().getAsDouble());
//        String shortMax = String.format(CommonConstans.Twodecimalplaces, shortPowerYdata.stream().mapToDouble(Double::parseDouble).max().getAsDouble());
//        String supreMax = String.format(CommonConstans.Twodecimalplaces, superPowerShortYdata.stream().mapToDouble(Double::parseDouble).max().getAsDouble());
        List<String> zdz = new ArrayList<>();
        List<String> sj2 = new ArrayList<>();
        zdz.add(currentMax);
        zdz.add("0");
        zdz.add("0");
        sj2.add(xdata.get(currentPowerYdata.indexOf(currentMax)));
        sj2.add("0:00");
        sj2.add("0:00");
        String currentAvg = String.format(CommonConstans.Twodecimalplaces, currentPowerYdata.stream().mapToDouble(Double::parseDouble).average().getAsDouble());
//        String shortAvg = String.format(CommonConstans.Twodecimalplaces, shortPowerYdata.stream().mapToDouble(Double::parseDouble).average().getAsDouble());
//        String supreAvg = String.format(CommonConstans.Twodecimalplaces, superPowerShortYdata.stream().mapToDouble(Double::parseDouble).average().getAsDouble());
        List<String> pjz = new ArrayList<>();
        List<String> fjl = new ArrayList<>();
        pjz.add(currentAvg);
        pjz.add("0");
        pjz.add("0");
        fjl = Arrays.asList("0.00", "0.00", "0.00");

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

    public HashMap<String, String> getSecDays(String secStartDate) {
        HashMap<String, String> result = new HashMap<>();
        result.put("title", String.valueOf(DateUtil.between(DateUtil.parse(secStartDate), DateUtil.date(), DateUnit.DAY)));
        return result;
    }

    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(CommonConstans.Twodecimalplaces, total.get()));
        return hashMap;
    }

    //获取有功功率
    public HashMap<String, String> getActivePowerByAreaName(String areaName) {
        HashMap<String, String> hashMap = new HashMap<>();
        AtomicReference<Double> total = new AtomicReference<>(0.0);
        AtomicReference<Double> total1 = new AtomicReference<>(0.0);
        List<StationBasic> stationBasicListAll = new ArrayList<>();
        Map<String, List<String>> queryCondtion = new HashMap<>();
        Map<String, List<String>> queryCondtion1 = new HashMap<>();
        if (!ObjectUtils.isEmpty(areaName)) {
            stationBasicListAll = getListOfStationBasicByAreaName(areaName);
        } else {
            stationBasicListAll = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("fan_gateway_id"));
        }
        stationBasicListAll.forEach(stationBasic -> {

            if (stationBasic.getStationType().equals("FDZ")) {
                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值"));
                List<ESEquipments> esEquipmentsList = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
                total.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(esEquipmentsList, "220kV夏雩线212线路测控装置PCS-9705TA有功功率一次值"));

            } else {
                queryCondtion1.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getBoosterGatewayId()));
                queryCondtion1.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("南瑞光差保护_313P"));
                List<ESEquipments> esEquipmentsList = commonServiceImpl.getListDataByCondtions(queryCondtion1, null, ESEquipments.class);
                total.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(esEquipmentsList, "南瑞光差保护_313P")*CommonConstans.kwToMv);
            }
        });
        //有功功率换算
        hashMap.put("title", String.format(CommonConstans.Twodecimalplaces, total.get()));
        return hashMap;
    }

    public Double keepFourdecimalPlaces(Double param) {
        return Double.valueOf(String.format("%.4f", param));
    }
    public Double getPlanGenByStationIdAndMonth(String stationId){
        String [] dates = DateUtil.today().split("-");
        return stationPlanMapper.getPlanGenByStationIdAndMonth(stationId,dates[0], String.valueOf(Integer.valueOf(dates[1])));
    }
}
