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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.api.util.Constants;
import com.yeejoin.amos.boot.module.jxiop.api.util.HttpRequestUtil;
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.service.CoreCommonService;
import com.yeejoin.amos.boot.module.jxiop.biz.tdmapper.IndicatorDataMapper;
import org.apache.commons.lang.StringUtils;
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.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
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;
	@Autowired
	StationPlanMapper stationPlanMapper;
	@Autowired
	IndicatorDataMapper indicatorDataMapper;
	/**
	 * 场站mapper
	 */
	@Autowired
	StationBasicMapper stationBasicMapper;
	/**
	 * 场站坐标mapper
	 */
	@Autowired
	StationCoordinateMapper stationCoordinateMapper;
	/***
	 * 设备基础信息中间表数据-热工院
	 */
	@Autowired
	SjglZsjZsbtzServiceImpl SjglZsjZsbtzServiceImpl;

	@Autowired
	CommonServiceImpl commonServiceImpl;

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

	@Autowired
	EmqKeeper emqKeeper;
	@Autowired
	CoreCommonService coreCommonService;
//    @Autowired
//    InfluxdbUtil influxdbUtil;

	@Autowired
	private HttpRequestUtil httpRequestUtil;
	
	@Value("${budun.baseurl:http://iiet-jepcc.powerchina.cn:8088/screen_api}")
	private String budunBaseURL;
	/**
	 * 根据场站编号获取该场站的装机容量
	 *
	 * @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 Map<String, String> getStationfs(StationBasic stationBasic) {
		String requestStationName =null;
		List<String> pointNames = Arrays.asList(CommonConstans.WIND_SPEED_THIRTY_SECONDS,CommonConstans.ACTIVE_POWER);
		String requestPointNames = pointNames.stream().collect(Collectors.joining(","));
 		List<String> stationNames = new ArrayList<>();
		if(!ObjectUtils.isEmpty(stationBasic.getStationCoreName())){
          stationNames.add(stationBasic.getStationCoreName());
		}
		if(!ObjectUtils.isEmpty(stationBasic.getBoosterCoreName())){
			stationNames.add(stationBasic.getBoosterCoreName());
		}
		if(stationNames.size()>1){
			requestStationName =stationNames.stream().collect(Collectors.joining(","));
		}
		List<CoreValuesDto> coreValuesDtoList  = coreCommonService.getValuesByStationNamesAndPointsNames(requestStationName,requestPointNames);
		String value = "0";
		Map<String, String> map = new HashMap<>();
		Map<String, List<String>> queryCondtion = new HashMap<>();
		if (stationBasic.getStationType().equals("FDZ")) {
			value = String.format("%.2f", coreCommonService.getAverageOfByPointName(coreValuesDtoList, CommonConstans.WIND_SPEED_THIRTY_SECONDS));
			map.put("name", "风速/辐照度");
			map.put("value", value + "m/s");
		} else {
			value = String.format("%.2f",
					coreCommonService.getAverageOfByPointName(coreValuesDtoList, CommonConstans.TOTAL_RADIATION));
			map.put("name", "风速/辐照度");
			map.put("value", value + "W/㎡");
		}

		return map;
	}

	/***
	 * 电站容量
	 */
	public Map<String, String> getStationrl(StationBasic stationBasic) {
		Double installCapacity = 0.0;
		String value = ObjectUtils.isEmpty(stationBasic.getInstalledCapacity()) ? "0.00" : String.format("%.2f", stationBasic.getInstalledCapacity());
		Map<String, String> map = new HashMap<>();
		map.put("name", "容量");
		map.put("value", value + "MW");
		return map;
	}

	/**
	 * 根据省份名称查询电站详情
	 * @return
	 */
