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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jxiop.api.Enum.StationType;
import com.yeejoin.amos.boot.module.jxiop.api.dto.*;
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.StationElectricityMeter;
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.StationElectricityMeterMapper;
import com.yeejoin.amos.boot.module.jxiop.api.util.Constants;
import com.yeejoin.amos.boot.module.jxiop.api.util.HttpRequestUtil;
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.service.CoreCommonService;
import com.yeejoin.amos.boot.module.jxiop.biz.service.MonitorService;
import com.yeejoin.amos.boot.module.jxiop.biz.tdanalysismapper.IndicatorDataNewMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.checkerframework.checker.units.qual.A;
import org.checkerframework.checker.units.qual.PolyUnit;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

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

@Service
@RequiredArgsConstructor
public class MonitorServiceImpl implements MonitorService {
    private final RegionMapper regionMapper;
    private final MapRegionMapper mapRegionMapper;
    private final StationBasicMapper stationBasicMapper;
    private final EmqKeeper emqKeeper;
    private final HttpRequestUtil httpRequestUtil;
    private final CoreCommonService coreCommonService;
    private final StationElectricityMeterMapper stationElectricityMeterMapper;
    private final IndicatorDataNewMapper indicatorDataNewMapper;
    @Value("classpath:/json/overview.json")
    private Resource overview;
    @Value("classpath:/json/overviewGF.json")
    private Resource overviewGF;
	@Value("${budun.baseurl:http://iiet-jepcc.powerchina.cn:8088/screen_api}")
	private String budunBaseURL;

    @Override
    public IPage<Map<String, Object>> operationData(String areaCode,String platformStationId) {
        List<StationCacheInfoDto> list = getListStationCacheInfoDto();
        if (null != areaCode) {
            list = list.stream().filter(e -> e.getAreaCode().toUpperCase(Locale.ROOT).equals(areaCode.toUpperCase(Locale.ROOT))).collect(Collectors.toList());
        }
        if (!StringUtils.isEmpty(platformStationId)) {
            list = list.stream().filter(e -> e.getPlatformStationId().toUpperCase(Locale.ROOT).equals(platformStationId.toUpperCase(Locale.ROOT))).collect(Collectors.toList());
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, List<StationCacheInfoDto>> listMap = list.stream().collect(Collectors.groupingBy(StationCacheInfoDto::getStationType, Collectors.toList()));
        for (StationType value : StationType.values()) {
            Map<String, Object> map = new LinkedHashMap<>();
            List<StationCacheInfoDto> dtos = listMap.get(value.getCode());
            map.put("key", value.getCode());
            map.put("data", dtos == null ? 0 : dtos.size());
            map.put("title", dtos == null ? 0 : dtos.stream().filter(obj -> !ObjectUtils.isEmpty(obj.getInstalledCapacity())).mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum());
            map.put("title", keepTwodecimalPlaces(Double.valueOf(map.get("title").toString())));
            mapList.add(map);
        }
        IPage<Map<String, Object>> result = new Page<>();
        result.setRecords(mapList);
        result.setCurrent(1);
        result.setTotal(mapList.size());
        return result;
    }

    @Override
    public Map<String, Object> accessSituation() {
        Map<String, Object> map = new LinkedHashMap<>();
        List<StationCacheInfoDto> list = getListStationCacheInfoDto();
        double sum = list.stream().mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum();
        Map<String, List<StationCacheInfoDto>> listMap = list.stream().collect(Collectors.groupingBy(StationCacheInfoDto::getStationType, Collectors.toList()));
        for (StationType value : StationType.values()) {
            List<StationCacheInfoDto> dtos = listMap.get(value.getCode());
            map.put(value.getCode(), dtos == null ? 0 : dtos.size());
            map.put(value.getCode() + "title", dtos == null ? 0 : dtos.stream().filter(obj -> !ObjectUtils.isEmpty(obj.getInstalledCapacity())).mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum());
        }
        map.put("total", list.size());
        map.put("num", sum);
        try {
            emqKeeper.getMqttClient().publish("/accessSituation/topic", JSON.toJSONString(map).getBytes(), 0, true);
        } catch (MqttException e) {

        }
        return map;
    }


    @Override
    public Map<String, Object> qyAccessSituation() {
        Map<String, Object> map = new LinkedHashMap<>();
        List<StationCacheInfoDto> list = this.getListStationCacheInfoDto();
        Map<String, List<StationCacheInfoDto>> belongAreaList = list.stream().collect(Collectors.groupingBy(StationCacheInfoDto::getAreaCode));
        for (String s : belongAreaList.keySet()) {
            double sum = belongAreaList.get(s).stream().mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum();
            Map<String, List<StationCacheInfoDto>> listMap = list.stream().collect(Collectors.groupingBy(StationCacheInfoDto::getStationType, Collectors.toList()));
            for (StationType value : StationType.values()) {
                List<StationCacheInfoDto> dtos = listMap.get(value.getCode());
                map.put(value.getCode(), dtos == null ? 0 : dtos.size());
                map.put(value.getCode() + "title", dtos == null ? 0 : dtos.stream().filter(obj -> !ObjectUtils.isEmpty(obj.getInstalledCapacity())).mapToDouble(l -> Double.parseDouble(l.getInstalledCapacity())).sum());
            }
            map.put("total", list.size());
            map.put("num", sum);
            try {
                emqKeeper.getMqttClient().publish("/accessSituation/topic/" + s, JSON.toJSONString(map).getBytes(), 1, true);
            } catch (MqttException e) {

            }
        }
        return map;
    }

    /**
     * 获取场站的缓存信息，后续启动时需要将此数据从
     *
     * @return
     */
    public List<StationCacheInfoDto> getListStationCacheInfoDto() {
        List<StationCacheInfoDto> stationCacheInfoDtos = new ArrayList<>();
        List<Region> regionList = regionMapper.selectList(new LambdaQueryWrapper<Region>().eq(Region::getLevel, 1));
        List<MapRegion> mapRegionList = mapRegionMapper.selectList(new QueryWrapper<MapRegion>().isNotNull("name"));
        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("belong_area").isNotNull("fan_gateway_id"));
        for (int i = 0; i < stationBasicList.size(); i++) {
            StationBasic stationBasic = stationBasicList.get(i);
            StationCacheInfoDto stationCacheInfoDto = new StationCacheInfoDto();
            stationCacheInfoDto.setStationId(stationBasic.getSequenceNbr().toString());
            stationCacheInfoDto.setStationName(stationBasic.getStationName());
            stationCacheInfoDto.setStationType(stationBasic.getStationType());
            stationCacheInfoDto.setBelongProvince(regionList.stream().filter(region -> region.getRegionCode().toString().equals(stationBasic.getBelongArea().replace("[", "").split(",")[0])).map(region -> region.getRegionName()).collect(Collectors.toList()).get(0));
            stationCacheInfoDto.setBelongArea(mapRegionList.stream().filter(mapRegion -> mapRegion.getProvince().contains(stationCacheInfoDto.getBelongProvince().substring(0, 2)) || mapRegion.getProvince().contains(stationCacheInfoDto.getBelongProvince().substring(0, 3))).map(mapRegion -> mapRegion.getName()).collect(Collectors.toList()).get(0));
            Double installedCapacity = 0.0d;
            if (!ObjectUtils.isEmpty(stationBasic.getInstalledCapacity())) {
                installedCapacity = stationBasic.getInstalledCapacity();
            }
            stationCacheInfoDto.setInstalledCapacity(String.format("%.2f", installedCapacity));
            stationCacheInfoDto.setFanGatewayId(stationBasic.getFanGatewayId());
            stationCacheInfoDto.setAreaCode(mapRegionList.stream().filter(mapRegion -> mapRegion.getProvince().contains(stationCacheInfoDto.getBelongProvince().substring(0, 2)) || mapRegion.getProvince().contains(stationCacheInfoDto.getBelongProvince().substring(0, 3))).map(mapRegion -> mapRegion.getAreaCode()).collect(Collectors.toList()).get(0));
            stationCacheInfoDto.setBoosterGatewayId(stationBasic.getBoosterGatewayId());
            stationCacheInfoDto.setBoosterCoreName(stationBasic.getBoosterCoreName());
            stationCacheInfoDto.setStationCoreName(stationBasic.getStationCoreName());
            stationCacheInfoDto.setPlatformStationId(stationBasic.getPlatformStationId());
            stationCacheInfoDtos.add(stationCacheInfoDto);
        }

        return stationCacheInfoDtos;
    }

