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

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.elasticsearch.search.aggregations.metrics.ParsedSum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.component.emq.EmqKeeper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationPlan;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationBasicMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.StationPlanMapper;
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.ESDailyPowerGeneration;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESEquipments;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESMoonPowerGeneration;
import com.yeejoin.amos.boot.module.jxiop.biz.constants.CommonConstans;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.SeriesData;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.StationCacheInfoDto;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IndicatorData;
import com.yeejoin.amos.boot.module.jxiop.biz.tdmapper.IndicatorDataMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.utils.DateUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

/**
 * @description:
 * @author: tw
 * @createDate: 2023/8/10
 */
@Service
//@RequiredArgsConstructor
@Slf4j
public class LargeScreenImpl {
	@Autowired
	CommonServiceImpl commonServiceImpl;
	@Autowired
	StationPlanMapper StationPlanMapper;
	@Autowired
	MonitoringServiceImpl monitoringServiceImpl;
	@Autowired
	StationBasicMapper stationBasicMapper;
	@Autowired
	EmqKeeper emqKeeper;
	@Autowired
	IndicatorDataMapper indicatorDataMapper;
	@Autowired
	SjglZsjZsbtzServiceImpl SjglZsjZsbtzServiceImpl;
	@Autowired
	private HttpRequestUtil httpRequestUtil;
	@Autowired
	AmosRequestContext amosRequestContext;
	@Autowired
	RestTemplate restTemplate;

	private final String SS = "瞬时风速";
	private final String ZFS = "WTX-801_25_WTX-801_总辐射";
	private final String ZFSLJ = "WTX-801_25_WTX-801_总辐射累计";
	private final String RSD = "日发电量";
	private final String YFD = "月发电量";
	private final String NFD = "年发电量";

	/**
	 * 全国
	 */
	@Scheduled(cron = "0/10 * * * * ?")
	//@PostConstruct
	public Map<String, Double> getqg() {
		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<String> value = new ArrayList<>();
//		value.add(SS);
//		value.add(ZFS);
//		value.add(ZFSLJ);
//		Map<String, List<String>> map = new HashMap<>();
//		map.put("equipmentIndexName.keyword", value);
//		List<StationCacheInfoDto> stationCacheInfoDtos = commonServiceImpl.getListStationCacheInfoDto();
//		List<? extends Terms.Bucket> lidate = commonServiceImpl.getgroupavg(map, "valueF", "equipmentIndexName.keyword",
//				ESEquipments.class);
//		DecimalFormat format2 = new DecimalFormat("#.00");
//		for (Terms.Bucket bucket : lidate) {
//			Aggregations aggregation = bucket.getAggregations();
//			List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
//			for (Aggregation agg : listdata) {
//				ParsedAvg parsedAvg = (ParsedAvg) agg;
//
//				switch (bucket.getKeyAsString()) {
//				case SS:
//					mapdta.put("SS", Double.valueOf(format2.format(parsedAvg.getValue())));
//					break;
//				case ZFS:
//					mapdta.put("ZFS", Double.valueOf(format2.format(parsedAvg.getValue())));
//					break;
//				case ZFSLJ:
//					mapdta.put("ZFSLJ", Double.valueOf(format2.format(parsedAvg.getValue())));
//					break;
//				default:
//					break;
//				}
//			}
//		}

		// 改为部盾接口
		String requestUrl = Constants.BASE_URL + "?" + 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);
		if (data != null) {
//			// 部盾每天十二点才填报,如果十二点前没有数据则获取前一天的数据
//			if (data.getDouble("sum_irradiance") != null && data.getDouble("sum_irradiance") == 0) {
//				// 计算昨天日期
//				LocalDate yesterday = currentDate.minusDays(1);
//				formattedDate = yesterday.format(formatter);
//				data = httpRequestUtil.getResPonse(requestUrl + "&reporting_data=" + formattedDate,
//						Constants.REQUEST_GET, "", Constants.resovleRule_data);
//			}
			mapdta.put("SS", data.getDouble("average_wind_speed"));
//			mapdta.put("ZFS", data.getDouble("avg_irradiance"));
//			mapdta.put("ZFSLJ", data.getDouble("sum_irradiance"));
		}
		//平均辐照度和利用小时数采用合成测点的值
		Map<String, Double> pointValue = getPointValue();
		mapdta.put("ZFS", pointValue.get("ZFS"));
		mapdta.put("ZFSLJ", pointValue.get("ZFSLJ"));
//        //日发电量
//        AtomicReference<Double> dailyPower = new AtomicReference<>(0.0);
//        //月发电量
//        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);
//                dailyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
//                monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量")));
//                annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));
//            } else {
//                Map<String, List<String>> queryCondtion = new HashMap<>();
//                queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, CommonConstans.taiHeGenIndicator);
//                queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationCacheInfoDto.getBoosterGatewayId()));
//                List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null, ESEquipments.class);
//                dailyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay)));
//                monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth)));
//                annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear)));
//            }
//
//        }
//
//        mapdta.put("RSD", keepFourdecimalPlaces(dailyPower.get()));
//        mapdta.put("YFD", keepFourdecimalPlaces(monthlyPower.get()));
//        mapdta.put("NFD", keepFourdecimalPlaces(annualPower.get()));