//    public List<RegionNationWideDto> getNationWideInfo(String provinceName, String type) {
//        List<RegionNationWideDto> regionNationWideDtoList = new ArrayList<>();
//        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().isNotNull("belong_area").isNotNull("fan_gateway_id"));
//        List<Region> regionList = this.regionMapper.selectList(new QueryWrapper<Region>().eq("level", 1));
//        List<StationBasic> list = new ArrayList<>();
//        //如果 provinceName 为空则表示当前为全国地图 否则则为省份地图
////        if (ObjectUtils.isEmpty(provinceName) || provinceName.equals("")) {
//        if ((!ObjectUtils.isEmpty(type) && type.equals("gis")) && (ObjectUtils.isEmpty(provinceName) || provinceName.equals(""))) {
//            for (int i = 0; i < regionList.size(); i++) {
//                RegionNationWideDto regionNationWideDto = new RegionNationWideDto();
//                AtomicReference<Double> guangfuMW = new AtomicReference<>(0.0);
//                AtomicReference<Double> fengdianMW = new AtomicReference<>(0.0);
//                AtomicReference<Integer> guangfu = new AtomicReference<>(0);
//                AtomicReference<Integer> fengdian = new AtomicReference<>(0);
//                Region region = regionList.get(i);
//                list = stationBasicList.stream().filter(stationBasic -> stationBasic.getBelongArea().contains(String.valueOf(region.getRegionCode()))).collect(Collectors.toList());
//                list.forEach(stationBasic -> {
//                    if (!ObjectUtils.isEmpty(stationBasic.getFanGatewayId()) && !ObjectUtils.isEmpty(stationBasic.getStationNumber())) {
//                        regionNationWideDto.setJsJoin(true);
//                    }
//                    if (stationBasic.getStationType().equals("FDZ")) {
//                        fengdianMW.set(getStationCaPACITYL(stationBasic.getStationNumber()));
//                        fengdian.getAndSet(fengdian.get() + 1);
//                    } else {
//                        guangfuMW.set(getStationCaPACITYL(stationBasic.getStationNumber()));
//                        guangfu.getAndSet(guangfu.get() + 1);
//                    }
//                });
//                regionNationWideDto.setFengdian(fengdian.toString());
//                regionNationWideDto.setGuangfu(guangfu.toString());
//                regionNationWideDto.setGuangfuMW("0");
//                regionNationWideDto.setFengdianMV("0");
//                if (!ObjectUtils.isEmpty(guangfuMW.get())) {
//                    regionNationWideDto.setGuangfuMW(String.format("%.2f", guangfuMW.get()));
//                }
//                if (!ObjectUtils.isEmpty(fengdianMW.get())) {
//                    regionNationWideDto.setFengdianMV(String.format("%.2f", fengdianMW.get()));
//                }
//                regionNationWideDto.setName(region.getRegionName());
//                regionNationWideDtoList.add(regionNationWideDto);
//            }
//        } else {
//            if (!ObjectUtils.isEmpty(provinceName) && provinceName.contains("%")) {
//                try {
//                    provinceName = URLDecoder.decode(provinceName, "UTF-8");
//                } catch (Exception e) {
//
//                }
//            }
//            String finalProvinceName = provinceName;
//            if (!ObjectUtils.isEmpty(type) && type.equals("station")) {
//                list = stationBasicList;
//            } else {
//                Region region = regionList.stream().filter(region1 -> region1.getRegionName().equals(finalProvinceName)).collect(Collectors.toList()).get(0);
//                list = stationBasicList.stream().filter(stationBasic -> stationBasic.getBelongArea().contains(String.valueOf(region.getRegionCode())) && stationBasic.getFanGatewayId() != null).collect(Collectors.toList());
//            }
//            List<StationCoordinate> stationCoordinateList = stationCoordinateMapper.selectList(new QueryWrapper<StationCoordinate>().isNotNull("station_id").eq("is_main_coordinate", 0));
//            for (int i = 0; i < list.size(); i++) {
//                HashMap<String, Double> hashMap = new HashMap<>();
//                StationBasic stationBasic = list.get(i);
//                RegionNationWideDto regionNationWideDto = new RegionNationWideDto();
//                regionNationWideDto.setStaitionId(String.valueOf(stationBasic.getSequenceNbr()));
//                regionNationWideDto.setStaitionName(stationBasic.getStationName());
//                regionNationWideDto.setStaitionType(stationBasic.getStationType());
//                String speendOrirradiate = "";
//                regionNationWideDto.setStationCapacity(String.valueOf(getStationCaPACITYL(stationBasic.getStationNumber())));
//                if (stationBasic.getStationType().equals("FDZ")) {
//                    speendOrirradiate = String.valueOf(commonServiceImpl.getAvgvalueByIndicatior(stationBasic.getFanGatewayId(), "30秒平均风速"));
//                } else {
//                    speendOrirradiate = String.valueOf(commonServiceImpl.getTotalByIndicatior(stationBasic.getBoosterGatewayId(), "WTX-801_25_WTX-801_总辐射"));
//                }
//                regionNationWideDto.setSpeendOrirradiate(speendOrirradiate);
//                StationCoordinate stationCoordinate = stationCoordinateList.stream().filter(stationCoordinate1 -> stationCoordinate1.getStationId().equals(stationBasic.getSequenceNbr())).collect(Collectors.toList()).get(0);
//                hashMap.put("lng", Double.valueOf(stationCoordinate.getLongitude()));
//                hashMap.put("lat", Double.valueOf(stationCoordinate.getLaitude()));
//                regionNationWideDto.setPosition(hashMap);
//                regionNationWideDtoList.add(regionNationWideDto);
//            }
//        }
//        List<StationBasic> finalList = list;
//        String finalProvinceName1 = provinceName;
//        Thread thread = new Thread(() -> {
//            getCompletionOfPowerIndicatorsByCurrentData(finalList, finalProvinceName1);
//        });
//        thread.start();
//        return regionNationWideDtoList;
//    }