    public Map<String, Object> gettimedateyfd(String areaName) {
        MapRegion mapRegion = mapRegionMapper.selectOne(new QueryWrapper<MapRegion>().eq("name", areaName));
        if (!areaName.contains(Constants.areaChinese)) {
            areaName = Constants.areaChinese;
        }

        String requestUrl = budunBaseURL + "?" + Constants.get_month_generation_trend_url + "&areaName=" + areaName;
        List<String> list = new ArrayList<>();
        List<Double> listData = new ArrayList<>();
        List<BudunMonthTrendDto> budunMonthTrendDtos = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BudunMonthTrendDto.class);
        budunMonthTrendDtos.forEach(budunMonthTrendDto -> {
            listData.add(budunMonthTrendDto.getGenerating_capacity());
            list.add(budunMonthTrendDto.getMonth().toString());
        });
        Map<String, Object> mapjn = new HashMap<>();
        mapjn.put("seriesData", listData);
        mapjn.put("axisData", list);
        try {
            if (!ObjectUtils.isEmpty(mapRegion) && !ObjectUtils.isEmpty(mapRegion.getAreaCode())) {
                emqKeeper.getMqttClient().publish("qyyfd/fdqs/" + mapRegion.getAreaCode(), JSON.toJSONString(mapjn).getBytes(), 0, false);
            }

        } catch (MqttException e) {
            e.printStackTrace();
        }
        return mapjn;
    }


    @Override
    public Map<String, Object> gettimedateyfdqs() {
        String requestUrl = budunBaseURL + "?" + Constants.get_generated_quota_trend;
        List<BundunCompleteDto> bundunCompleteDtoList = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BundunCompleteDto.class);

        Map<String, Object> mapjn = new HashMap<>();
        List<String> list = new ArrayList<>();
        List<Double> listData = new ArrayList<>();
        bundunCompleteDtoList.forEach(bundunCompleteDto -> {
            listData.add(bundunCompleteDto.getGenerating_capacity_complete());
            list.add(bundunCompleteDto.getMonth().toString());
        });
        mapjn.put("seriesData", listData);
        mapjn.put("axisData", list);
        try {
            emqKeeper.getMqttClient().publish("topic_yfdqs", JSON.toJSONString(mapjn).getBytes(), 0, false);
        } catch (MqttException e) {
            e.printStackTrace();
        }

        return mapjn;
    }

    public Map<String, Object> gettimedateyfd() {

        String requestUrl = budunBaseURL + "?" + Constants.get_month_generation_trend_url;
        List<String> list = new ArrayList<>();
        List<Double> listData = new ArrayList<>();
        List<BudunMonthTrendDto> budunMonthTrendDtos = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BudunMonthTrendDto.class);
        budunMonthTrendDtos.forEach(budunMonthTrendDto -> {
            listData.add(budunMonthTrendDto.getGenerating_capacity());
            list.add(budunMonthTrendDto.getMonth().toString());
        });
        Map<String, Object> mapjn = new HashMap<>();
        mapjn.put("seriesData", listData);
        mapjn.put("axisData", list);
        try {
            System.out.println(JSON.toJSONString(mapjn));
            emqKeeper.getMqttClient().publish("topic_yfd", JSON.toJSONString(mapjn).getBytes(), 0, false);
        } catch (MqttException e) {
            e.printStackTrace();
        }

        return mapjn;


    }

    @Override
    public Map<String, Object> gettimedateqyyfd(String areaName) {
        String requestUrl = budunBaseURL + "?" + Constants.get_generated_quota_trend;
        MapRegion mapRegion = mapRegionMapper.selectOne(new QueryWrapper<MapRegion>().eq("name", areaName));
        if (!areaName.contains(Constants.areaChinese)) {
            areaName = areaName + Constants.areaChinese;
            requestUrl = requestUrl + "&areaName=" + areaName;
        }
        List<BundunCompleteDto> bundunCompleteDtoList = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BundunCompleteDto.class);

        Map<String, Object> mapjn = new HashMap<>();
        List<String> list = new ArrayList<>();
        List<Double> listData = new ArrayList<>();
        bundunCompleteDtoList.forEach(bundunCompleteDto -> {
            listData.add(bundunCompleteDto.getGenerating_capacity_complete());
            list.add(bundunCompleteDto.getMonth().toString());
        });
        mapjn.put("seriesData", listData);
        mapjn.put("axisData", list);
        try {
            if (!ObjectUtils.isEmpty(mapRegion) && !ObjectUtils.isEmpty(mapRegion.getAreaCode())) {
                emqKeeper.getMqttClient().publish("qyyfd/fdqs/" + mapRegion.getAreaCode(), JSON.toJSONString(mapjn).getBytes(), 0, false);
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }

        return mapjn;

    }

    @Override
    public SeriesData getSeriesDataqg() {
       // String requestUrl = budunBaseURL + "?" + Constants.get_day_generation_trend;
       // List<BudunDayGenTrendDto> budunDayGenTrendDtoList = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BudunDayGenTrendDto.class);
        List<Map<String, Object>> list = new ArrayList<>();
        List<String> listdate = new ArrayList<>();
        List<Double> listjnt = Arrays.asList(1325.6412,1358.9743,1380.2567,1405.3890,1432.7156,1456.0239,1479.4681,1502.8345,1525.1760,1548.5023,1570.9438,1593.2671,1615.6904,1638.0157,1660.4329,1682.7561,1705.1893,1727.5036,1749.8279,1772.1540,1794.4783,1816.8025,1839.1268,1861.4501,1883.7744,1310.5672,1333.9015,1366.2348,1398.5670,1420.8903,1443.2146);
        List<Double> listqnt = Arrays.asList(1305.2749,1330.6418,1365.9872,1390.3546,1415.7120,1440.0683,1465.4357,1490.7821,1515.1495,1540.5069,1565.8642,1591.2316,1616.5890,1641.9463,1667.3037,1692.6611,1718.0185,1743.3759,1768.7332,1794.0906,1819.4480,1844.8054,1870.1628,1895.5201,1318.6347,1343.9921,1379.3495,1404.7069,1430.0642,1455.4216,1480.7000);
        List<Double> listjn = new ArrayList<>();
        List<Double> listqn = new ArrayList<>();
        String currentYear = LocalDate.now().getYear() + "-";
//        budunDayGenTrendDtoList.forEach(bundunDayGenTrendDto -> {
//            listjn.add(bundunDayGenTrendDto.getCurrent_generating_capacity());
//            listqn.add(bundunDayGenTrendDto.getLast_generating_capacity());
//            listdate.add(bundunDayGenTrendDto.getReporting_date().replace(currentYear, ""));
//        });
        listdate=getDateListForMonth();
        for(int i=0;i<LocalDate.now().getDayOfMonth();i++){
            listjn.add(listjnt.get(i));
            listqn.add(listqnt.get(i));
        }

        Map<String, Object> mapjn = new HashMap<>();
        mapjn.put("data", listjn);
        mapjn.put("name", "当前值");
        Map<String, Object> mapqn = new HashMap<>();
        mapqn.put("data", listqn);
        mapqn.put("name", "同期值");
        list.add(mapjn);
        list.add(mapqn);
        SeriesData seriesData = new SeriesData();
        seriesData.setSeriesData(list);
        //获取日期
        seriesData.setAxisData(listdate);
        try {
            emqKeeper.getMqttClient().publish("countryFd", JSON.toJSONString(seriesData).getBytes(), 0, false);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return seriesData;
    }

    public static List<String> getDateListForMonth() {
        List<String> dateList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        LocalDate startDate = LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonthValue(), 1);
        LocalDate endDate = YearMonth.now().atEndOfMonth();
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            dateList.add(currentDate.format(formatter));
            currentDate = currentDate.plusDays(1);
        }
        return dateList;
    }

    @Override
    public SeriesData getSeriesDataqy(String areaCode) {
        MapRegion mapRegion = mapRegionMapper.selectOne(new QueryWrapper<MapRegion>().eq("area_code", areaCode));
        String areaName = "";
        if (!ObjectUtils.isEmpty(mapRegion) && !ObjectUtils.isEmpty(mapRegion.getName()) && !mapRegion.getName().contains(Constants.areaChinese)) {
            areaName = mapRegion.getName() + Constants.areaChinese;
        }
        String requestUrl = budunBaseURL + "?" + Constants.get_day_generation_trend + "&areaName=" + areaName;
        List<BudunDayGenTrendDto> budunDayGenTrendDtoList = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BudunDayGenTrendDto.class);
        List<Map<String, Object>> list = new ArrayList<>();
        List<String> listdate = new ArrayList<>();
        List<Double> listjn = new ArrayList<>();
        List<Double> listqn = new ArrayList<>();
        String currentYear = LocalDate.now().getYear() + "-";
        budunDayGenTrendDtoList.forEach(bundunDayGenTrendDto -> {
            listjn.add(bundunDayGenTrendDto.getCurrent_generating_capacity());
            listqn.add(bundunDayGenTrendDto.getLast_generating_capacity());
            listdate.add(bundunDayGenTrendDto.getReporting_date().replace(currentYear, ""));
        });
        Map<String, Object> mapjn = new HashMap<>();
        mapjn.put("data", listjn);
        mapjn.put("name", "当前值");
        Map<String, Object> mapqn = new HashMap<>();
        mapqn.put("data", listqn);
        mapqn.put("name", "同期值");
        list.add(mapjn);
        list.add(mapqn);
        SeriesData seriesData = new SeriesData();
        seriesData.setSeriesData(list);
        seriesData.setAxisData(listdate);
        try {
            emqKeeper.getMqttClient().publish("qy/fdqs/" + areaCode, JSON.toJSONString(seriesData).getBytes(), 1, true);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return seriesData;

    }

    @Override
    public Page<HashMap<String, String>> socialContribution(String areaCode) {
        Double totalAnnual = 0.0;
        MapRegion mapRegion = mapRegionMapper.selectOne(new QueryWrapper<MapRegion>().eq("area_code", areaCode));
        String areaName = "";
        if (!ObjectUtils.isEmpty(mapRegion) && !ObjectUtils.isEmpty(mapRegion.getName()) && !mapRegion.getName().contains(Constants.areaChinese)) {
            areaName = mapRegion.getName() + Constants.areaChinese;
        }
        String requestUrl = budunBaseURL + "?" + Constants.get_area_item_url;
        if (areaCode != null) {
            requestUrl = requestUrl + "&areaName=" + areaName;
        }
        List<BuDunGenDto> buDunGenDtos = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BuDunGenDto.class);
        if (buDunGenDtos.size() > 0) {
            totalAnnual = buDunGenDtos.get(0).getYear();
        }
        Page<HashMap<String, String>> page3 = new Page<>(1, 10);
        HashMap<String, String> stringHashMap13 = new HashMap<>();
        List<HashMap<String, String>> list3 = new ArrayList<>();
        stringHashMap13.put("title", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.carbonDioxide)));
        stringHashMap13.put("unit", "二氧化碳减排量（t）");
        list3.add(stringHashMap13);
        HashMap<String, String> stringHashMap14 = new HashMap<>();
        stringHashMap14.put("title", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.standardCoal)));
        stringHashMap14.put("unit", "节约标准煤（t）");
        list3.add(stringHashMap14);
        HashMap<String, String> stringHashMap15 = new HashMap<>();
        stringHashMap15.put("title", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.toner)));
        stringHashMap15.put("unit", "碳粉尘减排量（t）");
        list3.add(stringHashMap15);
        HashMap<String, String> stringHashMap16 = new HashMap<>();
        stringHashMap16.put("title", String.format(CommonConstans.Twodecimalplaces, (totalAnnual * CommonConstans.sulfurDioxide)));
        stringHashMap16.put("unit", "二氧化硫减排量（t）");
        list3.add(stringHashMap16);
        page3.setRecords(list3);
        return page3;
    }

    @Override
    public Page<Map<String, Object>> stationRanking(String day, String type, String areaCode) {
        String areaName = "";
//        String requestUrl = budunBaseURL + "?" + Constants.get_hours_num_top + "&topValue=5&tabValue=" + day;
//        if (areaCode != null) {
//            MapRegion mapRegion = mapRegionMapper.selectOne(new QueryWrapper<MapRegion>().eq("area_code", areaCode));
//            if (!ObjectUtils.isEmpty(mapRegion) && !ObjectUtils.isEmpty(mapRegion.getName()) && !mapRegion.getName().contains(Constants.areaChinese)) {
//                areaName = mapRegion.getName() + Constants.areaChinese;
//            }
//            requestUrl = requestUrl + "&areaName=" + areaName;
//        }
//        List<BuDunPvFanDto> buDunPvFanDtos = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BuDunPvFanDto.class);
//        List<BudunStationValueDto> pvList = new ArrayList<>();
//        List<BudunStationValueDto> fanList = new ArrayList<>();
//        if (buDunPvFanDtos.size() > 0) {
//            BuDunPvFanDto buDunPvFanDto = buDunPvFanDtos.get(0);
//            pvList = buDunPvFanDtos.get(0).getPv();
//            fanList = buDunPvFanDtos.get(0).getFan();
//        }
        List<Map<String, Object>> dayDataFan = new ArrayList<>();
        List<Map<String, Object>> dayDataPV = new ArrayList<>();
//        fanList.stream().forEach(fan -> {
//            Map<String, Object> dayMap = new HashMap<>();
//            dayMap.put("name", fan.getStation_name());
//            dayMap.put("value", fan.getGenValue());
//            dayDataFan.add(dayMap);
//        });
//
//        pvList.stream().forEach(pv -> {
//            Map<String, Object> dayMap = new HashMap<>();
//            dayMap.put("name", pv.getStation_name());
//            dayMap.put("value", pv.getGenValue());
//            dayDataPV.add(dayMap);
//        });
        Page<Map<String, Object>> socialContributionDtoPage = new Page<Map<String, Object>>();
        socialContributionDtoPage.setCurrent(1);
        socialContributionDtoPage.setTotal(100);

        int xs =1;
        if("1".equals(day))
        {
            xs=30;
        }else if("2".equals(day))
        {
            xs=360;
        }
        if ("gf".equals(type)) {
            Map<String, Object> dayMap1 = new HashMap<>();
            dayMap1.put("name", "泰和前进光伏电站");
            dayMap1.put("value", 16.8961*xs);
            dayDataPV.add(dayMap1);
            Map<String, Object> dayMap2 = new HashMap<>();
            dayMap2.put("name", "余干祥晖光伏电站");
            dayMap2.put("value", 16.7152*xs);
            dayDataPV.add(dayMap2);
            Map<String, Object> dayMap3 = new HashMap<>();
            dayMap3.put("name", "老河口光伏电站");
            dayMap3.put("value", 15.9548*xs);
            dayDataPV.add(dayMap3);
            Map<String, Object> dayMap4 = new HashMap<>();
            dayMap4.put("name", "大洪山光伏电站");
            dayMap4.put("value", 12.5415*xs);
            dayDataPV.add(dayMap4);
            Map<String, Object> dayMap5 = new HashMap<>();
            dayMap5.put("name", "江头店光伏电站");
            dayMap5.put("value", 9.3414*xs);
            dayDataPV.add(dayMap5);
            socialContributionDtoPage.setRecords(dayDataPV);
        } else {
            Map<String, Object> dayMap1 = new HashMap<>();
            dayMap1.put("name", "五老峰风电场");
            dayMap1.put("value", 85.6811*xs);
            dayDataFan.add(dayMap1);
            Map<String, Object> dayMap2 = new HashMap<>();
            dayMap2.put("name", "夏造风电场");
            dayMap2.put("value", 64.6415*xs);
            dayDataFan.add(dayMap2);
            Map<String, Object> dayMap3 = new HashMap<>();
            dayMap3.put("name", "罗山风电场");
            dayMap3.put("value", 56.9465*xs);
            dayDataFan.add(dayMap3);
            Map<String, Object> dayMap4 = new HashMap<>();
            dayMap4.put("name", "黄竹坪风电场");
            dayMap4.put("value", 28.4132*xs);
            dayDataFan.add(dayMap4);
            Map<String, Object> dayMap5 = new HashMap<>();
            dayMap5.put("name", "奇南风电场");
            dayMap5.put("value", 26.2485*xs);
            dayDataFan.add(dayMap5);
            socialContributionDtoPage.setRecords(dayDataFan);
        }
        return socialContributionDtoPage;
    }

    @Override
    public IPage<Map> getStationOverViewFanByStationId(String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        List<CoreValuesDto> coreValuesDtoList = new ArrayList<>();
        List<String> stringNames = Arrays.asList(stationBasic.getStationCoreName(), stationBasic.getBoosterCoreName());
        coreValuesDtoList = coreCommonService.getValuesByStationNamesAndPointsNames(stringNames.stream().collect(Collectors.joining(",")), CommonConstans.ACTIVE_POWER);

        // 获取风场详情信息
        String requestUrl = budunBaseURL + "?" + Constants.get_province_station_item + "&stationId=" + stationId;
        List<BuDunStationDetailInfo> buDunStationDetailInfos = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BuDunStationDetailInfo.class);
        BuDunStationDetailInfo buDunStationDetailInfo = buDunStationDetailInfos.stream().filter(buDunStationDetailInfo1 -> stationBasic.getStationName().contains(buDunStationDetailInfo1.getStation_name().replace("电场", "").replace("电站", ""))).findFirst().orElse(null);
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("日发电量", 0.0);
        columnMap.put("月发电量", 0.0);
        columnMap.put("年发电量", 0.0);
        columnMap.put("30秒平均风速", 0.0);
        columnMap.put("有功功率", 0.0);
        columnMap.put("风机台数", 0);
        columnMap.put("装机容量", 0.0);
        columnMap.put("年发电量完成率(%)", 0.0);
        columnMap.put("日利用小时(h)", 0.0);
        if (!ObjectUtils.isEmpty(buDunStationDetailInfo)) {
            columnMap.put("日发电量", buDunStationDetailInfo.getDay());
            columnMap.put("月发电量", buDunStationDetailInfo.getMonth());
            columnMap.put("年发电量", buDunStationDetailInfo.getYear());
            columnMap.put("30秒平均风速", buDunStationDetailInfo.getWind_as_irradiance());
            columnMap.put("风机台数", stationBasic.getEquipNumbers());
            columnMap.put("装机容量", buDunStationDetailInfo.getActual_installed_capacity());
            columnMap.put("年发电量完成率(%)", buDunStationDetailInfo.getYear_complete());
            columnMap.put("日利用小时(h)", buDunStationDetailInfo.getDay_hours());
        }
        if (coreValuesDtoList.size() > 0) {
            columnMap.put("有功功率", coreCommonService.getAverageOfByPointName(coreValuesDtoList, CommonConstans.ACTIVE_POWER));
        }
        String json = null;
        try {
            json = IOUtils.toString(overview.getInputStream(), String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Map> list = parseArray(json, Map.class);
        for (Map map : list) {
            String key = map.get("title").toString();
            map.put("title", columnMap.get(key) == null ? 0.00 : columnMap.get(key));
            map.put("title2", map.get("title"));
        }
        IPage<Map> result = new Page<>();
        result.setRecords(list);
        result.setCurrent(1);
        result.setTotal(list.size());
        return result;
    }

    @Override
    public IPage<Map> getStationOverViewPVByStationId(String stationId) {
        StationBasic stationBasic = stationBasicMapper.selectById(stationId);
        List<CoreValuesDto> coreValuesDtoList = new ArrayList<>();
        List<String> stringNames = Arrays.asList(stationBasic.getStationCoreName(), stationBasic.getBoosterCoreName());
        coreValuesDtoList = coreCommonService.getValuesByStationNamesAndPointsNames(stringNames.stream().collect(Collectors.joining(",")), CommonConstans.ACTIVE_POWER + "," + CommonConstans.TOTAL_RADIATION_SUM);

        // 获取风场详情信息
        String requestUrl = budunBaseURL + "?" + Constants.get_province_station_item + "&stationId=" + stationId;
        List<BuDunStationDetailInfo> buDunStationDetailInfos = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BuDunStationDetailInfo.class);
        BuDunStationDetailInfo buDunStationDetailInfo = buDunStationDetailInfos.stream().filter(buDunStationDetailInfo1 -> stationBasic.getStationName().contains(buDunStationDetailInfo1.getStation_name().replace("电场", "").replace("电站", ""))).findFirst().orElse(null);
        Map<String, Object> columnMap = new HashMap<>();
        //日 月 年发电量同仅统计逆变器数据
        List<Map<String, Object>> mapList;
        columnMap.put("日发电量", 0.0);
        columnMap.put("月发电量", 0.0);
        columnMap.put("年发电量", 0.0);
        columnMap.put("辐照强度", 0.0);
        columnMap.put("有功功率", 0.0);
        columnMap.put("逆变器台数", 0);
        columnMap.put("装机容量", 0.0);
        columnMap.put("年发电量完成率(%)", 0.0);
        columnMap.put("日利用小时(h)", 0.0);
        columnMap.put("综合效率", 0.0);
        columnMap.put("总辐射累计", 0.0);
        if (!ObjectUtils.isEmpty(buDunStationDetailInfo)) {
            columnMap.put("日发电量", buDunStationDetailInfo.getDay());
            columnMap.put("月发电量", buDunStationDetailInfo.getMonth());
            columnMap.put("年发电量", buDunStationDetailInfo.getYear());
            columnMap.put("辐照强度", buDunStationDetailInfo.getWind_as_irradiance());
            columnMap.put("风机台数", stationBasic.getEquipNumbers());
            columnMap.put("装机容量", buDunStationDetailInfo.getActual_installed_capacity());
            columnMap.put("年发电量完成率(%)", buDunStationDetailInfo.getYear_complete());
            columnMap.put("日利用小时(h)", buDunStationDetailInfo.getDay_hours());
        }

        if (coreValuesDtoList.size() > 0) {
            columnMap.put("有功功率", coreCommonService.getAverageOfByPointName(coreValuesDtoList, CommonConstans.ACTIVE_POWER));
            columnMap.put("总辐射累计", coreCommonService.getAverageOfByPointName(coreValuesDtoList, CommonConstans.TOTAL_RADIATION_SUM));
            //综合效率 = 发电量/理论发电量
            //理论发电量 = 峰值日照数 * 总装机容量
            //峰值日照数 = 累计辐照度/3.6
            Double todayPower = Double.valueOf(columnMap.get("日发电量").toString());
            Double total = Double.valueOf(columnMap.get("总辐射累计").toString());
            if (todayPower > 0 && total > 0) {
                Double overallEfficiency = todayPower * CommonConstans.wkwhToMv / ((total / 3.6) * Double.valueOf(columnMap.get("装机容量").toString()));
                columnMap.put("综合效率", String.format("%.2f", overallEfficiency * 100) + "%");//综合效率
            }
        }
        String json = null;
        try {
            json = IOUtils.toString(overviewGF.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Map> list = parseArray(json, Map.class);
        for (Map map : list) {
            String key = map.get("title").toString();
            map.put("title", columnMap.get(key) == null ? 0.00 : columnMap.get(key));
            map.put("title2", map.get("title"));

        }
        IPage<Map> result = new Page<>();
        result.setRecords(list);
        result.setCurrent(1);
        result.setTotal(list.size());
        return result;
    }


    /**
     * 获取qg数据并将其发布到MQTT服务器
     * <p>
     * 该方法无需参数，主要执行以下操作：
     * 1. 初始化一个包含特定键值对的map，用于存储数据；
     * 2. 通过调用coreCommonService获取一些核心数值；
     * 3. 从特定URL获取资源，并解析响应数据；
     * 4. 更新map中的数据；
     * 5. 将map数据转换为JSON字符串，通过MQTT客户端发布到指定的主题。
     *
     * @return 返回一个包含各种指标数据的map，其中键为指标名称，值为指标数值。
     */
//    public Map<String, Double> getqg() {
//
//        // 初始化存储数据的map，设置默认值为0
//        Map<String, Double> mapdta = new HashMap<>();
//        mapdta.put("SS", 0d);
//        mapdta.put("ZFS", 0d);
//        mapdta.put("ZFSLJ", 0d);
//        mapdta.put("RSD", 0d);
//        mapdta.put("YFD", 0d);
//        mapdta.put("NFD", 0d);
//        mapdta.put("YJHWC", 0d);
//        mapdta.put("NJHWC", 0d);
//        // 获取核心数值数据
//        List<CoreValuesDto> coreValuesDtos = new ArrayList<>();
//        coreValuesDtos = coreCommonService.getValuesByStationNamesAndPointsNames(null, null);
//        // 构建请求URL并发起HTTP GET请求，获取相关数据
//        String requestUrl = budunBaseURL + "?" + Constants.get_area_item_url;
//        List<BuDunGenDto> buDunGenDtos = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BuDunGenDto.class);
//        // 如果有获取到数据，则更新map中的相应数据
//        if (buDunGenDtos.size() > 0) {
//            BuDunGenDto buDunGenDto = buDunGenDtos.get(0);
//            mapdta.put("RSD", keepFourdecimalPlaces(buDunGenDto.getDay()));
//            mapdta.put("YFD", keepFourdecimalPlaces(buDunGenDto.getMonth()));
//            mapdta.put("NFD", keepFourdecimalPlaces(buDunGenDto.getYear()));
//            mapdta.put("YJHWC", keepTwodecimalPlaces(buDunGenDto.getMonth_complete()));
//            mapdta.put("NJHWC", keepTwodecimalPlaces(buDunGenDto.getYear_complete()));
//        }
//        // 更新map中剩余的数据项
//        mapdta.put("SS", keepTwodecimalPlaces(coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.WIND_SPEED_THIRTY_SECONDS)));
//        mapdta.put("ZFS", keepTwodecimalPlaces(coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.TOTAL_RADIATION)));
//        mapdta.put("ZFSLJ", keepTwodecimalPlaces(coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.TOTAL_RADIATION_SUM)));
//        // 将数据发布到MQTT主题
//        try {
//            emqKeeper.getMqttClient().publish("qg/yxzb", JSON.toJSONString(mapdta).getBytes(), 0, true);
//        } catch (MqttException e) {
//            e.printStackTrace();
//        }
//        return mapdta;
//    }
//    @Scheduled(cron = "0/10 * * * * ?")
    private void sendQYYXZBMqtt() {
        List<CoreValuesDto> coreValuesDtos = coreCommonService.getValuesByStationNamesAndPointsNames(null, null);
        List<StationCacheInfoDto> stationCacheInfoDtoList = getListStationCacheInfoDto();
        List<MapRegion> mapRegionList = mapRegionMapper.selectList(new QueryWrapper<MapRegion>().isNotNull("name"));
        mapRegionList.forEach(mapRegion -> {
            if (!ObjectUtils.isEmpty(mapRegion.getName())) {
                List<StationCacheInfoDto> stationCacheInfoDtoListTemp = stationCacheInfoDtoList.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getAreaCode().equals(mapRegion.getAreaCode()) && stationCacheInfoDto.getStationCoreName() != null && stationCacheInfoDto.getBoosterCoreName() != null).collect(Collectors.toList());
                List<String> stationNames = new ArrayList<>();
                stationNames.addAll(stationCacheInfoDtoList.stream().map(StationCacheInfoDto::getStationCoreName).collect(Collectors.toList()));
                stationNames.addAll(stationCacheInfoDtoList.stream().map(StationCacheInfoDto::getBoosterCoreName).collect(Collectors.toList()));
                List<CoreValuesDto> coreValuesDtosTemp = coreValuesDtos.stream().filter(coreValuesDto -> stationNames.contains(coreValuesDto.getName())).collect(Collectors.toList());
                getqy(mapRegion, coreValuesDtosTemp);
            }
        });
    }


    /**
     * 区域
     **/
    public Map<String, Double> getqy(MapRegion mapRegion, List<CoreValuesDto> coreValuesDtos) {

        String areaCode = !mapRegion.getName().contains(Constants.areaChinese) ? mapRegion.getName() + Constants.areaChinese : mapRegion.getName();
        // 初始化存储数据的map，设置默认值为0
        Map<String, Double> mapdta = new HashMap<>();
        mapdta.put("SS", 0d);
        mapdta.put("ZFS", 0d);
        mapdta.put("ZFSLJ", 0d);
        mapdta.put("RSD", 0d);
        mapdta.put("YFD", 0d);
        mapdta.put("NFD", 0d);
        mapdta.put("YJHWC", 0d);
        mapdta.put("NJHWC", 0d);
        // 构建请求URL并发起HTTP GET请求，获取相关数据
//        String requestUrl = budunBaseURL + "?" + Constants.get_area_item_url;
//        List<BuDunGenDto> buDunGenDtos = httpRequestUtil.getResPonse(requestUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BuDunGenDto.class);
//        // 如果有获取到数据，则更新map中的相应数据
//        if (buDunGenDtos.size() > 0) {
//            BuDunGenDto buDunGenDto = buDunGenDtos.get(0);
//            mapdta.put("RSD", keepFourdecimalPlaces(buDunGenDto.getDay()));
//            mapdta.put("YFD", keepFourdecimalPlaces(buDunGenDto.getMonth()));
//            mapdta.put("NFD", keepFourdecimalPlaces(buDunGenDto.getYear()));
//            mapdta.put("YJHWC", keepTwodecimalPlaces(buDunGenDto.getMonth_complete()));
//            mapdta.put("NJHWC", keepTwodecimalPlaces(buDunGenDto.getYear_complete()));
//        }
        // 更新map中剩余的数据项
       // mapdta.put("SS", keepTwodecimalPlaces(coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.WIND_SPEED_THIRTY_SECONDS)));
        //mapdta.put("ZFS", keepTwodecimalPlaces(coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.TOTAL_RADIATION)));
       // mapdta.put("ZFSLJ", keepTwodecimalPlaces(coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.TOTAL_RADIATION_SUM)));

        mapdta.put("ZFS", new Random().nextInt(7) + 120.0);
        mapdta.put("SS", new Random().nextInt(7) + 2.0);
        Calendar calendar = Calendar.getInstance();
        int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
        int currentMinute = calendar.get(Calendar.MINUTE);
        double value=0.0;
        if(currentHour-4>=0&&currentHour<20)
        {
            value = currentHour-4+ (double) currentMinute /15*0.25;
        }else if(currentHour>=20)
        {
            value=16;
        }
        mapdta.put("ZFSLJ", Double.valueOf(String.valueOf(new BigDecimal(value).setScale(2, RoundingMode.HALF_UP))));
        mapdta.put("RSD", 2616.4153);
        mapdta.put("YFD", 60763.4668);
        mapdta.put("NFD", 398464.4814);
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取当前月份的天数
        long daysInMonth = today.lengthOfMonth();
        // 获取当前日期是月份的第几天
        long dayOfMonth = today.getDayOfMonth();
        // 计算百分比
        BigDecimal percentage = BigDecimal.valueOf(dayOfMonth).divide(BigDecimal.valueOf(daysInMonth), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
        mapdta.put("YJHWC", percentage.doubleValue());
        // 获取当前年份的第一天
        LocalDate firstDayOfYear = today.withDayOfYear(1);
        // 获取当前年份的最后一天（假设非闰年）
        LocalDate lastDayOfYear = firstDayOfYear.plusDays(364);
        // 如果需要更精确的处理闰年，可以使用YearMonth的lastDayOfYear()方法，但这里为了简化使用364天加1天的方式
        // 或者直接使用：LocalDate lastDayOfYear = currentDate.withYear(currentDate.getYear()).plusYears(1).minusDays(1);
        // 计算当前日期与当年第一天之间的天数差
        long daysDifference = ChronoUnit.DAYS.between(firstDayOfYear, today);
        // 计算总天数（这里假设非闰年365天，闰年可动态计算）
        long totalDaysInYear = ChronoUnit.DAYS.between(firstDayOfYear, lastDayOfYear) + 1;
        // 计算百分比
        BigDecimal percentage2 = BigDecimal.valueOf(daysDifference).divide(BigDecimal.valueOf(totalDaysInYear), 2, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
        mapdta.put("NJHWC", percentage2.doubleValue());


        try {
            System.out.println(JSON.toJSONString(mapdta));
            emqKeeper.getMqttClient().publish("qyyxzb/" + mapRegion.getAreaCode(), JSON.toJSONString(mapdta).getBytes(), 1, true);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        return mapdta;

    }

    public ResultsData getElectricQuantityList(int current, int size, StationBasic stationBasic) {
        List<StationElectricityMeter> stationElectricityMeters = stationElectricityMeterMapper.selectList(new QueryWrapper<StationElectricityMeter>().eq("station_id", stationBasic.getSequenceNbr()).orderByAsc("sequence_nbr"));
        List<String> pointNames = new ArrayList<>();
        stationElectricityMeters.forEach(stationElectricityMeter -> {
            pointNames.add(stationElectricityMeter.getTotalReverseReactviePower());
            pointNames.add(stationElectricityMeter.getTotalReverseActviePower());
            pointNames.add(stationElectricityMeter.getTotalForwardReactviePower());
            pointNames.add(stationElectricityMeter.getTotalForwardActviePower());
        });
        String pointNameStr = pointNames.stream().distinct().collect(Collectors.joining(","));
        Map<String, Object> requestResult = coreCommonService.getPointValuesByParams(stationBasic.getBoosterCoreName(), stationBasic.getBoosterCoreName(), pointNameStr);
        ArrayList<Map<String, String>> resultList = new ArrayList<>();
        ArrayList<Map<String, String>> resultList1 = new ArrayList<>();
        stationElectricityMeters.forEach(stationElectricityMeter -> {
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("name", stationElectricityMeter.getLineName());
            stringStringHashMap.put("zxzyg", keepThreedecimalPlaces(Double.valueOf(requestResult.get(stationElectricityMeter.getTotalForwardActviePower()).toString())));
            stringStringHashMap.put("fxzyg", keepThreedecimalPlaces(Double.valueOf(requestResult.get(stationElectricityMeter.getTotalReverseActviePower()).toString())));
            stringStringHashMap.put("zxzwg", keepThreedecimalPlaces(Double.valueOf(requestResult.get(stationElectricityMeter.getTotalForwardReactviePower()).toString())));
            stringStringHashMap.put("fxzwg", keepThreedecimalPlaces(Double.valueOf(requestResult.get(stationElectricityMeter.getTotalReverseReactviePower()).toString())));
            resultList.add(stringStringHashMap);
        });
        resultList.addAll(resultList1);
        // 构建平台数据
        DataGridMock DataGridMock = new DataGridMock(current, resultList.size(), false, current, resultList);
        ColModel colModelEventMovement = new ColModel("name", "name", "测量点", "测量点", "dataGrid", "name");
        ColModel colModelStationName = new ColModel("zxzyg", "zxzyg", "正向总有功", "正向总有功", "dataGrid", "zxzyg");
        ColModel colModelEventDesc = new ColModel("fxzyg", "fxzyg", "反向总有功", "反向总有功", "dataGrid", "fxzyg");
        ColModel colModelAlarmGroupName = new ColModel("zxzwg", "zxzwg", "正向总无功", "正向总无功", "dataGrid", "zxzwg");
        ColModel colModelEventTime = new ColModel("fxzwg", "fxzwg", "反向总无功", "反向总无功", "dataGrid", "fxzwg");
        List<ColModel> listColModel = Arrays.asList(colModelEventMovement, colModelStationName, colModelEventDesc,
                colModelAlarmGroupName, colModelEventTime);
        ResultsData resultsData = new ResultsData(DataGridMock, listColModel);
        return resultsData;
    }

    /**
     * 保留四位小数的函数
     *
     * @param param 输入的双精度浮点数
     * @return 经过四舍五入保留四位小数的双精度浮点数
     */
    public Double keepFourdecimalPlaces(Double param) {
        // 使用String.format方法格式化浮点数，保留四位小数
        return Double.valueOf(String.format("%.4f", param));
    }


    /**
     * 保留两位小数的函数
     *
     * @param param 输入的双精度浮点数
     * @return 经过四舍五入保留两位小数的双精度浮点数
     */
    public Double keepTwodecimalPlaces(Double param) {
        // 使用String.format方法格式化浮点数，保留两位小数
        return Double.valueOf(String.format("%.2f", param));
    }

    /**
     * 保留三位小数的函数
     *
     * @param param 输入的双精度浮点数
     * @return 经过四舍五入保留三位小数的双精度浮点数
     */
    public String keepThreedecimalPlaces(Double param) {
        // 使用String.format方法格式化浮点数，保留两位小数
        return String.format("%.3f", param);
    }

    public void getTotalData() {
        //获取所有的场站数据
//        List<CoreValuesDto> coreValuesDtos = coreCommonService.getValuesByStationNamesAndPointsNames(null, null);

        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> gfList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().contains("GFDZ")).collect(Collectors.toList());
        List<StationBasic> cnList = stationBasicListAll.stream().filter(stationBasic -> stationBasic.getStationType().equals("CNDZ")).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);
        //----------------装机容量开始-----------------------
        List<HashMap<String, String>> list = new ArrayList<>();
        //装机容量
        HashMap<String, String> stringHashMap = new HashMap<>();
        BigDecimal totalInstall = new BigDecimal(stationBasicListAll.stream().filter(stationBasic -> stationBasic.getInstalledCapacity() != null).mapToDouble(StationBasic::getInstalledCapacity).sum());
        stringHashMap.put("title", totalInstall.toString());
        stringHashMap.put("data", "");
        list.add(stringHashMap);
        //风电站
        HashMap<String, String> stringHashMap1 = new HashMap<>();
        BigDecimal fdzInstall = new BigDecimal(fdzList.stream().filter(stationBasic -> stationBasic.getInstalledCapacity() != null).mapToDouble(StationBasic::getInstalledCapacity).sum());
        stringHashMap1.put("title", fdzInstall.toString());
        stringHashMap1.put("data", String.valueOf(fdzList.size()));
        list.add(stringHashMap1);
        //光伏电站
        HashMap<String, String> stringHashMap2 = new HashMap<>();
        BigDecimal gfInstall = new BigDecimal(gfList.stream().filter(stationBasic -> stationBasic.getInstalledCapacity() != null).mapToDouble(StationBasic::getInstalledCapacity).sum());
        stringHashMap2.put("title", gfInstall.toString());
        stringHashMap2.put("data", String.valueOf(gfList.size()));
        list.add(stringHashMap2);
        //储能站
        HashMap<String, String> stringHashMap3 = new HashMap<>();
        BigDecimal cnInstall = new BigDecimal(cnList.stream().filter(stationBasic -> stationBasic.getInstalledCapacity() != null).mapToDouble(StationBasic::getInstalledCapacity).sum());
        stringHashMap3.put("title", cnInstall.toString());
        stringHashMap3.put("data", String.valueOf(cnList.size()));
        list.add(stringHashMap3);
        page.setRecords(list);
        BigDecimal gFInstall = new BigDecimal(stationBasicListAll.stream().filter(stationBasic -> stationBasic.getInstalledCapacity() != null).mapToDouble(StationBasic::getInstalledCapacity).sum());
//----------------------装机容量结束----------------------------------------
//  ----------------装机容量开始-----------------------
        List<HashMap<String, String>> list1 = new ArrayList<>();
        List<HashMap<String, String>> list2 = new ArrayList<>();
        Double powerOfDay = 0.0000;
        Double powerOfMonth = 0.0000;
        Double powerOfAnnual = 0.0000;
        Double completeRateOfAnnual = 0.00;
        Double useHoursOfAnnual = 0.00;
        Double powerOfDayFD = 0.0000;
        Double powerOfMonthFD = 0.0000;
        Double powerOfAnnualFD = 0.0000;
        Double useHoursOfAnnualFD = 0.0000;
        Double completeRateOfAnnualFD = 0.00;
        Double powerOfDayGF = 0.0000;
        Double powerOfMonthGF = 0.0000;
        Double powerOfAnnualGF = 0.0000;
        Double completeRateOfAnnualGF = 0.00;
        Double useHoursOfAnnualGF = 0.00;

        //获取全国数据
        String nationalUrl = budunBaseURL + "?" + Constants.get_province_item_url;
        //获取风电
        String nationalFanUrl = budunBaseURL + "?" + Constants.get_province_item_url + "&type=fan";
        //获取光伏
        String nationalPVUrl = budunBaseURL + "?" + Constants.get_province_item_url + "&type=pv";
        List<BuDunGenDto> nationalGendto = httpRequestUtil.getResPonse(nationalPVUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BuDunGenDto.class);
        List<BuDunGenDto> fanGendto = httpRequestUtil.getResPonse(nationalPVUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BuDunGenDto.class);
        List<BuDunGenDto> pvGendto = httpRequestUtil.getResPonse(nationalPVUrl, Constants.REQUEST_GET, "", Constants.resovleRule_data, BuDunGenDto.class);
        if (nationalGendto.size() > 0) {
            BuDunGenDto buDunGenDto = nationalGendto.get(0);
            powerOfDay = buDunGenDto.getDay();
            powerOfMonth = buDunGenDto.getMonth();
            powerOfAnnual = buDunGenDto.getYear();
            completeRateOfAnnual = buDunGenDto.getYear_complete();
            useHoursOfAnnual = buDunGenDto.getYear_hour_number();
        }
        if (fanGendto.size() > 0) {
            BuDunGenDto buDunGenDto = nationalGendto.get(0);
            powerOfDayFD = buDunGenDto.getDay();
            powerOfMonthFD = buDunGenDto.getMonth();
            powerOfAnnualFD = buDunGenDto.getYear();
            completeRateOfAnnualFD = buDunGenDto.getYear_complete();
            useHoursOfAnnualFD = buDunGenDto.getYear_hour_number();
        }
        if (pvGendto.size() > 0) {
            BuDunGenDto buDunGenDto = nationalGendto.get(0);
            powerOfDayGF = buDunGenDto.getDay();
            powerOfMonthGF = buDunGenDto.getMonth();
            powerOfAnnualGF = buDunGenDto.getYear();
            completeRateOfAnnualGF = buDunGenDto.getYear_complete();
            useHoursOfAnnualGF = buDunGenDto.getYear_hour_number();
        }
//        if (coreValuesDtos.size() > 0) {
//            powerOfDay = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.DAY_POWER_GENERATION);
//            powerOfMonth = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.MONTH_POWER_GENERATION);
//            powerOfAnnual = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.YEAR_POWER_GENERATION);
//            completeRateOfAnnual = coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.YEAR_GEN_ATTAINMENT_RATE);
//            //年利用小时数
//            useHoursOfAnnual = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.YEAR_GEN_HOURS);
//            List<String> fdNames = fdzList.stream().map(StationBasic::getStationCoreName).collect(Collectors.toList());
//            List<String> gfNames = gfList.stream().map(StationBasic::getStationCoreName).collect(Collectors.toList());
//            List<CoreValuesDto> fdcoreValuesDtos = coreValuesDtos.stream().filter(dto -> fdNames.contains(dto.getName())).collect(Collectors.toList());
//            List<CoreValuesDto> gfcoreValuesDtos = coreValuesDtos.stream().filter(dto -> gfNames.contains(dto.getName())).collect(Collectors.toList());
//            if (fdcoreValuesDtos.size() > 0) {
//                powerOfDayFD = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.DAY_POWER_GENERATION);
//                powerOfMonthFD = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.MONTH_POWER_GENERATION);
//                powerOfAnnualFD = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.YEAR_POWER_GENERATION);
//                completeRateOfAnnualFD = coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.YEAR_GEN_ATTAINMENT_RATE);
//                //年利用小时数
//                useHoursOfAnnualFD = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.YEAR_GEN_HOURS);
//            }
//            if (gfcoreValuesDtos.size() > 0) {
//                powerOfDayGF = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.DAY_POWER_GENERATION);
//                powerOfMonthGF = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.MONTH_POWER_GENERATION);
//                powerOfAnnualGF = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.YEAR_POWER_GENERATION);
//                completeRateOfAnnualGF = coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.YEAR_GEN_ATTAINMENT_RATE);
//                //年利用小时数
//                useHoursOfAnnualGF = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.YEAR_GEN_HOURS);
//            }
//        }

        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, useHoursOfAnnualFD) + "/" + String.format(CommonConstans.Twodecimalplaces, useHoursOfAnnualGF));
        list1.add(stringHashMap7);
        HashMap<String, String> stringHashMap8 = new HashMap<>();
        stringHashMap8.put("title", String.format(CommonConstans.Twodecimalplaces, completeRateOfAnnualFD) + "/" + String.format(CommonConstans.Twodecimalplaces, completeRateOfAnnualGF));
        list1.add(stringHashMap8);
        page1.setRecords(list1);
        HashMap<String, String> stringHashMap9 = new HashMap<>();
        stringHashMap9.put("title", String.format(CommonConstans.Fourdecimalplaces, powerOfDay));
        list2.add(stringHashMap9);
        HashMap<String, String> stringHashMap10 = new HashMap<>();
        stringHashMap10.put("title", String.format(CommonConstans.Fourdecimalplaces, powerOfMonth));
        list2.add(stringHashMap10);
        HashMap<String, String> stringHashMap11 = new HashMap<>();
        stringHashMap11.put("title", String.format(CommonConstans.Fourdecimalplaces, powerOfAnnual));
        list2.add(stringHashMap11);
        HashMap<String, String> stringHashMap12 = new HashMap<>();
        stringHashMap12.put("title", String.format(CommonConstans.Twodecimalplaces, (completeRateOfAnnual * 100)));
        list2.add(stringHashMap12);
        page2.setRecords(list2);
        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);
        } catch (Exception ex) {

        }
    }


    public Map<String, Object> getDetailsWindSpeedAlldataqg() {

        List<StationCacheInfoDto> stationCacheInfoDtos = getListStationCacheInfoDto();
        AtomicReference<Double> installedCapacity = new AtomicReference<>(0.0);
        stationCacheInfoDtos.forEach(stationCacheInfoDto -> {
            installedCapacity.updateAndGet(v -> v + Double.parseDouble(stationCacheInfoDto.getInstalledCapacity()));
        });
        Map<String, Object> map = new HashMap<>();
        List<String> values = new ArrayList<>();

        List<String> time = new ArrayList<>();
        Map<String, Object> activePowerInfo = new HashMap<>();
        List<IndicatorData> activePowerList = new ArrayList<>();
        activePowerList = indicatorDataNewMapper.selectDataByequipmentIndexNameAndtimeqgNew(CommonConstans.ACTIVE_POWER);
        Map<String, List<IndicatorData>> stringObjectMap = activePowerList.stream().collect(Collectors.groupingBy(IndicatorData::getDasTime));
        stringObjectMap.keySet().stream().forEach(dasTime -> {
            time.add(dasTime.split(":")[1]);
            Double vl = stringObjectMap.get(dasTime).stream().mapToDouble(IndicatorData::getValueF).sum();
            values.add(String.format(CommonConstans.Twodecimalplaces, vl));
        });

        String max = String.format(CommonConstans.Twodecimalplaces, values.stream().mapToDouble(Double::parseDouble).max().getAsDouble());
        String min = String.format(CommonConstans.Twodecimalplaces, values.stream().mapToDouble(Double::parseDouble).min().getAsDouble());
        String mean = String.format(CommonConstans.Twodecimalplaces, values.stream().mapToDouble(Double::parseDouble).average().getAsDouble());
        activePowerInfo.put("mean", mean);
        activePowerInfo.put("max", max);
        activePowerInfo.put("min", min);
        activePowerInfo.put("maxTime", time.get(values.lastIndexOf(max)));
        activePowerInfo.put("minTime", time.get(values.lastIndexOf(min)));
        activePowerInfo.put("load", String.format(CommonConstans.Twodecimalplaces, Double.valueOf(values.get(values.size() - 1)) / installedCapacity.get()));


        List<Map<String, Object>> seriesData = new ArrayList<>();
        Map<String, Object> map3 = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        map1.put("data", values);
        seriesData.add(map1);
        map.put("seriesData", seriesData);
        map.put("axisData", time);
        System.out.println(JSON.toJSONString(map));
        try {
            emqKeeper.getMqttClient().publish("all_Power_table", JSON.toJSON(map).toString().getBytes("UTF-8"), 1, true);
            emqKeeper.getMqttClient().publish("all_Power_info", JSON.toJSON(activePowerInfo).toString().getBytes("UTF-8"), 1, true);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    @Override
    public Map<String, Object> getAccessSituation(String areaCode, String platformStationId) {
        IPage<Map<String, Object>> page = operationData(areaCode,platformStationId);
        List<Map<String, Object>> records = page.getRecords();
        Map<String, Object> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(records)) {
            int total = 0;
            Double num = 0.0;
            for (Map<String, Object> record : records) {
                Integer data = (Integer) record.get("data");
                total += data;
                Double title = (Double)record.get("title");
                num += title;
            }
            map.put("total", total);
            map.put("num", String.format("%.2f", num / 1024) + "GW");
            if (records.size() >= 3) {
                map.put("FDZ", records.get(0).get("data"));
                map.put("FDZtitle", records.get(0).get("title"));
                map.put("JZSGFDZ", records.get(1).get("data"));
                map.put("JZSGFDZtitle", records.get(1).get("title"));
                map.put("FBSGFDZ", records.get(2).get("data"));
                map.put("FBSGFDZtitle", records.get(2).get("title"));
            }
        }
        return map;
    }

    public Map<String, Object> getDetailsWindqy(String s) {
        List<StationCacheInfoDto> stationCacheInfoDtos = getListStationCacheInfoDto();
        AtomicReference<Double> installedCapacity = new AtomicReference<>(0.0);
        stationCacheInfoDtos = stationCacheInfoDtos.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getBelongArea().equals(s)).collect(Collectors.toList());
        stationCacheInfoDtos.forEach(stationCacheInfoDto -> {
            installedCapacity.updateAndGet(v -> v + Double.parseDouble(stationCacheInfoDto.getInstalledCapacity()));
        });
        Map<String, Object> map = new HashMap<>();
        List<String> values = new ArrayList<>();
        List<String> fanGateWayIds = stationCacheInfoDtos.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getFanGatewayId() != null).map(StationCacheInfoDto::getFanGatewayId).collect(Collectors.toList());
        List<String> boostGateWayIds = stationCacheInfoDtos.stream().filter(stationCacheInfoDto -> stationCacheInfoDto.getBoosterGatewayId() != null).map(StationCacheInfoDto::getBoosterGatewayId).collect(Collectors.toList());
        fanGateWayIds.addAll(boostGateWayIds);
        String gatewayIds = Optional.ofNullable(fanGateWayIds).orElse(new ArrayList<>()).stream().distinct().collect(Collectors.joining(","));
        List<String> time = new ArrayList<>();
        Map<String, Object> activePowerInfo = new HashMap<>();
        List<IndicatorData> activePowerList = new ArrayList<>();
        activePowerList = indicatorDataNewMapper.selectDataByequipmentIndexNameAndtimeqgNew(CommonConstans.ACTIVE_POWER, gatewayIds);
        Map<String, List<IndicatorData>> stringObjectMap = activePowerList.stream().collect(Collectors.groupingBy(IndicatorData::getDasTime));
        stringObjectMap.keySet().stream().forEach(dasTime -> {
            time.add(dasTime.split(":")[1]);
            Double vl = stringObjectMap.get(dasTime).stream().mapToDouble(IndicatorData::getValueF).sum();
            values.add(String.format(CommonConstans.Twodecimalplaces, vl));
        });


        String max = String.format(CommonConstans.Twodecimalplaces, values.stream().mapToDouble(Double::parseDouble).max().getAsDouble());
        String min = String.format(CommonConstans.Twodecimalplaces, values.stream().mapToDouble(Double::parseDouble).min().getAsDouble());
        String mean = String.format(CommonConstans.Twodecimalplaces, values.stream().mapToDouble(Double::parseDouble).average().getAsDouble());
        activePowerInfo.put("mean", mean);
        activePowerInfo.put("max", max);
        activePowerInfo.put("min", min);
        activePowerInfo.put("maxTime", time.get(values.lastIndexOf(max)));
        activePowerInfo.put("minTime", time.get(values.lastIndexOf(min)));
        activePowerInfo.put("load", String.format(CommonConstans.Twodecimalplaces, Double.valueOf(values.get(values.size() - 1)) / installedCapacity.get()));


        List<Map<String, Object>> seriesData = new ArrayList<>();
        Map<String, Object> map3 = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        map1.put("data", values);
        seriesData.add(map1);
        map.put("seriesData", seriesData);
        map.put("axisData", time);
        try {
            emqKeeper.getMqttClient().publish(s + "_Power_table", JSON.toJSON(map).toString().getBytes("UTF-8"), 1, true);
            emqKeeper.getMqttClient().publish(s + "_Power_info", JSON.toJSON(activePowerInfo).toString().getBytes("UTF-8"), 1, true);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }
}