		// 总和
//        value.clear();
//        value.add(RSD);
//        value.add(YFD);
//        value.add(NFD);
//        List<? extends Terms.Bucket> lidatesum = commonServiceImpl.getgroupsum(map, "valueF", "equipmentIndexName.keyword", ESEquipments.class);
//
//        for (Terms.Bucket bucket : lidatesum) {
//            Aggregations aggregation = bucket.getAggregations();
//            List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
//            for (Aggregation agg : listdata) {
//                ParsedSum parsedSum = (ParsedSum) agg;
//                switch (bucket.getKeyAsString()) {
//                    case RSD:
//                        mapdta.put("RSD", Double.valueOf(format2.format(parsedSum.getValue()*CommonConstans.pvGenPoweActor* CommonConstans.pvGenPoweActorDay)));
//                        break;
//                    case YFD:
//                        mapdta.put("YFD", Double.valueOf(format2.format(parsedSum.getValue()*CommonConstans.pvGenPoweActornew)));
//                        break;
//                    case NFD:
//                        mapdta.put("NFD", Double.valueOf(format2.format(parsedSum.getValue()*CommonConstans.pvGenPoweActorYear)));
//                        break;
//                    default:
//                        break;
//                }
//            }
//        }
//        //计算月完成百分比
//        //当前月份 获取
//        LocalDate currentDate = LocalDate.now();
//        int month = currentDate.getMonthValue();
//
//        QueryWrapper<StationPlan> wrapper = new QueryWrapper<>();
//        wrapper.select("ifnull(sum(value), 0) as sum_value");
//        wrapper.eq("monthly", month);
//        List<Map<String, Object>> list = StationPlanMapper.selectMaps(wrapper);
//        Double sumValue = list != null && !list.isEmpty() ? (Double) list.get(0).get("sum_value") : 0;
//        //计算年完成百分比
//        Double ybfb = sumValue > 0 ? mapdta.get("YFD") / sumValue * 100 : 0;
//        ybfb = new BigDecimal(ybfb).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
//
//        mapdta.put("YJHWC", ybfb);
//        QueryWrapper<StationPlan> wrapper1 = new QueryWrapper<>();
//        wrapper1.select("ifnull(sum(value), 0) as sum_value");
//        List<Map<String, Object>> list1 = StationPlanMapper.selectMaps(wrapper1);
//        Double sumValuen = list1 != null && !list1.isEmpty() ? (Double) list1.get(0).get("sum_value") : 0;
//        Double ybfbn = sumValuen > 0 ? mapdta.get("NFD") / sumValue * 100 : 0;
//        ybfbn = new BigDecimal(ybfbn).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
//        mapdta.put("NJHWC", ybfbn);
		try {
			emqKeeper.getMqttClient().publish("qg/yxzb", JSON.toJSONString(mapdta).getBytes(), 0, true);
		} catch (MqttException e) {
			e.printStackTrace();
		}
		return mapdta;

	}
	/**
	 * 获取平均辐照度和利用小时数
	 * @return
	 */
	private Map<String,Double> getPointValue() {
		Map<String,Double> resultMap=new HashMap();
		JSONObject jsonObject = sendCoreGetRequest(Constants.get_big_screen_point_url);
		if (!Objects.isNull(jsonObject)) {
			if (jsonObject.getInteger("status") == HttpStatus.OK.value()) {
				JSONArray resultJsonArray = jsonObject.getJSONArray("result");
				if (CollectionUtil.isNotEmpty(resultJsonArray)) {
					for (Object o : resultJsonArray) {
						if (o instanceof Map) {
							Map map = (Map) o;
							JSONObject result = new JSONObject(map);
							String pointName = (String) map.get("pointName");
							if ("大屏监控平均辐照度".equals(pointName)) {
								resultMap.put("ZFS",result.getDouble("value"));
							}
							if ("大屏监控利用小时数".equals(pointName)) {
								resultMap.put("ZFSLJ",result.getDouble("value"));
							}
						}
					}
				}

			}
		}
		return resultMap;
	}

	/**
	 * 发送GET请求
	 * @param url
	 * @return
	 */
	private JSONObject sendCoreGetRequest(String url) {
		HttpHeaders headers = new HttpHeaders();
		headers.set("Token", amosRequestContext.getToken());
		headers.set("Product", amosRequestContext.getProduct());
		headers.set("Appkey", amosRequestContext.getAppKey());
		HttpEntity entity = new HttpEntity<>(headers);
		log.info("发送GET请求,请求地址{}", url);
		try {
			ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class);
			if (HttpStatus.OK == response.getStatusCode()) {
				log.info("发送请求成功，请求返回体{}", response.getBody());
				return response.getBody();
			} else {
				throw new BadRequest("返回接口异常,失败原因[" + response + "]");
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BadRequest("发送GET请求失败,失败原因[" + e.getMessage() + "]");
		}
	}
	@Scheduled(cron = "0/10 * * * * ?")
	//@PostConstruct
	private void sendQYYXZBMqtt() {
		List<StationCacheInfoDto> listStationCacheInfoDto = commonServiceImpl.getListStationCacheInfoDto();
		Map<String, List<StationCacheInfoDto>> belongAreaList = listStationCacheInfoDto.stream()
				.collect(Collectors.groupingBy(StationCacheInfoDto::getAreaCode));
		for (String s : belongAreaList.keySet()) {
			// List<String> ids =
			// belongAreaList.get(s).stream().map(StationCacheInfoDto::getFanGatewayId).collect(Collectors.toList());
			getqy(belongAreaList.get(s), s);
		}
	}

	/**
	 * 区域
	 **/
	public Map<String, String> getqy(List<StationCacheInfoDto> gatewayId, String s) {
		Map<String, String> mapdta = new HashMap<>();
		mapdta.put("SS", "0");
		mapdta.put("ZFS", "0");
		mapdta.put("ZFSLJ", "0");
		mapdta.put("RSD", "0");
		mapdta.put("YFD", "0");
		mapdta.put("NFD", "0");
		mapdta.put("YJHWC", "0");
		mapdta.put("NJHWC", "0");
//		// 平均数
//		List<String> value = new ArrayList<>();
//		List<String> ids = new ArrayList<>();
//		for (StationCacheInfoDto stationCacheInfoDto : gatewayId) {
//			ids.add(stationCacheInfoDto.getFanGatewayId());
//			ids.add(stationCacheInfoDto.getBoosterGatewayId());
//		}
//
//		// List<String> ids =
//		// gatewayId.stream().map(StationCacheInfoDto::getFanGatewayId).collect(Collectors.toList());
//
//		value.add(SS);
//		value.add(ZFS);
//		value.add(ZFSLJ);
//		Map<String, List<String>> map = new HashMap<>();
//		map.put("equipmentIndexName.keyword", value);
//		map.put("gatewayId.keyword", ids);
//
//		List<? extends Terms.Bucket> lidate = commonServiceImpl.getgroupavg(map, "valueF", "equipmentIndexName.keyword",
//				ESEquipments.class);
//		DecimalFormat format2 = new DecimalFormat("#.00");
//		for (Terms.Bucket bucket : lidate) {
//			Aggregations aggregation = bucket.getAggregations();
//			List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
//			for (Aggregation agg : listdata) {
//				ParsedAvg parsedAvg = (ParsedAvg) agg;
//
//				switch (bucket.getKeyAsString()) {
//				case SS:
//					mapdta.put("SS", Double.valueOf(format2.format(parsedAvg.getValue())));
//					break;
//				case ZFS:
//					mapdta.put("ZFS", Double.valueOf(format2.format(parsedAvg.getValue())));
//					break;
//				case ZFSLJ:
//					mapdta.put("ZFSLJ", Double.valueOf(format2.format(parsedAvg.getValue())));
//					break;
//				default:
//					break;
//				}
//			}
//		}
//
//		// 日发电量
//		AtomicReference<Double> dailyPower = new AtomicReference<>(0.0);
//		// 月发电量
//		AtomicReference<Double> monthlyPower = new AtomicReference<>(0.0);
//		// 年发电量
//		AtomicReference<Double> annualPower = new AtomicReference<>(0.0);
//		for (StationCacheInfoDto stationBasic : gatewayId) {
//
//			if ("FDZ".equals(stationBasic.getStationType())) {
//				Map<String, List<String>> queryCondtion = new HashMap<>();
//				queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, Arrays.asList("日发电量", "月发电量", "年发电量"));
//				queryCondtion.put(CommonConstans.QueryStringGateWayId, Arrays.asList(stationBasic.getFanGatewayId()));
//				List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null,
//						ESEquipments.class);
//				dailyPower.updateAndGet(
//						v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "日发电量")));
//				monthlyPower.updateAndGet(
//						v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "月发电量")));
//				annualPower.updateAndGet(
//						v -> v + keepFourdecimalPlaces(commonServiceImpl.getSumByEquipmentIndxName(result, "年发电量")));
//			} else {
//				Map<String, List<String>> queryCondtion = new HashMap<>();
//				queryCondtion.put(CommonConstans.QueryStringEquipmentIndexName, CommonConstans.taiHeGenIndicator);
//				queryCondtion.put(CommonConstans.QueryStringGateWayId,
//						Arrays.asList(stationBasic.getBoosterGatewayId()));
//				List<ESEquipments> result = commonServiceImpl.getListDataByCondtions(queryCondtion, null,
//						ESEquipments.class);
//				dailyPower.updateAndGet(v -> v + keepFourdecimalPlaces(
//						commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorDay)));
//				monthlyPower.updateAndGet(v -> v + keepFourdecimalPlaces(
//						commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorMonth)));
//				annualPower.updateAndGet(v -> v + keepFourdecimalPlaces(
//						commonServiceImpl.getSumByEquipmentIndxName(result, CommonConstans.taiHeGenIndicatorYear)));
//			}
//
//		}
//
//		mapdta.put("RSD", keepFourdecimalPlaces(dailyPower.get()));
//		mapdta.put("YFD", keepFourdecimalPlaces(monthlyPower.get()));
//		mapdta.put("NFD", keepFourdecimalPlaces(annualPower.get()));
//
////        //总和
////        value.clear();
////        value.add(RSD);
////        value.add(YFD);
////        value.add(NFD);
////        List<? extends Terms.Bucket> lidatesum = commonServiceImpl.getgroupsum(map, "valueF", "equipmentIndexName.keyword", ESEquipments.class);
////
////        for (Terms.Bucket bucket : lidatesum) {
////            Aggregations aggregation = bucket.getAggregations();
////            List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
////            for (Aggregation agg : listdata) {
////                ParsedSum parsedSum = (ParsedSum) agg;
////                switch (bucket.getKeyAsString()) {
////                    case RSD:
////                        mapdta.put("RSD", Double.valueOf(format2.format(parsedSum.getValue()*CommonConstans.pvGenPoweActor* CommonConstans.pvGenPoweActorDay)));
////                        break;
////                    case YFD:
////                        mapdta.put("YFD", Double.valueOf(format2.format(parsedSum.getValue()*CommonConstans.pvGenPoweActornew)));
////                        break;
////                    case NFD:
////                        mapdta.put("NFD", Double.valueOf(format2.format(parsedSum.getValue()*CommonConstans.pvGenPoweActornew)));
////                        break;
////                    default:
////                        break;
////                }
////            }
////        }
//		// 计算月完成百分比
//		// 当前月份 获取
//		LocalDate currentDate = LocalDate.now();
//		int month = currentDate.getMonthValue();
//
//		QueryWrapper<StationPlan> wrapper = new QueryWrapper<>();
//		wrapper.select("ifnull(sum(value), 0) as sum_value");
//		wrapper.eq("monthly", month);
//		List<Map<String, Object>> list = StationPlanMapper.selectMaps(wrapper);
//		Double sumValue = list != null && !list.isEmpty() ? (Double) list.get(0).get("sum_value") : 0;
//		// 计算年完成百分比
//		Double ybfb = sumValue > 0 ? mapdta.get("YFD") / sumValue * 100 : 0;
//		ybfb = new BigDecimal(ybfb).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//
//		mapdta.put("YJHWC", ybfb);
//		QueryWrapper<StationPlan> wrapper1 = new QueryWrapper<>();
//		wrapper1.select("ifnull(sum(value), 0) as sum_value");
//		List<Map<String, Object>> list1 = StationPlanMapper.selectMaps(wrapper1);
//		Double sumValuen = list1 != null && !list1.isEmpty() ? (Double) list1.get(0).get("sum_value") : 0;
//		Double ybfbn = sumValuen > 0 ? mapdta.get("NFD") / sumValuen * 100 : 0;
//		ybfbn = new BigDecimal(ybfbn).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
//		mapdta.put("NJHWC", ybfbn);

		// 改为部盾接口
		String requestUrl = Constants.BASE_URL + "?" + 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 + "&code=" + s,
				Constants.REQUEST_GET, "", Constants.resovleRule_data);
		DecimalFormat df = new DecimalFormat("#.0000");
		if (data.getDouble("day_generating_capacity") != null) {
			mapdta.put("Day", df.format(Double.valueOf(data.getDouble("day_generating_capacity"))));
			mapdta.put("RSD", df.format(Double.valueOf(data.getDouble("day_generating_capacity"))));
		}
		if (data.getDouble("month_generating_capacity") != null) {
			mapdta.put("Moon", df.format(Double.valueOf(data.getDouble("month_generating_capacity"))));
			mapdta.put("YFD", df.format(Double.valueOf(data.getDouble("month_generating_capacity"))));
		}
		if (data.getDouble("year_generating_capacity") != null) {
			mapdta.put("Year", df.format(Double.valueOf(data.getDouble("year_generating_capacity"))));
			mapdta.put("NFD", df.format(Double.valueOf(data.getDouble("year_generating_capacity"))));
		}
		if (data.getString("month_quota_rate") != null) {
			mapdta.put("YJHWC", data.getString("month_quota_rate").replace("%", ""));
		}
		if (data.getString("year_quota_rate") != null) {
			mapdta.put("NJHWC", data.getString("year_quota_rate").replace("%", ""));
		}

		// 部盾每天十二点才填报,如果十二点前没有数据则获取前一天的数据