//    public ResultsData getCompletionOfPowerIndicatorsByProvinceName(int current, int size, String provinceName) {
//
//        List<ColModel> colModels = new ArrayList<>();
//        List<CompletionOfPowerIndicatorsDto> completionOfPowerIndicatorsDtoList = new ArrayList<>();
//        ColModel colModelStatitonName = new ColModel("stationName", "stationName", "场站", "场站", "dataGrid", "stationName");
//        ColModel colModelInstallCapactity = new ColModel("installCapactity", "installCapactity", "装机容量", "装机容量", "dataGrid", "installCapactity");
//        ColModel colModelWindSpeedOrIrradiance = new ColModel("windSpeedOrIrradiance", "windSpeedOrIrradiance", "风速/辐照度", "风速/辐照度", "dataGrid", "windSpeedOrIrradiance");
//        ColModel colModelActivePower = new ColModel("activePower", "activePower", "有功", "有功", "dataGrid", "activePower");
//        ColModel colModelDailyPower = new ColModel("dailyPower", "dailyPower", "日发电量", "日发电量", "dataGrid", "dailyPower");
//        ColModel colModelMonthlyPower = new ColModel("monthlyPower", "monthlyPower", "月发电量", "月发电量", "dataGrid", "monthlyPower");
//        ColModel colModelAnnualPower = new ColModel("annualPower", "annualPower", "年发电量", "年发电量", "dataGrid", "annualPower");
//        colModels.add(colModelStatitonName);
//        colModels.add(colModelInstallCapactity);
//        colModels.add(colModelWindSpeedOrIrradiance);
//        colModels.add(colModelActivePower);
//        colModels.add(colModelDailyPower);
//        colModels.add(colModelMonthlyPower);
//        colModels.add(colModelAnnualPower);
//        Region region = this.regionMapper.selectOne(new QueryWrapper<Region>().eq("level", 1).eq("region_name", provinceName));
//        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().like("belong_area", region.getRegionCode()));
//        //遍历列表
//        stationBasicList.forEach(stationBasic -> {
//            CompletionOfPowerIndicatorsDto completionOfPowerIndicatorsDto = new CompletionOfPowerIndicatorsDto();
//            completionOfPowerIndicatorsDto.setStationName(stationBasic.getStationName());
//            completionOfPowerIndicatorsDto.setInstallCapactity("0");
//            if (getStationCaPACITYL(stationBasic.getStationNumber()) != null) {
//                completionOfPowerIndicatorsDto.setInstallCapactity(String.format("%.2f", getStationCaPACITYL(stationBasic.getStationNumber())));
//            }
//
//            try {
//                List<Map<String, Object>> mapList;
//                List<Map<String, Object>> mapList1;
//                if (stationBasic.getStationType().equals("FDZ")) {
//                    mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' or equipmentIndexName='有功功率'  or equipmentIndexName='30秒平均风速' )");
//                    completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance(String.valueOf(commonServiceImpl.getAvgvalueByIndicatior(mapList, "30秒平均风速")));
//                    completionOfPowerIndicatorsDto.setActivePower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "有功功率")));
//                    completionOfPowerIndicatorsDto.setDailyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "日发电量")));
//                    completionOfPowerIndicatorsDto.setMonthlyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "月发电量")));
//                    completionOfPowerIndicatorsDto.setAnnualPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "年发电量")));
//                } else {
//                    mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where frontModule=~/逆变器/ and(equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' or equipmentIndexName='有功功率')");
//                    mapList1 = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getBoosterGatewayId() + " where equipmentIndexName='WTX-801_25_WTX-801_总辐射'");
//                    completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList1, "WTX-801_25_WTX-801_总辐射")));
//                    completionOfPowerIndicatorsDto.setActivePower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "有功功率")));
//                    completionOfPowerIndicatorsDto.setDailyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "日发电量")));
//                    completionOfPowerIndicatorsDto.setMonthlyPower(String.valueOf(commonServiceImpl.getTotalByIndicatior(mapList, "月发电量")));
//                    completionOfPowerIndicatorsDto.setAnnualPower(String.format("%.2f", new BigDecimal(commonServiceImpl.getTotalByIndicatior(mapList, "年发电量"))));
//                }
//
//
//            } catch (Exception exception) {
//                completionOfPowerIndicatorsDto.setWindSpeedOrIrradiance("0");
//                completionOfPowerIndicatorsDto.setActivePower("0");
//                completionOfPowerIndicatorsDto.setDailyPower("0");
//                completionOfPowerIndicatorsDto.setMonthlyPower("0");
//                completionOfPowerIndicatorsDto.setAnnualPower("0");
//            }
//            completionOfPowerIndicatorsDtoList.add(completionOfPowerIndicatorsDto);
//        });
//        Integer allsize = completionOfPowerIndicatorsDtoList.size();
//        DataGridMock dataGridMock = new DataGridMock(current, allsize, false, allsize / size + 1, completionOfPowerIndicatorsDtoList);
//        ResultsData resultsData = new ResultsData(dataGridMock, colModels);
//        return resultsData;
//    }