//		if (data.getDouble("sum_irradiance") != null && data.getDouble("sum_irradiance") == 0) {
//			// 计算昨天日期
//			LocalDate yesterday = currentDate.minusDays(1);
//			formattedDate = yesterday.format(formatter);
//			data = httpRequestUtil.getResPonse(requestUrl + "&reporting_data=" + formattedDate+"&code="+s, Constants.REQUEST_GET,
//					"", Constants.resovleRule_data);
//		}
		mapdta.put("SS", data.getString("average_wind_speed"));
//		mapdta.put("ZFS", data.getString("avg_irradiance"));
//		mapdta.put("ZFSLJ", data.getString("sum_irradiance"));
		Map<String, Double> pointValue = getPointValue();
		mapdta.put("ZFS", String.valueOf(pointValue.get("ZFS")));
		mapdta.put("ZFSLJ", String.valueOf(pointValue.get("ZFSLJ")));

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

	}

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

	// 全国发电趋势
//	@Scheduled(cron = "0/10 * * * * ? ")
	public SeriesData getSeriesDataqg() {

		// 获取今年当月 日发电趋势
		List<Double> listjn = gettimedate(new Date());
		// 获取去年当月 日发电趋势
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.YEAR, -1);
		Date oneYearAgoToday = calendar.getTime();
		List<Double> listqn = gettimedate(oneYearAgoToday);

		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<Map<String, Object>> list = new ArrayList<>();
		list.add(mapjn);
		list.add(mapqn);
		SeriesData seriesData = new SeriesData();
		seriesData.setSeriesData(list);
		// 获取日期
		List<String> listdate = dayReportnq(new Date());
		seriesData.setAxisData(listdate);
		try {
			emqKeeper.getMqttClient().publish("countryFd", JSON.toJSONString(seriesData).getBytes(), 0, false);
		} catch (MqttException e) {
			e.printStackTrace();
		}

		return seriesData;
	}

	// 获取区域月日发电量

	@Scheduled(cron = "0/10 * * * * ?")
	private void sendQYFDLMqtt() {
		List<StationCacheInfoDto> listStationCacheInfoDto = commonServiceImpl.getListStationCacheInfoDto();
		Map<String, List<StationCacheInfoDto>> belongAreaList = listStationCacheInfoDto.stream()
				.collect(Collectors.groupingBy(StationCacheInfoDto::getBelongArea));
		for (String s : belongAreaList.keySet()) {
			List<String> ids = belongAreaList.get(s).stream().map(StationCacheInfoDto::getFanGatewayId)
					.collect(Collectors.toList());
			getSeriesDataqy(new Date(), ids, s);
		}
	}

	// 区域发电趋势

	public SeriesData getSeriesDataqy(Date date, List<String> gatewayId, String areaCode) {

		// 获取今年当月 日发电趋势
		List<Double> listjn = gettimedateqy(new Date(), gatewayId);
		// 获取去年当月 日发电趋势
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.YEAR, -1);
		Date oneYearAgoToday = calendar.getTime();
		List<Double> listqn = gettimedateqy(oneYearAgoToday, gatewayId);

		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<Map<String, Object>> list = new ArrayList<>();
		list.add(mapjn);
		list.add(mapqn);
		SeriesData seriesData = new SeriesData();
		seriesData.setSeriesData(list);
		// 获取日期
		List<String> listdate = dayReportnq(new Date());
		seriesData.setAxisData(listdate);
		try {
			emqKeeper.getMqttClient().publish("qy/fdqs/" + areaCode, JSON.toJSONString(seriesData).getBytes(), 1, true);
		} catch (MqttException e) {
			e.printStackTrace();
		}

		return seriesData;

	}

	// 获取全国月日发电量

	public List<Double> gettimedate(Date date) {

		SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyyMM");
		String monthy = myFmt2.format(date);
		List<Double> listdate = new ArrayList<>();
		List<String> value = new ArrayList<>();
		value.add(RSD);
		Map<String, List<String>> map = new HashMap<>();
		map.put("equipmentIndexName.keyword", value);
		List<String> value1 = new ArrayList<>();
		value1.add(monthy);
		map.put("moon.keyword", value1);

		List<? extends Terms.Bucket> lidate = commonServiceImpl.getgroupsum(map, "value", "day.keyword",
				ESDailyPowerGeneration.class);

		Map<String, Double> mapdta = new HashMap<>();
		DecimalFormat format2 = new DecimalFormat("#.0000");

		for (Terms.Bucket bucket : lidate) {
			Aggregations aggregation = bucket.getAggregations();
			List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
			for (Aggregation agg : listdata) {
				ParsedSum parsedSum = (ParsedSum) agg;
				mapdta.put(bucket.getKeyAsString(), Double.valueOf(format2.format(parsedSum.getValue())));
			}
		}
		// 组装数据
		List<String> list = dayReport(date);
		for (String s : list) {
			if (mapdta != null && mapdta.containsKey(s)) {
				listdate.add(mapdta.get(s));
			} else {
				listdate.add(0d);
			}
		}
		try {
			emqKeeper.getMqttClient().publish("topic", JSON.toJSONString(listdate).getBytes(), 0, false);
		} catch (MqttException e) {
			e.printStackTrace();
		}

		return listdate;

	}

	public List<Double> gettimedateqy(Date date, List<String> stationId) {

		SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyyMM");
		String monthy = myFmt2.format(date);
		List<Double> listdate = new ArrayList<>();
		List<String> value = new ArrayList<>();
		value.add(RSD);
		Map<String, List<String>> map = new HashMap<>();
		map.put("equipmentIndexName.keyword", value);
		map.put("stationId.keyword", stationId);
		List<String> value1 = new ArrayList<>();
		value1.add(monthy);
		map.put("moon.keyword", value1);

		List<? extends Terms.Bucket> lidate = commonServiceImpl.getgroupsum(map, "value", "day.keyword",
				ESDailyPowerGeneration.class);

		Map<String, Double> mapdta = new HashMap<>();
		DecimalFormat format2 = new DecimalFormat("#.0000");

		for (Terms.Bucket bucket : lidate) {
			Aggregations aggregation = bucket.getAggregations();
			List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
			for (Aggregation agg : listdata) {
				ParsedSum parsedSum = (ParsedSum) agg;
				mapdta.put(bucket.getKeyAsString(), Double.valueOf(format2.format(parsedSum.getValue())));
			}
		}
		// 组装数据
		List<String> list = dayReport(date);
		for (String s : list) {
			if (mapdta != null && mapdta.containsKey(s)) {
				listdate.add(mapdta.get(s));
			} else {
				listdate.add(0d);
			}
		}

		return listdate;

	}

	//全国月发电量趋势
	@Scheduled(cron = "0/10 * * * * ?")
	public Map<String, Object> gettimedateyfd() {

		SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy");
		String monthy = myFmt2.format(new Date());
		List<Double> listdate = new ArrayList<>();
		List<String> value = new ArrayList<>();
		value.add(YFD);
		Map<String, List<String>> map = new HashMap<>();
		map.put("equipmentIndexName.keyword", value);
		List<String> value1 = new ArrayList<>();
		value1.add(monthy);
		map.put("year.keyword", value1);

		List<? extends Terms.Bucket> lidate = commonServiceImpl.getgroupsum(map, "value", "day.keyword",
				ESMoonPowerGeneration.class);

		Map<String, Double> mapdta = new HashMap<>();
		DecimalFormat format2 = new DecimalFormat("#.0000");

		for (Terms.Bucket bucket : lidate) {
			Aggregations aggregation = bucket.getAggregations();
			List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
			for (Aggregation agg : listdata) {
				ParsedSum parsedSum = (ParsedSum) agg;
				mapdta.put(bucket.getKeyAsString(), Double.valueOf(format2.format(parsedSum.getValue())));
			}
		}
		// 组装数据
		List<String> list = yueReport();
		for (String s : list) {
			if (mapdta != null && mapdta.containsKey(s)) {
				listdate.add(mapdta.get(s));
			} else {
				listdate.add(0d);
			}
		}
		Map<String, Object> mapjn = new HashMap<>();
		mapjn.put("seriesData", listdate);
		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;

	}

	// 区域月发电量趋势

	// 获取区域月日发电量

	@Scheduled(cron = "0/10 * * * * ?")
	public void sendQYFDLMqttyfd() {
		List<StationCacheInfoDto> listStationCacheInfoDto = commonServiceImpl.getListStationCacheInfoDto();
		Map<String, List<StationCacheInfoDto>> belongAreaList = listStationCacheInfoDto.stream()
				.collect(Collectors.groupingBy(StationCacheInfoDto::getBelongArea));
		for (String s : belongAreaList.keySet()) {
			List<String> ids = belongAreaList.get(s).stream().map(StationCacheInfoDto::getFanGatewayId)
					.collect(Collectors.toList());
			gettimedateqyyfd(new Date(), ids, s);
		}
	}

	public Map<String, Object> gettimedateqyyfd(Date date, List<String> gatewayId, String areaCode) {

		SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy");
		String monthy = myFmt2.format(date);
		List<Double> listdate = new ArrayList<>();
		List<String> value = new ArrayList<>();
		value.add(YFD);
		Map<String, List<String>> map = new HashMap<>();
		map.put("equipmentIndexName.keyword", value);
		map.put("gatewayId.keyword", gatewayId);
		List<String> value1 = new ArrayList<>();
		value1.add(monthy);
		map.put("year.keyword", value1);

		List<? extends Terms.Bucket> lidate = commonServiceImpl.getgroupsum(map, "value", "day.keyword",
				ESMoonPowerGeneration.class);

		Map<String, Double> mapdta = new HashMap<>();
		DecimalFormat format2 = new DecimalFormat("#.0000");

		for (Terms.Bucket bucket : lidate) {
			Aggregations aggregation = bucket.getAggregations();
			List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
			for (Aggregation agg : listdata) {
				ParsedSum parsedSum = (ParsedSum) agg;
				mapdta.put(bucket.getKeyAsString(), Double.valueOf(format2.format(parsedSum.getValue())));
			}
		}
		// 组装数据
		List<String> list = yueReport();
		for (String s : list) {
			if (mapdta != null && mapdta.containsKey(s)) {
				listdate.add(mapdta.get(s));
			} else {
				listdate.add(0d);
			}
		}
		Map<String, Object> mapjn = new HashMap<>();
		mapjn.put("seriesData", listdate);
		mapjn.put("axisData", list);
		try {
			System.out.println(JSON.toJSONString(mapjn));
			emqKeeper.getMqttClient().publish("qyyfd/fdqs/" + areaCode, JSON.toJSONString(mapjn).getBytes(), 0, false);
		} catch (MqttException e) {
			e.printStackTrace();
		}

		return mapjn;

	}

	// 全国发电完成趋势
	@Scheduled(cron = "0/10 * * * * ?")
	public Map<String, Object> gettimedateyfdqs() {
		SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy");
		String monthy = myFmt2.format(new Date());
		List<Double> listdate = new ArrayList<>();
		List<String> value = new ArrayList<>();
		value.add(YFD);
		Map<String, List<String>> map = new HashMap<>();
		map.put("equipmentIndexName.keyword", value);
		List<String> value1 = new ArrayList<>();
		value1.add(monthy);
		map.put("year.keyword", value1);

		List<? extends Terms.Bucket> lidate = commonServiceImpl.getgroupsum(map, "value", "day.keyword",
				ESMoonPowerGeneration.class);

		Map<String, Double> mapdta = new HashMap<>();
		DecimalFormat format2 = new DecimalFormat("#.0000");

		for (Terms.Bucket bucket : lidate) {
			Aggregations aggregation = bucket.getAggregations();
			List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
			for (Aggregation agg : listdata) {
				ParsedSum parsedSum = (ParsedSum) agg;
				mapdta.put(bucket.getKeyAsString(), Double.valueOf(format2.format(parsedSum.getValue())));
			}
		}
		// 计划完成量
		Map<String, Double> mapwc = new HashMap<>();
		QueryWrapper<StationPlan> wrapper = new QueryWrapper<>();
		wrapper.select(" monthly ,sum(value) `value` ");
		wrapper.eq("year", monthy);
		wrapper.groupBy("monthly");
		List<Map<String, Object>> list1 = StationPlanMapper.selectMaps(wrapper);
		for (Map<String, Object> stringObjectMap : list1) {
			mapwc.put(stringObjectMap.get("monthly").toString(),
					Double.valueOf(stringObjectMap.get("value").toString()));
		}

		// 组装数据
		List<String> list = yueReport();
		for (String s : list) {
			if (mapdta != null && mapdta.containsKey(s)) {
				if (mapwc != null && mapwc.containsKey(s)) {
					listdate.add(Double.valueOf(format2.format(mapdta.get(s) / mapwc.get(s) * 100)));

				} else {
					listdate.add(0d);
				}
			} else {
				listdate.add(0d);
			}
		}
		Map<String, Object> mapjn = new HashMap<>();
		mapjn.put("seriesData", listdate);
		mapjn.put("axisData", list);
		try {
			System.out.println(JSON.toJSONString(mapjn));
			emqKeeper.getMqttClient().publish("topic_yfdqs", JSON.toJSONString(mapjn).getBytes(), 0, false);
		} catch (MqttException e) {
			e.printStackTrace();
		}

		return mapjn;

	}

	// 区域发电完成趋势

	@Scheduled(cron = "0/10 * * * * ?")
	public void sendQYFDLMqttyfdqs() {
		List<StationCacheInfoDto> listStationCacheInfoDto = commonServiceImpl.getListStationCacheInfoDto();
		Map<String, List<StationCacheInfoDto>> belongAreaList = listStationCacheInfoDto.stream()
				.collect(Collectors.groupingBy(StationCacheInfoDto::getBelongArea));
		for (String s : belongAreaList.keySet()) {
			List<String> ids = belongAreaList.get(s).stream().map(StationCacheInfoDto::getFanGatewayId)
					.collect(Collectors.toList());
			List<String> idsStationId = belongAreaList.get(s).stream().map(StationCacheInfoDto::getStationId)
					.collect(Collectors.toList());
			gettimedateqyyfdqs(new Date(), ids, s, idsStationId);
		}
	}

	public Map<String, Object> gettimedateqyyfdqs(Date date, List<String> gatewayId, String areaCode,
												  List<String> idsStationId) {

		SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy");
		String monthy = myFmt2.format(date);
		List<Double> listdate = new ArrayList<>();
		List<String> value = new ArrayList<>();
		value.add(YFD);
		Map<String, List<String>> map = new HashMap<>();
		map.put("equipmentIndexName.keyword", value);
		map.put("gatewayId.keyword", gatewayId);
		List<String> value1 = new ArrayList<>();
		value1.add(monthy);
		map.put("year.keyword", value1);

		List<? extends Terms.Bucket> lidate = commonServiceImpl.getgroupsum(map, "value", "day.keyword",
				ESMoonPowerGeneration.class);

		Map<String, Double> mapdta = new HashMap<>();
		DecimalFormat format2 = new DecimalFormat("#.0000");

		for (Terms.Bucket bucket : lidate) {
			Aggregations aggregation = bucket.getAggregations();
			List<Aggregation> listdata = Objects.nonNull(aggregation) ? aggregation.asList() : null;
			for (Aggregation agg : listdata) {
				ParsedSum parsedSum = (ParsedSum) agg;
				mapdta.put(bucket.getKeyAsString(), Double.valueOf(format2.format(parsedSum.getValue())));
			}
		}

		// 计划完成量
		Map<String, Double> mapwc = new HashMap<>();
		QueryWrapper<StationPlan> wrapper = new QueryWrapper<>();
		wrapper.select(" monthly ,sum(value) `value` ");
		wrapper.eq("year", monthy);
		wrapper.in("station_basic_id", idsStationId);
		wrapper.groupBy("monthly");
		List<Map<String, Object>> list1 = StationPlanMapper.selectMaps(wrapper);
		for (Map<String, Object> stringObjectMap : list1) {
			mapwc.put(stringObjectMap.get("monthly").toString(),
					Double.valueOf(stringObjectMap.get("value").toString()));
		}

		// 组装数据
		List<String> list = yueReport();
		for (String s : list) {
			if (mapdta != null && mapdta.containsKey(s)) {
				if (mapwc != null && mapwc.containsKey(s)) {
					listdate.add(Double.valueOf(format2.format(mapdta.get(s) / mapwc.get(s) * 100)));

				} else {
					listdate.add(0d);
				}
			} else {
				listdate.add(0d);
			}
		}
		Map<String, Object> mapjn = new HashMap<>();
		mapjn.put("seriesData", listdate);
		mapjn.put("axisData", list);
		try {
			System.out.println(JSON.toJSONString(mapjn));
			emqKeeper.getMqttClient().publish("qyyfdqs/fdqs/" + areaCode, JSON.toJSONString(mapjn).getBytes(), 0,
					false);
		} catch (MqttException e) {
			e.printStackTrace();
		}

		return mapjn;

	}

	// 每个场站 曲线定时刷新
	@Scheduled(cron = "0/10 * * * * ?")
	public void getDetailsWindSpeedAlldata() {
		List<StationBasic> stationBasicList = stationBasicMapper
				.selectList(new QueryWrapper<StationBasic>().isNotNull("belong_area").isNotNull("fan_gateway_id"));
		for (StationBasic stationBasic : stationBasicList) {
			monitoringServiceImpl.getDetailsWindSpeedAlldata(stationBasic);
		}
	}

	// 全国场站功率和曲线

	@Scheduled(cron = "0/10 * * * * ?")
	public void getDetailsWindSpeedAlldataqgsh() {
		getDetailsWindSpeedAlldataqg();
	}

	public Map<String, Object> getDetailsWindSpeedAlldataqg() {
		List<StationBasic> stationBasicListfd = stationBasicMapper.selectList(new QueryWrapper<StationBasic>()
				.isNotNull("belong_area").isNotNull("fan_gateway_id").eq("station_type", "FDZ"));
		List<StationBasic> stationBasicListgf = stationBasicMapper.selectList(new QueryWrapper<StationBasic>()
				.isNotNull("belong_area").isNotNull("fan_gateway_id").eq("station_type", "JZSGFDZ"));

//        List<String> fdGatewayId = stationBasicListfd.stream().map(StationBasic::getBoosterGatewayId).collect(Collectors.joining(","));
//        List<String> gfGatewayId = stationBasicListgf.stream().map(StationBasic::getBoosterGatewayId).collect(Collectors.toList());
		String fdGatewayIds = stationBasicListfd.stream()
				.map(stationBasic -> "'" + stationBasic.getBoosterGatewayId() + "'").collect(Collectors.joining(","));
		String gfGatewayIds = stationBasicListgf.stream()
				.map(stationBasic -> "'" + stationBasic.getBoosterGatewayId() + "'").collect(Collectors.joining(","));

		List<StationBasic> stationBasicListAll = new ArrayList<>();
		stationBasicListAll.addAll(stationBasicListfd);
		stationBasicListAll.addAll(stationBasicListgf);
		AtomicReference<Double> installedCapacity = new AtomicReference<>(0.0);
		stationBasicListAll.forEach(stationBasic -> {
			installedCapacity.updateAndGet(v -> v + getStationCaPACITYL(stationBasic.getStationNumber()));
		});

		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> activePowerListFD = new ArrayList<>();
		List<IndicatorData> activePowerListGF = new ArrayList<>();
//        String startTime = cn.hutool.core.date.DateUtil.today() + " 00:00:00";
//        String endTime = cn.hutool.core.date.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);

		activePowerListFD = indicatorDataMapper
				.selectDataByequipmentIndexNameAndtimeqgNew(CommonConstans.xiazaoActivePowerPoint, fdGatewayIds);

		activePowerListGF = indicatorDataMapper
				.selectDataByequipmentIndexNameAndtimeqgNew(CommonConstans.taiheActivePowerPoint, gfGatewayIds);
		System.out.println(JSON.toJSONString(activePowerListFD));
		for (int i = 0; i < activePowerListFD.size(); i++) {
			IndicatorData indicatorData = activePowerListFD.get(i);
			IndicatorData indicatorData2 = activePowerListGF.get(i);
			time.add(cn.hutool.core.date.DateUtil.format(indicatorData.getCreatedTime(), "HH:mm"));
			// Double vl= indicatorData.getValueF()+indicatorData2.getValueF() *
			// CommonConstans.kwToMv;
			Double vl = Double.valueOf(String.format(CommonConstans.Twodecimalplaces, indicatorData.getValueF()))
					+ Double.valueOf(String.format(CommonConstans.Twodecimalplaces,
					indicatorData2.getValueF() * CommonConstans.kwToMv));
			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;
	}

	// 区域场站功率和曲线
	@Scheduled(cron = "0/10 * * * * ?")
	public void getDetailsWindqyqx() {
		List<StationBasic> stationBasicList = stationBasicMapper
				.selectList(new QueryWrapper<StationBasic>().isNotNull("belong_area").isNotNull("fan_gateway_id"));
		Map<String, List<StationBasic>> belongAreaList = stationBasicList.stream()
				.collect(Collectors.groupingBy(StationBasic::getBelongArea));
		for (String s : belongAreaList.keySet()) {
			getDetailsWindqy(s, belongAreaList.get(s));
		}
	}

	public Map<String, Object> getDetailsWindqy(String s, List<StationBasic> listStationCacheInfoDto) {
		List<StationBasic> stationBasicListfd = listStationCacheInfoDto.stream()
				.filter(e -> "FDZ".equals(e.getStationType())).collect(Collectors.toList());
		List<StationBasic> stationBasicListgf = listStationCacheInfoDto.stream()
				.filter(e -> !"FDZ".equals(e.getStationType())).collect(Collectors.toList());
//        String fdGatewayIds="";
//        String gfGatewayIds="";
//        List<String> fdGatewayId = stationBasicListfd.stream().map(StationBasic::getBoosterGatewayId).collect(Collectors.toList());
//        List<String> gfGatewayId = stationBasicListgf.stream().map(StationBasic::getBoosterGatewayId).collect(Collectors.toList());
		String fdGatewayIds = stationBasicListfd.stream()
				.map(stationBasic -> "'" + stationBasic.getBoosterGatewayId() + "'").collect(Collectors.joining(","));
		String gfGatewayIds = stationBasicListgf.stream()
				.map(stationBasic -> "'" + stationBasic.getBoosterGatewayId() + "'").collect(Collectors.joining(","));

		List<StationBasic> stationBasicListAll = new ArrayList<>();
		stationBasicListAll.addAll(stationBasicListfd);
		stationBasicListAll.addAll(stationBasicListgf);
		AtomicReference<Double> installedCapacity = new AtomicReference<>(0.0);
		stationBasicListAll.forEach(stationBasic -> {
			installedCapacity.updateAndGet(v -> v + getStationCaPACITYL(stationBasic.getStationNumber()));
		});

		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> activePowerListFD = new ArrayList<>();
		List<IndicatorData> activePowerListGF = new ArrayList<>();
//        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);

//        String startTime = DateUtils.convertDateToString(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
//        String endTime = DateUtils.convertDateToString(currentDayEndTime, DateUtils.DATE_TIME_PATTERN);

		activePowerListFD = indicatorDataMapper
				.selectDataByequipmentIndexNameAndtimeqgNew(CommonConstans.xiazaoActivePowerPoint, fdGatewayIds);

		activePowerListGF = indicatorDataMapper
				.selectDataByequipmentIndexNameAndtimeqgNew(CommonConstans.taiheActivePowerPoint, gfGatewayIds);
		System.out.println(JSON.toJSONString(activePowerListFD));
		for (int i = 0; i < activePowerListFD.size(); i++) {
			IndicatorData indicatorData = activePowerListFD.get(i);
			IndicatorData indicatorData2 = activePowerListGF.get(i);
			time.add(cn.hutool.core.date.DateUtil.format(indicatorData.getCreatedTime(), "HH:mm"));
			// Double vl= indicatorData.getValueF()+indicatorData2.getValueF() *
			// CommonConstans.kwToMv;
			Double vl = Double.valueOf(String.format(CommonConstans.Twodecimalplaces, indicatorData.getValueF()))
					+ Double.valueOf(String.format(CommonConstans.Twodecimalplaces,
					indicatorData2.getValueF() * CommonConstans.kwToMv));
			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(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;
	}

	public Map<String, Object> getDetailsWindSpeed(String gatewayId, String equipmentNumber) {

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

		List<IndicatorData> indicatorDataListWindSpeed = new ArrayList<>();
		List<IndicatorData> indicatorDataListActivePower = new ArrayList<>();
		indicatorDataListWindSpeed = indicatorDataMapper.selectDataByequipmentIndexNameAndtimeAndEquipmentNumber("瞬时风速",
				equipmentNumber, startTime, endTime, gatewayId);
		indicatorDataListActivePower = indicatorDataMapper.selectDataByequipmentIndexNameAndtimeAndEquipmentNumber(
				"有功功率", equipmentNumber, startTime, endTime, gatewayId);
		List<String> windSpeeds = new ArrayList<>();
		List<String> activePowers = new ArrayList<>();
		List<String> axisData = new ArrayList<>();
		for (int i = 0; i < indicatorDataListWindSpeed.size(); i++) {
			windSpeeds.add(indicatorDataListWindSpeed.get(i).getValue());
			activePowers.add(indicatorDataListActivePower.get(i).getValue());
			axisData.add(
					cn.hutool.core.date.DateUtil.format(indicatorDataListWindSpeed.get(i).getCreatedTime(), "HH:mm"));
		}
		List<Map<String, Object>> seriesData = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> map1 = new HashMap<>();
		Map<String, Object> map2 = new HashMap<>();
		map1.put("data", windSpeeds);
		map2.put("data", activePowers);
		seriesData.add(map1);
		seriesData.add(map2);
		map.put("seriesData", seriesData);
		map.put("axisData", axisData);
		return map;
	}

	public List<String> yueReport() {

		List<String> list = new ArrayList<>();

		for (int i = 1; i < 13; i++) {

			list.add(String.valueOf(i));
		}

		return list;
	}

	public Double getStationCaPACITYL(String werks) {
		Double installCapacity = 0.0;
		installCapacity = SjglZsjZsbtzServiceImpl.getStationCapactityByStationWerks(werks);
		return ObjectUtils.isEmpty(installCapacity) ? 0.00 : installCapacity;
	}

	public List<String> dayReport(Date month) {

		List<String> list = new ArrayList<>();

		Calendar cal = Calendar.getInstance();
		cal.setTime(month);// month 为指定月份任意日期
		int year = cal.get(Calendar.YEAR);
		int m = cal.get(Calendar.MONTH) + 1;
		int dayNumOfMonth = DateUtil.getDaysByYearMonth(year, m);
		cal.set(Calendar.DAY_OF_MONTH, 1);// 从一号开始

		for (int i = 0; i < dayNumOfMonth; i++) {

			list.add(String.valueOf(i + 1));
		}

		return list;
	}

	public List<String> dayReportnq(Date month) {

		List<String> list = new ArrayList<>();

		Calendar cal = Calendar.getInstance();
		cal.setTime(month);// month 为指定月份任意日期
		int year = cal.get(Calendar.YEAR);
		int m = cal.get(Calendar.MONTH) + 1;
		int dayNumOfMonth = DateUtil.getDaysByYearMonth(year, m);
		cal.set(Calendar.DAY_OF_MONTH, 1);// 从一号开始

		for (int i = 0; i < dayNumOfMonth; i++) {

			list.add(m + "-" + String.valueOf(i + 1));
		}
		try {
			emqKeeper.getMqttClient().publish("topic", JSON.toJSONString(list).getBytes(), 0, false);
		} catch (MqttException e) {
			e.printStackTrace();
		}

		return list;

	}

}