//    public void getCompletionOfPowerIndicatorsByCurrentData(List<StationBasic> stationBasicList, String provinceName) {
//        String provinceNameTopic = "";
//        if (provinceName.contains("黑龙江") || provinceName.contains("内蒙古")) {
//            provinceNameTopic = provinceName.substring(0, 3);
//        } else {
//            provinceNameTopic = provinceName.substring(0, 2);
//        }
//        HashMap<String, String> stringHashMap = new HashMap<>();
//        stringHashMap.put("title", provinceNameTopic + "区域");
//        try {
//            emqKeeper.getMqttClient().publish("proviceName_topic", JSON.toJSON(stringHashMap).toString().getBytes("UTF-8"), 1, true);
//            logger.info("----------------------------------推送省份名称消息成功败--------------------------------");
//        } catch (Exception e) {
//            logger.info("----------------------------------推送省份名称消息失败--------------------------------");
//        }
//        Page<SocialContributionDto> socialContributionDtoPage = new Page<SocialContributionDto>();
//        logger.error("--------------------------区域实时数据消息开始发送----------------------------------------------");
//        List<SocialContributionDto> socialContributionDtoList = new ArrayList<>();
//        //日发电量
//        AtomicReference<Double> dailyPower = new AtomicReference<>(0.0);
//        //月发电量
//        AtomicReference<Double> monthlyPower = new AtomicReference<>(0.0);
//        //年发电量
//        AtomicReference<Double> annualPower = new AtomicReference<>(0.0);
//        //年发电量完成比例
//        String completionRatio = "0.00";
//        //年利用小时数
//        AtomicReference<Double> useHours = new AtomicReference<>(0.0);
//        AtomicReference<Double> installCapacity = new AtomicReference<>(0.0);
//        stationBasicList.forEach(stationBasic -> {
//            List<Map<String, Object>> mapList = new ArrayList<>();
//            if (stationBasic.getStationType().equals("FDZ")) {
//                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
//            } else {
//                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where frontModule=~/逆变器/ and (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
//            }
//            List<Map<String, Object>> finalMapList = mapList;
//            dailyPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "日发电量"));
//            monthlyPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "月发电量"));
//            annualPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "年发电量"));
//            installCapacity.updateAndGet(v -> v + getStationCaPACITYL(stationBasic.getStationNumber()));
//        });
//        SocialContributionDto dailyPowerdto = new SocialContributionDto();
//        dailyPowerdto.setTitle(String.format("%.2f", dailyPower.get()));
//        dailyPowerdto.setUnit("万kWh");
//        SocialContributionDto monthlyPowerdto = new SocialContributionDto();
//        monthlyPowerdto.setTitle(String.format("%.2f", monthlyPower.get()));
//        monthlyPowerdto.setUnit("万kWh");
//        SocialContributionDto annualPowerdto = new SocialContributionDto();
//        annualPowerdto.setTitle(String.format("%.2f", annualPower.get()));
//        annualPowerdto.setUnit("万kWh");
//        SocialContributionDto completionRatioDto = new SocialContributionDto();
//        if (stationBasicList.size() > 0) {
//            completionRatioDto.setTitle(String.format("%.2f", 23.21 + Math.random() * 10));
//        } else {
//            completionRatioDto.setTitle(completionRatio);
//        }
//        completionRatioDto.setUnit("%");
//        SocialContributionDto useHoursDto = new SocialContributionDto();
//        useHoursDto.setTitle(String.format("%.2f", annualPower.get() / installCapacity.get()));
//        useHoursDto.setUnit("h");
//        socialContributionDtoList.add(dailyPowerdto);
//        socialContributionDtoList.add(monthlyPowerdto);
//        socialContributionDtoList.add(annualPowerdto);
//        socialContributionDtoList.add(completionRatioDto);
//        socialContributionDtoList.add(useHoursDto);
//        socialContributionDtoPage.setRecords(socialContributionDtoList);
//        socialContributionDtoPage.setTotal(100);
//        socialContributionDtoPage.setCurrent(1);
//        try {
////            emqKeeper.getMqttClient().publish("completionofpowerindicator_topic", JSON.toJSON(socialContributionDtoPage).toString().getBytes("UTF-8"), 1, true);
//            logger.info("-----------------发送区域实时生产数据消息=================== 成功！" + JSON.toJSONString(socialContributionDtoPage));
//        } catch (Exception exception) {
//            logger.error("-----------------发送区域实时生产数据消息=================== 失败！");
//        }
//    }
	public List<TabDto> getTabsByStationBasicId(String stationBasicId) {
		StationBasic stationBasic = stationBasicMapper.selectById(stationBasicId);
		List<TabDto> tabDtoList = new ArrayList<>();
		if (stationBasic.getStationType().contains("FDZ") && stationBasic.getStationType().length() < 4) {
			TabDto tab0 = new TabDto("风机布置图", "0");
			TabDto tab1 = new TabDto("集电线路图", "1");
			TabDto tab2 = new TabDto("运行列表", "2");
			TabDto tab3 = new TabDto("升压站监控", "3");
			TabDto tab4 = new TabDto("电量表计", "4");
			TabDto tab5 = new TabDto("故障信息", "5");
			tabDtoList.add(tab0);
			tabDtoList.add(tab1);
			tabDtoList.add(tab2);
			tabDtoList.add(tab3);
			tabDtoList.add(tab4);
			tabDtoList.add(tab5);
		} else {
			TabDto tab6 = new TabDto("光伏区布置图", "6");
			TabDto tab7 = new TabDto("集电线路图", "7");
			TabDto tab8 = new TabDto("运行列表", "8");
			TabDto tab9 = new TabDto("升压站监控", "9");
			TabDto tab10 = new TabDto("电量表计", "10");
			TabDto tab11 = new TabDto("故障信息", "11");
//            TabDto tab12 = new TabDto("集中式-离散率", "12");
//            TabDto tab13 = new TabDto("组串式-离散率", "13");
			TabDto tab14 = new TabDto("离散率", "14");
			tabDtoList.add(tab6);
			tabDtoList.add(tab7);
			tabDtoList.add(tab8);
			tabDtoList.add(tab9);
			tabDtoList.add(tab10);
			tabDtoList.add(tab11);
//            tabDtoList.add(tab12);
//            tabDtoList.add(tab13);
			tabDtoList.add(tab14);
		}
		return tabDtoList;
	}

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

		return mapAreaInfoDtoList;
	}

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

	public Map<String, Object> getDetailsWindSpeedAlldata(StationBasic stationBasic) {
		Map<String, Object> map = new HashMap<>();
		List<String> values = new ArrayList<>();
		Map<Date, Double> groupMap = new HashMap<>();
		List<String> time = new ArrayList<>();
		Map<String, Object> activePowerInfo = new HashMap<>();
		List<IndicatorData> activePowerList = new ArrayList<>();
//        String startTime = DateUtil.today() + " 00:00:00";
//        String endTime = DateUtil.today() + " 23:59:59";

		Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
		Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
		String startTime = sdf.format(currentDayStartTime);
		String endTime = sdf.format(currentDayEndTime);

		Double installedCapacity = commonServiceImpl.getStationCapactityByStationWerks(stationBasic.getStationNumber());
		if ("FDZ".equals(stationBasic.getStationType())) {
			activePowerList = indicatorDataMapper.selectDataByequipmentIndexNameAndtime(
					CommonConstans.xiazaoActivePowerPoint, startTime, endTime, stationBasic.getBoosterGatewayId());
		} else {
			activePowerList = indicatorDataMapper.selectDataByequipmentIndexNameAndtime(
					CommonConstans.taiheActivePowerPoint, startTime, endTime, stationBasic.getBoosterGatewayId());
		}
		for (int i = 0; i < activePowerList.size(); i++) {
			IndicatorData indicatorData = activePowerList.get(i);
			time.add(DateUtil.format(indicatorData.getCreatedTime(), "HH:mm"));
			if ("FDZ".equals(stationBasic.getStationType())) {
				values.add(String.format(CommonConstans.Twodecimalplaces, indicatorData.getValueF()));
			} else {
				values.add(String.format(CommonConstans.Twodecimalplaces,
						indicatorData.getValueF() * CommonConstans.kwToMv));
			}
		}
		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));

		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(stationBasic.getSequenceNbr() + "_Power_table",
					JSON.toJSON(map).toString().getBytes("UTF-8"), 1, true);
			emqKeeper.getMqttClient().publish(stationBasic.getSequenceNbr() + "_Power_info",
					JSON.toJSON(activePowerInfo).toString().getBytes("UTF-8"), 1, true);
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return map;
	}

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

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

	public String getPowerOfDaily(List<StationBasic> stationBasicList) {

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

				}
			}

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

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

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

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

	// 获取社会贡献

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

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

//    public Page<HashMap<String, String>> getDetailsOnPowergeneration(String areaName) {
//        Page<HashMap<String, String>> hashMapPage = new Page<>(1, 99);
//        List<HashMap<String, String>> hashMapList = new ArrayList<>();
//        List<StationBasic> stationBasicList = stationBasicMapper.selectList(new QueryWrapper<StationBasic>().eq("station_type", "FDZ").isNotNull("fan_gateway_id"));
//        //日发电量
//        AtomicReference<Double> dailyPower = new AtomicReference<>(0.0);
//        //月发电量
//        AtomicReference<Double> monthlyPower = new AtomicReference<>(0.0);
//        //年发电量
//        AtomicReference<Double> annualPower = new AtomicReference<>(0.0);
//        stationBasicList.forEach(stationBasic -> {
//            List<Map<String, Object>> mapList = new ArrayList<>();
//            if (stationBasic.getStationType().equals("FDZ")) {
//                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where  (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
//            } else {
//                mapList = influxdbUtil.query("SELECT * FROM indicators_" + stationBasic.getFanGatewayId() + " where frontModule=~/逆变器/ and (equipmentIndexName='日发电量' or  equipmentIndexName='月发电量' or equipmentIndexName='年发电量' )");
//            }
//            List<Map<String, Object>> finalMapList = mapList;
//            dailyPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "日发电量"));
//            monthlyPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "月发电量"));
//            annualPower.updateAndGet(v -> v + commonServiceImpl.getTotalByIndicatior(finalMapList, "年发电量"));
//        });
//        HashMap<String, String> dayHashMap = new HashMap<>();
//        dayHashMap.put("title", String.format("%.2f", dailyPower.get()) + "KWh");
//        HashMap<String, String> monthHashMap = new HashMap<>();
//        monthHashMap.put("title", String.format("%.2f", monthlyPower.get()) + "KWh");
//        HashMap<String, String> annualHashMap = new HashMap<>();
//        annualHashMap.put("title", String.format("%.2f", annualPower.get()) + "KWh");
//        HashMap<String, String> totalHashMap = new HashMap<>();
//        totalHashMap.put("title", String.format("%.2f", annualPower.get()) + "KWh");
//        hashMapList.add(dayHashMap);
//        hashMapList.add(monthHashMap);
//        hashMapList.add(annualHashMap);
//        hashMapList.add(totalHashMap);
//        hashMapPage.setRecords(hashMapList);
//        return hashMapPage;
//    }
	public List<StationBasic> getListOfStationBasicByAreaName(String areaName) {
		List<StationBasic> stationBasicListAll = new ArrayList<>();
		MapRegion mapRegion = mapRegionMapper.selectOne(new QueryWrapper<MapRegion>().eq("name", areaName));
		// 获取片区下的省份名称
		ArrayList<String> stringArrayList = mapRegion.getProvince();
		// 变量获取所有的场站信息
		for (int i = 0; i < stringArrayList.size(); i++) {
			Region region = regionMapper
					.selectOne(new LambdaQueryWrapper<Region>().eq(Region::getLevel, 1).like(Region::getRegionName, stringArrayList.get(i)));
			List<StationBasic> stationBasicList = stationBasicMapper
					.selectList(new QueryWrapper<StationBasic>().like("belong_area", region.getRegionCode()));
			stationBasicListAll.addAll(stationBasicList);
		}
		return stationBasicListAll;
	}

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

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

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

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

	@Scheduled(cron = "0/5 * * * * *")
	public void getTotalData() {
		// 计算所有场站年计划完成量
		int year = Calendar.getInstance().get(Calendar.YEAR);
		int Moon = Calendar.getInstance().get(Calendar.MONTH) + 1;
		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;

		double moonValue = stationPlans.stream().filter(e -> e.getMonthly().equals(String.valueOf(Moon)))
				.mapToDouble(StationPlan::getValue).sum();

		// 查询风电站年计划完成量
//
//        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<>();
		AtomicReference<Double> powerOfDayFD = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> powerOfMonthFD = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> powerOfAnnualFD = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> powerOfDayGF = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> powerOfMonthGF = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> powerOfAnnualGF = new AtomicReference<>(new Double(0.00));
		fdzList.forEach(stationBasic -> {
			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.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量"));
//            powerOfMonthFD.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量"));
//            powerOfAnnualFD.updateAndGet(v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量"));

			powerOfDayFD.updateAndGet(
					v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
			powerOfMonthFD.updateAndGet(
					v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量")));
			powerOfAnnualFD.updateAndGet(
					v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));

		});
		gfList.forEach(stationBasic -> {
			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.updateAndGet(
					v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay));
			powerOfMonthGF.updateAndGet(v -> v
					+ commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth));
			powerOfAnnualGF.updateAndGet(
					v -> v + commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear));
		});
		HashMap<String, String> stringHashMap4 = new HashMap<>();
		stringHashMap4.put("title", String.format(CommonConstans.Twodecimalplaces, powerOfDayFD.get()) + "/"
				+ String.format(CommonConstans.Twodecimalplaces, powerOfDayGF.get()));
		list1.add(stringHashMap4);
		HashMap<String, String> stringHashMap5 = new HashMap<>();
		stringHashMap5.put("title", String.format(CommonConstans.Twodecimalplaces, powerOfMonthFD.get()) + "/"
				+ String.format(CommonConstans.Twodecimalplaces, powerOfMonthGF.get()));
		list1.add(stringHashMap5);
		HashMap<String, String> stringHashMap6 = new HashMap<>();
		stringHashMap6.put("title", String.format(CommonConstans.Twodecimalplaces, powerOfAnnualFD.get()) + "/"
				+ String.format(CommonConstans.Twodecimalplaces, powerOfAnnualGF.get()));
		list1.add(stringHashMap6);
		HashMap<String, String> stringHashMap7 = new HashMap<>();
		stringHashMap7.put("title", String.format(CommonConstans.Twodecimalplaces, powerOfAnnualFD.get() / fdzValue)
				+ "/" + String.format(CommonConstans.Twodecimalplaces, powerOfAnnualGF.get() / gfvalue));
		list1.add(stringHashMap7);
		HashMap<String, String> stringHashMap8 = new HashMap<>();
		stringHashMap8.put("title",
				String.format(CommonConstans.Twodecimalplaces,
						(powerOfAnnualFD.get() * CommonConstans.wkwhToMv) / fdzInstall.doubleValue()) + "/"
						+ String.format(CommonConstans.Twodecimalplaces,
								(powerOfAnnualGF.get() * CommonConstans.wkwhToMv) / gfInstall.doubleValue()));
		list1.add(stringHashMap8);
		page1.setRecords(list1);
		HashMap<String, String> stringHashMap9 = new HashMap<>();
		stringHashMap9.put("title",
				String.format(CommonConstans.Fourdecimalplaces, powerOfDayFD.get() + powerOfDayGF.get()));
		HashMap<String, String> resultMap = new HashMap<>();
		//resultMap.put("Day", String.format(CommonConstans.Fourdecimalplaces, powerOfDayFD.get() + powerOfDayGF.get()));
		list2.add(stringHashMap9);
		HashMap<String, String> stringHashMap10 = new HashMap<>();
		stringHashMap10.put("title",
				String.format(CommonConstans.Twodecimalplaces, powerOfMonthFD.get() + powerOfMonthGF.get()));
		//resultMap.put("Moon",String.format(CommonConstans.Fourdecimalplaces, powerOfMonthFD.get() + powerOfMonthGF.get()));
		//resultMap.put("YJHWC", String.format(CommonConstans.Twodecimalplaces,(powerOfMonthFD.get() + powerOfMonthGF.get()) / moonValue * 100));
		list2.add(stringHashMap10);
		HashMap<String, String> stringHashMap11 = new HashMap<>();
		stringHashMap11.put("title",
				String.format(CommonConstans.Fourdecimalplaces, powerOfAnnualFD.get() + powerOfAnnualGF.get()));
		//resultMap.put("Year",String.format(CommonConstans.Fourdecimalplaces, powerOfAnnualFD.get() + powerOfAnnualGF.get()));
		list2.add(stringHashMap11);
		HashMap<String, String> stringHashMap12 = new HashMap<>();
		stringHashMap12.put("title", String.format(CommonConstans.Twodecimalplaces,
				(powerOfAnnualFD.get() + powerOfAnnualGF.get()) / yearValue * 100));
		//resultMap.put("NJHWC", String.format(CommonConstans.Twodecimalplaces,(powerOfAnnualFD.get() + powerOfAnnualGF.get()) / yearValue * 100));
		list2.add(stringHashMap12);
		page2.setRecords(list2);
		Double totalAnnual = (powerOfAnnualFD.get() + powerOfAnnualGF.get());
		HashMap<String, String> stringHashMap13 = new HashMap<>();
		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);
		
		
		//改为部盾接口
		String requestUrl = budunBaseURL + "?" + Constants.get_quota_info;
		LocalDate currentDate = LocalDate.now();
	    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		LocalDate yesterday = currentDate.minusDays(1);
		String formattedDate = yesterday.format(formatter);
	    JSONObject data = httpRequestUtil.getResPonse(requestUrl+"&reporting_data="+formattedDate, Constants.REQUEST_GET, "",
				Constants.resovleRule_data);
	    DecimalFormat df = new DecimalFormat("#.0000");
		if (data.getDouble("day_generating_capacity") != null) {
			  resultMap.put("Day", df.format(Double.valueOf(data.getDouble("day_generating_capacity"))));
		}
		if (data.getDouble("month_generating_capacity") != null) {
			 resultMap.put("Moon", df.format(Double.valueOf(data.getDouble("month_generating_capacity"))));
		}
		if (data.getDouble("year_generating_capacity") != null) {
			   resultMap.put("Year", df.format(Double.valueOf(data.getDouble("year_generating_capacity"))));
		}
		if (data.getString("month_quota_rate") != null) {
		    resultMap.put("YJHWC", data.getString("month_quota_rate").replace("%", ""));
		}
		if (data.getString("year_quota_rate") != null) {
		    resultMap.put("NJHWC", data.getString("year_quota_rate").replace("%", ""));
		}
		
		try {
			emqKeeper.getMqttClient().publish("bigscreen_zjrl_topic", JSON.toJSON(page).toString().getBytes("UTF-8"), 1,
					true);
			emqKeeper.getMqttClient().publish("bigscreen_ssscsj_topic", JSON.toJSON(page1).toString().getBytes("UTF-8"),
					1, true);
			emqKeeper.getMqttClient().publish("bigscreen_zssscsj_topic",
					JSON.toJSON(page2).toString().getBytes("UTF-8"), 1, true);
			emqKeeper.getMqttClient().publish("bigscreen_qgjrdz_topic",
					JSON.toJSON(resultMap).toString().getBytes("UTF-8"), 1, true);
			emqKeeper.getMqttClient().publish("bigscreen_zshgx_topic", JSON.toJSON(page3).toString().getBytes("UTF-8"),
					1, true);
		} catch (Exception ex) {

		}
	}

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

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

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

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

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

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

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

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

	public Map<String, String> getGenPowerInfoForBuDun(String areaCode, String stationId) {
		HashMap<String, String> returnResult = new HashMap<>();
		returnResult.put("monthCompleteRate", "0.00%");
		returnResult.put("monthValue", "0.0000");
		returnResult.put("monthPlanValue", "0.0000");
		returnResult.put("yearCompleteRate", "0.00%");
		returnResult.put("yearValue", "0.0000");
		returnResult.put("yearPlanValue", "0.0000");

		List<StationCacheInfoDto> stationCacheInfoDtos = commonServiceImpl.getListStationCacheInfoDto();
		if (StringUtils.isNotBlank(areaCode)) {
			stationCacheInfoDtos = stationCacheInfoDtos.stream()
					.filter(stationCacheInfoDto -> stationCacheInfoDto.getAreaCode().equals(areaCode))
					.collect(Collectors.toList());
		}
		if (StringUtils.isNotBlank(stationId)) {
			stationCacheInfoDtos = stationCacheInfoDtos.stream()
					.filter(stationCacheInfoDto -> stationCacheInfoDto.getStationId().equals(stationId))
					.collect(Collectors.toList());
		}
		// 月发电量
		AtomicReference<Double> monthlyPower = new AtomicReference<>(0.0);
		// 年发电量
		AtomicReference<Double> annualPower = new AtomicReference<>(0.0);
		for (StationCacheInfoDto stationCacheInfoDto : stationCacheInfoDtos) {

			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);
				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);
				monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(
						commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth)));
				annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(
						commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear)));
			}
		}
		List<String> stationIds = stationCacheInfoDtos.stream().map(StationCacheInfoDto::getStationId)
				.collect(Collectors.toList());
		List<StationPlan> stationPlans = stationPlanMapper
				.selectList(new QueryWrapper<StationPlan>().in("station_basic_id", stationIds));
		String currentYearAndMonth = DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN);
		String currentYear = currentYearAndMonth.split("-")[0];
		Integer currentMonth = Integer.valueOf(currentYearAndMonth.split("-")[1]);
		Double yearPlanValue = stationPlans.stream().filter(stationPlan -> stationPlan.getYear().equals(currentYear))
				.mapToDouble(i -> i.getValue()).sum();
		Double monthPlanValue = stationPlans.stream()
				.filter(stationPlan -> currentMonth == Integer.valueOf(stationPlan.getMonthly()))
				.mapToDouble(i -> i.getValue()).sum();
		if (monthlyPower.get() > 0 && monthPlanValue > 0) {
			returnResult.put("monthCompleteRate",
					String.format(CommonConstans.Twodecimalplaces, (monthlyPower.get() / monthPlanValue) * 100) + "%");
			returnResult.put("monthValue", String.format(CommonConstans.Fourdecimalplaces, monthlyPower.get()));
			returnResult.put("monthPlanValue", String.format(CommonConstans.Fourdecimalplaces, monthPlanValue));
		}
		if (annualPower.get() > 0 && yearPlanValue > 0) {
			returnResult.put("yearCompleteRate",
					String.format(CommonConstans.Twodecimalplaces, (annualPower.get() / yearPlanValue) * 100) + "%");
			returnResult.put("yearValue", String.format(CommonConstans.Fourdecimalplaces, annualPower.get()));
			returnResult.put("yearPlanValue", String.format(CommonConstans.Fourdecimalplaces, yearPlanValue));
		}
		return returnResult;
	}

	public Map<String, Object> getGenPowerInfo(String areaCode) {
		List<StationCacheInfoDto> stationCacheInfoDtos = commonServiceImpl.getListStationCacheInfoDto();
		if (StringUtils.isNotBlank(areaCode)) {
			MapRegion mapRegion = mapRegionMapper.selectOne(new QueryWrapper<MapRegion>().eq("area_code", areaCode));
			List<StationCacheInfoDto> filterData = stationCacheInfoDtos.stream()
					.filter(stationCacheInfoDto -> stationCacheInfoDto.getAreaCode().equals(areaCode))
					.collect(Collectors.toList());
			stationCacheInfoDtos = filterData.size() > 0 ? filterData : stationCacheInfoDtos;
			if (!ObjectUtils.isEmpty(mapRegion)) {
				stationCacheInfoDtos = filterData;
			}
		}
		List<StationCacheInfoDto> fanStationList = stationCacheInfoDtos.stream()
				.filter(stationCacheInfoDto -> stationCacheInfoDto.getStationType().equals("FDZ"))
				.collect(Collectors.toList());
		List<StationCacheInfoDto> pvStationList = stationCacheInfoDtos.stream()
				.filter(stationCacheInfoDto -> !stationCacheInfoDto.getStationType().equals("FDZ"))
				.collect(Collectors.toList());
		Map<String, List<StationCacheInfoDto>> groupByProvince = stationCacheInfoDtos.stream()
				.collect(Collectors.groupingBy(StationCacheInfoDto::getBelongProvince));
		HashMap<String, Object> returnResult = new HashMap<>();
		HashMap<String, Object> pv_interval = new HashMap<>();
		HashMap<String, Object> fan_interval = new HashMap<>();
		HashMap<String, Double> dayGenCache = new HashMap();
		HashMap<String, Double> monthGenCache = new HashMap();
		returnResult.put("pv_station_count", pvStationList.size());
		returnResult.put("fan_station_count", fanStationList.size());
		AtomicReference<Double> powerOfDayFD = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> powerOfMonthFD = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> powerOfDayGF = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> powerOfMonthGF = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> planOfFD = new AtomicReference<>(new Double(0.00));
		AtomicReference<Double> planOfGF = new AtomicReference<>(new Double(0.00));
		fanStationList.forEach(stationBasic -> {
			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);
			if (result != null) {
				powerOfDayFD.updateAndGet(
						v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
				powerOfMonthFD.updateAndGet(
						v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量")));
				dayGenCache.put(stationBasic.getStationId(),
						keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
				monthGenCache.put(stationBasic.getStationId(),
						keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量")));
			}
			planOfFD.updateAndGet(v -> v + getPlanGenByStationIdAndMonth(stationBasic.getStationId()));
		});
		pvStationList.forEach(stationBasic -> {
			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);
			if (result != null) {
				powerOfDayGF.updateAndGet(v -> v
						+ commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay));
				powerOfMonthGF.updateAndGet(v -> v
						+ commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth));
				dayGenCache.put(stationBasic.getStationId(), keepFourdecimalPlaces(
						commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay)));
				monthGenCache.put(stationBasic.getStationId(), keepFourdecimalPlaces(
						commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth)));
			}
			planOfGF.updateAndGet(v -> v + getPlanGenByStationIdAndMonth(stationBasic.getStationId()));
		});
		returnResult.put("today_pv_power", String.format(CommonConstans.Twodecimalplaces, powerOfDayGF.get()));
		returnResult.put("today_fan_power", String.format(CommonConstans.Twodecimalplaces, powerOfDayFD.get()));
		returnResult.put("month_pv_power", String.format(CommonConstans.Twodecimalplaces, powerOfMonthGF.get()));
		returnResult.put("month_fan_power", String.format(CommonConstans.Twodecimalplaces, powerOfMonthFD.get()));
		returnResult.put("month_pv_quota_schedule",
				String.format(CommonConstans.Twodecimalplaces, (powerOfMonthGF.get() / planOfGF.get()) * 100));
		if (returnResult.get("month_pv_quota_schedule").toString().equals("NaN")) {
			returnResult.put("month_pv_quota_schedule", 0.00f);
		}
		returnResult.put("month_fan_quota_schedule",
				String.format(CommonConstans.Twodecimalplaces, (powerOfMonthFD.get() / planOfFD.get()) * 100));
		if (returnResult.get("month_fan_quota_schedule").toString().equals("NaN")) {
			returnResult.put("month_fan_quota_schedule", 0.00f);
		}
		groupByProvince.keySet().forEach(s -> {
			HashMap<String, Object> fan = new HashMap<>();
			HashMap<String, Object> pv = new HashMap<>();
			List<StationCacheInfoDto> list = groupByProvince.get(s);
			List<String> fanStationIds = list.stream()
					.filter(stationCacheInfoDto -> stationCacheInfoDto.getStationType().equals("FDZ"))
					.collect(Collectors.toList()).stream()
					.map(stationCacheInfoDto -> stationCacheInfoDto.getStationId()).collect(Collectors.toList());
			List<String> pvStationIds = list.stream()
					.filter(stationCacheInfoDto -> !stationCacheInfoDto.getStationType().equals("FDZ"))
					.collect(Collectors.toList()).stream()
					.map(stationCacheInfoDto -> stationCacheInfoDto.getStationId()).collect(Collectors.toList());
			fan.put("station_count", fanStationIds.size());
			pv.put("station_count", pvStationIds.size());
			fan.put("today_power", getTotalPowerFromCache(fanStationIds, dayGenCache));
			pv.put("today_power", getTotalPowerFromCache(pvStationIds, dayGenCache));
			fan.put("month_power", getTotalPowerFromCache(fanStationIds, monthGenCache));
			pv.put("month_power", getTotalPowerFromCache(pvStationIds, monthGenCache));
			pv_interval.put(s, pv);
			fan_interval.put(s, fan);

		});
		returnResult.put("pv_interval", pv_interval);
		returnResult.put("fan_interval", fan_interval);
		return returnResult;
	}

	public Double getPlanGenByStationIdAndMonth(String stationId) {
		String[] dates = DateUtil.today().split("-");
		Double plan = stationPlanMapper.getPlanGenByStationIdAndMonth(stationId, dates[0],
				String.valueOf(Integer.valueOf(dates[1])));
		if (plan == null) {
			plan = 0.0;
		}
		return plan;
	}

	public Double getTotalPowerFromCache(List<String> keys, HashMap<String, Double> cache) {
		AtomicReference<Double> result = new AtomicReference<>(0.0);
		if (keys != null && !keys.isEmpty() && cache != null && !cache.isEmpty()) {
			keys.forEach(s -> {
				if(cache.get(s)!=null) 
				{
					result.set(result.get() + cache.get(s));
				}
			});
		}
		return keepFourdecimalPlaces(result.get());
	}
}
