package com.jiayue.ipfcst.service;

import com.jiayue.ipfcst.common.data.constant.enums.EquipmentTypeEnum;
import com.jiayue.ipfcst.common.data.entity.*;
import com.jiayue.ipfcst.common.data.repository.DisplayConfigRepository;
import com.jiayue.ipfcst.common.data.repository.ElectricFieldRepository;
import com.jiayue.ipfcst.common.data.repository.EnvironmentalDataRepository;
import com.jiayue.ipfcst.common.data.service.BaseService;
import com.jiayue.ipfcst.repository.EquipmentAttributeRepository;
import com.jiayue.ipfcst.repository.ProtocolGatherDataPointRepository;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class EnvironmentalDataService extends BaseService {

  private final EnvironmentalDataRepository environmentalDataRepository;

  private final ProtocolGatherDataPointRepository protocolGatherDataPointRepository;

  private final ElectricFieldRepository electricFieldRepository;

  private final EquipmentAttributeRepository equipmentAttributeRepository;

  private final DisplayConfigRepository displayConfigRepository;


  public Map<String, Object> getData(Long startTime, Long endTime, Integer eqId,Integer code) {

    Map<String, Object> map = new HashMap<>();

    Map<String, Object> footMap = new HashMap<>();

    EquipmentTypeEnum equipmentTypeEnum;

    String displayCode = "weatherStationEnvironmental";
    if (code == 1) {
      //获取气象站的数据类型集合
      equipmentTypeEnum = EquipmentTypeEnum.WEATHERSTATION;
    } else {
      //获取测风塔的数据类型集合
      equipmentTypeEnum = EquipmentTypeEnum.WINDTOWER;
      displayCode = "windTowerEnvironmental";
    }
    //根据常查的类型选择要查询的显示配置
    DisplayConfig displayConfig = displayConfigRepository.findByDisplayCode(displayCode);
    //因为实际功率属于场站的数据类型，所以要单独添加 EquipmentTypeEnum.POWERSTATION
    List<EquipmentAttribute> equipmentAttributes = equipmentAttributeRepository.findByEquipmentTypeOrEquipmentType(equipmentTypeEnum, EquipmentTypeEnum.POWERSTATION);

    //如果没有对应的显示配置，初始化一份
    if (displayConfig != null) {
      Integer[] allEqId = new Integer[equipmentAttributes.size()];
      int n = 0;
      for (EquipmentAttribute equipmentAttribute : equipmentAttributes) {
        allEqId[n] = equipmentAttribute.getId();
        n++;
      }
      List<ProtocolGatherDataPoint> byEquipmentAttribute = protocolGatherDataPointRepository.findByEquipmentAttributeIdIn(allEqId);
      String allCode = displayConfig.getShowCode() + displayConfig.getHiddenCode();
      StringBuilder showCode = new StringBuilder(displayConfig.getShowCode());
      String[] allCodes = allCode.split(",");
      for (ProtocolGatherDataPoint protocolGatherDataPoint : byEquipmentAttribute) {
        String nFieldName = protocolGatherDataPoint.getEquipmentAttribute().getEquipmentType().toString() + protocolGatherDataPoint.getEquipmentAttribute().getFieldName();
        if (!Arrays.asList(allCodes).contains(nFieldName)) {
          showCode.append(nFieldName).append(",");
        }
      }

      displayConfig.setShowCode(showCode.toString());
      displayConfigRepository.save(displayConfig);
    }

    //筛选设备对应的采集点表数据
    List<ProtocolGatherDataPoint> protocolGatherDataPoints = protocolGatherDataPointRepository.findByEquipmentIdOrEquipmentId(eqId, 0);
    //根据采集点表取出对应的数据类型
    List<EquipmentAttribute> equipmentAttributess = new ArrayList<>();
    for (EquipmentAttribute equipmentAttribute : equipmentAttributes) {
      if (protocolGatherDataPoints.stream().anyMatch(m -> m.getEquipmentAttribute().getId().equals(equipmentAttribute.getId()))) {
        equipmentAttributess.add(equipmentAttribute);
      }
    }

    List<EquipmentAttribute> resultEquipmentAttributes = new ArrayList<>();

    if (displayConfig == null) {
      resultEquipmentAttributes = equipmentAttributess;
    } else {
      String showCode = displayConfig.getShowCode();
      String[] split = showCode.split(",");

      for (EquipmentAttribute equipmentAttribute : equipmentAttributess) {
        String nFieldName = equipmentAttribute.getEquipmentType().toString() + equipmentAttribute.getFieldName();
        for (String s : split) {
          if (s.equals(nFieldName)) {
            resultEquipmentAttributes.add(equipmentAttribute);
          }
        }
      }
    }

    List<Map<String, Object>> tableColumn = getTableColumn(resultEquipmentAttributes);

    EquipmentTypeEnum[] equipmentTypeEnums = {equipmentTypeEnum, EquipmentTypeEnum.POWERSTATION};
    Integer[] eqIds = {eqId, 0};
    List<EnvironmentalData> environmentalDatas = environmentalDataRepository.findByStatisticalTimeBetweenAndEquipmentTypeEnumInAndEquipmentIdIn(new Date(startTime), new Date(endTime), equipmentTypeEnums, eqIds);

    List<EnvironmentalData> environmentalDataList = environmentalDatas.stream().filter(c -> c.getAvgValue() != null).collect(Collectors.toList());

    List<Map<String, Object>> dayList = new ArrayList<>();
    List<Map<String, Object>> monthList = new ArrayList<>();
    List<Map<String, Object>> yearList = new ArrayList<>();

    if (!environmentalDataList.isEmpty()) {
      dayList = getDayData(environmentalDataList, resultEquipmentAttributes, dayList);

      monthList = getMonthData(environmentalDataList, resultEquipmentAttributes, monthList);

      yearList = getYearData(environmentalDataList, resultEquipmentAttributes, yearList);

      footMap = getFootData(footMap, resultEquipmentAttributes, environmentalDataList);
    }

    map.put("footerData", footMap);
    map.put("tableColumn", tableColumn);
    map.put("dayList", dayList);
    map.put("monthList", monthList);
    map.put("yearList", yearList);

    return map;
  }


  public List<Map<String, String>> eqAttribute() {
    List<Map<String, String>> list = new ArrayList<>();
    ElectricField electricField = electricFieldRepository.findAll().get(0);
    Integer code = electricField.getElectricFieldTypeEnum().getCode();
    List<EquipmentAttribute> equipmentAttributes;
    if (code == 1) {
      //获取气象站的数据类型集合
      equipmentAttributes = equipmentAttributeRepository.findByEquipmentTypeOrEquipmentType(EquipmentTypeEnum.WEATHERSTATION, EquipmentTypeEnum.POWERSTATION);
    } else {
      //获取测风塔的数据类型集合
      equipmentAttributes = equipmentAttributeRepository.findByEquipmentTypeOrEquipmentType(EquipmentTypeEnum.WINDTOWER, EquipmentTypeEnum.POWERSTATION);
    }
    for (EquipmentAttribute equipmentAttribute : equipmentAttributes) {
      Map<String, String> map = new HashMap<>();
      String nFieldName = equipmentAttribute.getEquipmentType().toString() + equipmentAttribute.getFieldName();
      map.put("key", equipmentAttribute.getExplanation());
      map.put("value", nFieldName);
      list.add(map);

    }
    return list;
  }

  public List<EquipmentAttribute> getEqAttributeById(Integer eqId) {
    List<EquipmentAttribute> equipmentAttributes;
    EquipmentTypeEnum equipmentTypeEnum;
    //获取气象站的数据类型集合
    equipmentTypeEnum = EquipmentTypeEnum.WEATHERSTATION;
    equipmentAttributes = equipmentAttributeRepository.findByEquipmentTypeOrEquipmentType(equipmentTypeEnum, EquipmentTypeEnum.POWERSTATION);
    //筛选设备对应的采集点表数据
    List<ProtocolGatherDataPoint> protocolGatherDataPointList = protocolGatherDataPointRepository.findByEquipmentIdOrEquipmentId(eqId, 0);
    List<ProtocolGatherDataPoint> protocolGatherDataPoints = new ArrayList<>();
    for (ProtocolGatherDataPoint protocolGatherDataPoint : protocolGatherDataPointList) {
      EquipmentAttribute equipmentAttribute = equipmentAttributeRepository.findById(protocolGatherDataPoint.getEquipmentAttribute().getId()).get();
      if (equipmentAttribute.getEquipmentType().equals(equipmentTypeEnum) || equipmentAttribute.getEquipmentType().equals(EquipmentTypeEnum.POWERSTATION)) {
        protocolGatherDataPoints.add(protocolGatherDataPoint);
      }
    }

    //根据采集点表取出对应的数据类型
    List<EquipmentAttribute> equipmentAttributess = new ArrayList<>();
    for (EquipmentAttribute equipmentAttribute : equipmentAttributes) {
      if (protocolGatherDataPoints.stream().anyMatch(m -> m.getEquipmentAttribute().getId().equals(equipmentAttribute.getId()))) {
        equipmentAttributess.add(equipmentAttribute);
      }
    }
    return equipmentAttributess;
  }

  //用于获取集合最大值
  public EnvironmentalData getEnvMax(List<EnvironmentalData> environmentalDatass) {
    EnvironmentalData maxData;
    try {
      maxData = environmentalDatass.stream().filter(environmentalData -> environmentalData.getMaxValue() != null).collect(Collectors.toList()).stream().max(Comparator.comparing(EnvironmentalData::getMaxValue)).get();
    } catch (NoSuchElementException e) {
      e.printStackTrace();
      maxData = new EnvironmentalData();
    }

    return maxData;
  }

  //用于获取集合最小值
  public EnvironmentalData getEnvMin(List<EnvironmentalData> environmentalDatass) {
    EnvironmentalData minData;
    try {
      minData = environmentalDatass.stream().filter(environmentalData -> environmentalData.getMinValue() != null).collect(Collectors.toList()).stream().min(Comparator.comparing(EnvironmentalData::getMinValue)).get();
    } catch (NoSuchElementException e) {
      e.printStackTrace();
      minData = new EnvironmentalData();
    }

    return minData;
  }

  //用于获取集合平均值
  public double getEnvAvg(List<EnvironmentalData> environmentalDatass) {
    double avgData = -99;
    try {
      avgData = environmentalDatass.stream().filter(environmentalData -> environmentalData.getAvgValue() != null).collect(Collectors.toList()).stream().mapToDouble(environmentalData -> environmentalData.getAvgValue().doubleValue()).average().getAsDouble();
    } catch (NoSuchElementException e) {
      e.printStackTrace();
    }
    return avgData;
  }

  //未获取到值时为集合添加占位内容
  public Map<String, Object> putNoThing(Map<String, Object> tempMap, EquipmentAttribute equipmentAttribute) {
    String nFieldName = equipmentAttribute.getEquipmentType().toString() + equipmentAttribute.getFieldName();
    tempMap.put("maxAvgValue" + nFieldName, "");
    tempMap.put("max" + nFieldName, "");
    tempMap.put("maxTime" + nFieldName, "");
    tempMap.put("min" + nFieldName, "");
    tempMap.put("minTime" + nFieldName, "");
    tempMap.put("avg" + nFieldName, "");
    return tempMap;
  }


  //为成功获取到的数据对象进行数据封装
  public Map<String, Object> putVal(Map<String, Object> tempMap, EquipmentAttribute equipmentAttribute, EnvironmentalData maxEData, EnvironmentalData minEData, double asDouble) {
    String nFieldName = equipmentAttribute.getEquipmentType().toString() + equipmentAttribute.getFieldName();
    tempMap.put("maxAvgValue" + nFieldName, maxEData.getMaxAvgValue() == null ? "" : maxEData.getMaxAvgValue());
    tempMap.put("max" + nFieldName, maxEData.getMaxValue() == null ? "" : maxEData.getMaxValue());
    tempMap.put("maxTime" + nFieldName, maxEData.getMaxValueTime() == null ? "" : maxEData.getMaxValueTime());
    tempMap.put("min" + nFieldName, minEData.getMinValue() == null ? "" : minEData.getMinValue());
    tempMap.put("minTime" + nFieldName, minEData.getMinValueTime() == null ? "" : minEData.getMinValueTime());
    tempMap.put("avg" + nFieldName, asDouble == -99 ? "" : new BigDecimal(asDouble).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
    return tempMap;
  }


  public List<Map<String, Object>> getDayData(List<EnvironmentalData> environmentalDataList, List<EquipmentAttribute> equipmentAttributes, List<Map<String, Object>> dayList) {
    Map<String, List<EnvironmentalData>> afterFormatting = null;

    List<Map<String, EnvironmentalData>> beforeFormatting = new ArrayList<>();
    //提取日统计数据
    for (EnvironmentalData n : environmentalDataList) {
      HashMap<String, EnvironmentalData> map1 = new HashMap<>();
      map1.put(DateFormatUtils.format(n.getStatisticalTime(), "yyyyMMdd"), n);
      beforeFormatting.add(map1);
      afterFormatting = beforeFormatting.stream().flatMap(m -> m.entrySet().stream()).collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
    }
    Map<String, List<EnvironmentalData>> resultMap = new LinkedHashMap<>();
    afterFormatting.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> resultMap.put(e.getKey(), e.getValue()));
    for (String key : resultMap.keySet()) {
      Map<String, Object> tempMap = new HashMap<>();
      List<EnvironmentalData> n = resultMap.get(key);

      for (EquipmentAttribute equipmentAttribute : equipmentAttributes) {
        String nFieldName = equipmentAttribute.getEquipmentType().toString() + equipmentAttribute.getFieldName();
        String explanation = equipmentAttribute.getExplanation();
        List<EnvironmentalData> environmentalDatass = new ArrayList<>();
        for (EnvironmentalData environmentalData : n) {
          if (environmentalData.getEquipmentAttribute().equals(equipmentAttribute)) {
            environmentalDatass.add(environmentalData);
          }
        }
        if (!environmentalDatass.isEmpty()) {
          EnvironmentalData environmentalData = environmentalDatass.get(0);

          if (nFieldName.equals("WEATHERSTATIONglobalRDA") || nFieldName.equals("WEATHERSTATIONdirectRDA") || nFieldName.equals("WEATHERSTATIONdiffuseRDA") || nFieldName.equals("WEATHERSTATIONobliqueRDA") || nFieldName.equals("WEATHERSTATIONhourDA") || explanation.equals("日站外受阻电量") || explanation.equals("日站内受阻电量") || explanation.equals("日受阻电量")) {
            tempMap.put("sum" + nFieldName, environmentalData.getMaxValue());
          } else {
            tempMap.put("maxAvgValue" + nFieldName, environmentalData.getMaxAvgValue());
            tempMap.put("max" + nFieldName, environmentalData.getMaxValue());
            tempMap.put("maxTime" + nFieldName, environmentalData.getMaxValueTime());
            tempMap.put("min" + nFieldName, environmentalData.getMinValue());
            tempMap.put("minTime" + nFieldName, environmentalData.getMinValueTime());
            tempMap.put("avg" + nFieldName, environmentalData.getAvgValue());
          }
        } else {
          if (nFieldName.equals("WEATHERSTATIONglobalRDA") || nFieldName.equals("WEATHERSTATIONdirectRDA") || nFieldName.equals("WEATHERSTATIONdiffuseRDA") || nFieldName.equals("WEATHERSTATIONobliqueRDA") || nFieldName.equals("WEATHERSTATIONhourDA") || explanation.equals("日站外受阻电量") || explanation.equals("日站内受阻电量") || explanation.equals("日受阻电量")) {
            tempMap.put("sum" + nFieldName, "");
          } else {
            tempMap = putNoThing(tempMap, equipmentAttribute);
          }
        }
      }
      tempMap.put("times", key);
      dayList.add(tempMap);
    }

    return dayList;
  }


  public List<Map<String, Object>> getMonthData(List<EnvironmentalData> environmentalDataList, List<EquipmentAttribute> equipmentAttributes, List<Map<String, Object>> monthList) {
    Map<String, List<EnvironmentalData>> monthAfterFormatting = null;

    List<Map<String, EnvironmentalData>> monthBeforeFormatting = new ArrayList<>();
    //提取月统计数据
    for (EnvironmentalData n : environmentalDataList) {
      Map<String, EnvironmentalData> map1 = new HashMap<>();
      map1.put(DateFormatUtils.format(n.getStatisticalTime(), "yyyyMM"), n);
      monthBeforeFormatting.add(map1);
      monthAfterFormatting = monthBeforeFormatting.stream().flatMap(m -> m.entrySet().stream()).collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
    }
    Map<String, List<EnvironmentalData>> monthResultMap = new LinkedHashMap<>();
    monthAfterFormatting.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> monthResultMap.put(e.getKey(), e.getValue()));
    for (String key : monthResultMap.keySet()) {
      Map<String, Object> tempMap = new HashMap<>();
      List<EnvironmentalData> n = monthResultMap.get(key);

      for (EquipmentAttribute equipmentAttribute : equipmentAttributes) {
        String nFieldName = equipmentAttribute.getEquipmentType().toString() + equipmentAttribute.getFieldName();
        String explanation = equipmentAttribute.getExplanation();
        List<EnvironmentalData> environmentalDatass = new ArrayList<>();
        for (EnvironmentalData environmentalData : n) {
          if (environmentalData.getEquipmentAttribute().equals(equipmentAttribute)) {
            environmentalDatass.add(environmentalData);
          }
        }
        if (!environmentalDatass.isEmpty()) {
          if (nFieldName.equals("WEATHERSTATIONglobalRDA") || nFieldName.equals("WEATHERSTATIONdirectRDA") || nFieldName.equals("WEATHERSTATIONdiffuseRDA") || nFieldName.equals("WEATHERSTATIONobliqueRDA") || nFieldName.equals("WEATHERSTATIONhourDA") || explanation.equals("日站外受阻电量") || explanation.equals("日站内受阻电量") || explanation.equals("日受阻电量")) {
            //
            Map<String, List<EnvironmentalData>> afterFormattingDay = null;

            List<Map<String, EnvironmentalData>> beforeFormattingDay = new ArrayList<>();
            //提取日统计数据
            for (EnvironmentalData nDay : environmentalDatass) {
              Map<String, EnvironmentalData> map1 = new HashMap<>();
              map1.put(DateFormatUtils.format(nDay.getStatisticalTime(), "yyyyMMdd"), nDay);
              beforeFormattingDay.add(map1);
              afterFormattingDay = beforeFormattingDay.stream().flatMap(m -> m.entrySet().stream()).collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
            }
            Map<String, List<EnvironmentalData>> resultMapDay = new LinkedHashMap<>();
            afterFormattingDay.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> resultMapDay.put(e.getKey(), e.getValue()));
            List<EnvironmentalData> listDay = new ArrayList<>();
            for (String keyDay : resultMapDay.keySet()) {
              List<EnvironmentalData> nDay = resultMapDay.get(keyDay);
              EnvironmentalData maxEData = getEnvMax(nDay);
              listDay.add(maxEData);
            }
            //
            double sumValue = environmentalDatass.stream().filter(environmentalData -> environmentalData.getMaxValue() != null).collect(Collectors.toList()).stream().mapToDouble(environmentalData -> environmentalData.getMaxValue().doubleValue()).sum();
            BigDecimal bSumValue = new BigDecimal(sumValue);
            tempMap.put("sum" + nFieldName, bSumValue.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
            double asDouble = getEnvAvg(listDay);

            EnvironmentalData maxEData = getEnvMax(listDay);
            EnvironmentalData minEData = getEnvMin(listDay);
            tempMap = putVal(tempMap, equipmentAttribute, maxEData, minEData, asDouble);


          } else {
            EnvironmentalData maxEData = getEnvMax(environmentalDatass);
            EnvironmentalData minEData = getEnvMin(environmentalDatass);
            double asDouble = getEnvAvg(environmentalDatass);
            tempMap = putVal(tempMap, equipmentAttribute, maxEData, minEData, asDouble);
          }
        } else {
          tempMap = putNoThing(tempMap, equipmentAttribute);
          if (nFieldName.equals("WEATHERSTATIONglobalRDA") || nFieldName.equals("WEATHERSTATIONdirectRDA") || nFieldName.equals("WEATHERSTATIONdiffuseRDA") || nFieldName.equals("WEATHERSTATIONobliqueRDA") || nFieldName.equals("WEATHERSTATIONhourDA") || explanation.equals("日站外受阻电量") || explanation.equals("日站内受阻电量") || explanation.equals("日受阻电量")) {
            tempMap.put("sum" + nFieldName, "");
          }
        }
      }
      tempMap.put("times", key);
      monthList.add(tempMap);
    }

    return monthList;
  }


  public List<Map<String, Object>> getYearData(List<EnvironmentalData> environmentalDataList, List<EquipmentAttribute> equipmentAttributes, List<Map<String, Object>> yearList) {
    Map<String, List<EnvironmentalData>> yearAfterFormatting = null;
    //提取年统计数据
    List<Map<String, EnvironmentalData>> yearBeforeFormatting = new ArrayList<>();
    for (EnvironmentalData n : environmentalDataList) {
      Map<String, EnvironmentalData> map1 = new HashMap<>();
      map1.put(DateFormatUtils.format(n.getStatisticalTime(), "yyyy"), n);
      yearBeforeFormatting.add(map1);
      yearAfterFormatting = yearBeforeFormatting.stream().flatMap(m -> m.entrySet().stream()).collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
    }
    Map<String, List<EnvironmentalData>> yearResultMap = new LinkedHashMap<>();
    yearAfterFormatting.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> yearResultMap.put(e.getKey(), e.getValue()));
    for (String key : yearResultMap.keySet()) {
      Map<String, Object> tempMap = new HashMap<>();
      List<EnvironmentalData> n = yearResultMap.get(key);

      for (EquipmentAttribute equipmentAttribute : equipmentAttributes) {
        String nFieldName = equipmentAttribute.getEquipmentType().toString() + equipmentAttribute.getFieldName();
        String explanation = equipmentAttribute.getExplanation();
        List<EnvironmentalData> environmentalDatass = new ArrayList<>();
        for (EnvironmentalData environmentalData : n) {
          if (environmentalData.getEquipmentAttribute().equals(equipmentAttribute)) {
            environmentalDatass.add(environmentalData);
          }
        }
        if (!environmentalDatass.isEmpty()) {
          if (nFieldName.equals("WEATHERSTATIONglobalRDA") || nFieldName.equals("WEATHERSTATIONdirectRDA") || nFieldName.equals("WEATHERSTATIONdiffuseRDA") || nFieldName.equals("WEATHERSTATIONobliqueRDA") || nFieldName.equals("WEATHERSTATIONhourDA") || explanation.equals("日站外受阻电量") || explanation.equals("日站内受阻电量") || explanation.equals("日受阻电量")) {
            //
            Map<String, List<EnvironmentalData>> afterFormattingDay = null;

            List<Map<String, EnvironmentalData>> beforeFormattingDay = new ArrayList<>();
            //提取日统计数据
            for (EnvironmentalData nDay : environmentalDatass) {
              Map<String, EnvironmentalData> map1 = new HashMap<>();
              map1.put(DateFormatUtils.format(nDay.getStatisticalTime(), "yyyyMMdd"), nDay);
              beforeFormattingDay.add(map1);
              afterFormattingDay = beforeFormattingDay.stream().flatMap(m -> m.entrySet().stream()).collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
            }
            Map<String, List<EnvironmentalData>> resultMapDay = new LinkedHashMap<>();
            afterFormattingDay.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> resultMapDay.put(e.getKey(), e.getValue()));
            List<EnvironmentalData> listDay = new ArrayList<>();
            for (String keyDay : resultMapDay.keySet()) {
              List<EnvironmentalData> nDay = resultMapDay.get(keyDay);
              EnvironmentalData maxEData = getEnvMax(nDay);
              listDay.add(maxEData);
            }
            //
            double sumValue = environmentalDatass.stream().filter(environmentalData -> environmentalData.getMaxValue() != null).collect(Collectors.toList()).stream().mapToDouble(environmentalData -> environmentalData.getMaxValue().doubleValue()).sum();
            BigDecimal bSumValue = new BigDecimal(sumValue);
            tempMap.put("sum" + nFieldName, bSumValue.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
            double asDouble = getEnvAvg(listDay);

            EnvironmentalData maxEData = getEnvMax(listDay);
            EnvironmentalData minEData = getEnvMin(listDay);
            tempMap = putVal(tempMap, equipmentAttribute, maxEData, minEData, asDouble);
          } else {
            EnvironmentalData maxEData = getEnvMax(environmentalDatass);
            EnvironmentalData minEData = getEnvMin(environmentalDatass);
            double asDouble = getEnvAvg(environmentalDatass);
            tempMap = putVal(tempMap, equipmentAttribute, maxEData, minEData, asDouble);
          }
        } else {
          tempMap = putNoThing(tempMap, equipmentAttribute);
          if (nFieldName.equals("WEATHERSTATIONglobalRDA") || nFieldName.equals("WEATHERSTATIONdirectRDA") || nFieldName.equals("WEATHERSTATIONdiffuseRDA") || nFieldName.equals("WEATHERSTATIONobliqueRDA") || nFieldName.equals("WEATHERSTATIONhourDA") || explanation.equals("日站外受阻电量") || explanation.equals("日站内受阻电量") || explanation.equals("日受阻电量")) {
            tempMap.put("sum" + nFieldName, "");
          }
        }
      }
      tempMap.put("times", key);
      yearList.add(tempMap);
    }

    return yearList;
  }


  public Map<String, Object> getFootData(Map<String, Object> footMap, List<EquipmentAttribute> equipmentAttributes, List<EnvironmentalData> environmentalDataList) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //提取表格底部统计数据
    for (EquipmentAttribute equipmentAttribute : equipmentAttributes) {
      String nFieldName = equipmentAttribute.getEquipmentType().toString() + equipmentAttribute.getFieldName();
      String explanation = equipmentAttribute.getExplanation();
      List<EnvironmentalData> environmentalDatass = new ArrayList<>();
      for (EnvironmentalData environmentalData : environmentalDataList) {
        if (environmentalData.getEquipmentAttribute().equals(equipmentAttribute)) {
          environmentalDatass.add(environmentalData);
        }
      }
      if (!environmentalDatass.isEmpty()) {
        if (nFieldName.equals("WEATHERSTATIONglobalRDA") || nFieldName.equals("WEATHERSTATIONdirectRDA") || nFieldName.equals("WEATHERSTATIONdiffuseRDA") || nFieldName.equals("WEATHERSTATIONobliqueRDA") || nFieldName.equals("WEATHERSTATIONhourDA") || explanation.equals("日站外受阻电量") || explanation.equals("日站内受阻电量") || explanation.equals("日受阻电量")) {
          Map<String, List<EnvironmentalData>> afterFormattingDay = null;

          List<Map<String, EnvironmentalData>> beforeFormattingDay = new ArrayList<>();
          //提取日统计数据
          for (EnvironmentalData nDay : environmentalDatass) {
            Map<String, EnvironmentalData> map1 = new HashMap<>();
            map1.put(DateFormatUtils.format(nDay.getStatisticalTime(), "yyyyMMdd"), nDay);
            beforeFormattingDay.add(map1);
            afterFormattingDay = beforeFormattingDay.stream().flatMap(m -> m.entrySet().stream()).collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
          }
          Map<String, List<EnvironmentalData>> resultMapDay = new LinkedHashMap<>();
          afterFormattingDay.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> resultMapDay.put(e.getKey(), e.getValue()));
          List<EnvironmentalData> listDay = new ArrayList<>();
          for (String keyDay : resultMapDay.keySet()) {
            List<EnvironmentalData> nDay = resultMapDay.get(keyDay);
            EnvironmentalData maxEData = getEnvMax(nDay);
            listDay.add(maxEData);
          }
          //
          double sumValue = environmentalDatass.stream().filter(environmentalData -> environmentalData.getMaxValue() != null).collect(Collectors.toList()).stream().mapToDouble(environmentalData -> environmentalData.getMaxValue().doubleValue()).sum();
          BigDecimal bSumValue = new BigDecimal(sumValue);
          footMap.put("sum" + nFieldName, bSumValue.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
          double asDouble = getEnvAvg(listDay);
          footMap.put("avg" + nFieldName, asDouble == -99 ? "" : new BigDecimal(asDouble).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
          EnvironmentalData maxEData = getEnvMax(listDay);
          EnvironmentalData minEData = getEnvMin(listDay);
          footMap.put("maxAvgValue" + nFieldName, maxEData.getMaxAvgValue() == null ? "" : maxEData.getMaxAvgValue());
          footMap.put("max" + nFieldName, maxEData.getMaxValue() == null ? "" : maxEData.getMaxValue());
          footMap.put("maxTime" + nFieldName, maxEData.getMaxValueTime() == null ? "" : sdf.format(maxEData.getMaxValueTime()));
          footMap.put("min" + nFieldName, minEData.getMinValue() == null ? "" : minEData.getMinValue());
          footMap.put("minTime" + nFieldName, maxEData.getMinValueTime() == null ? "" : sdf.format(minEData.getMinValueTime()));
        } else {
          EnvironmentalData maxEData = getEnvMax(environmentalDatass);
          EnvironmentalData minEData = getEnvMin(environmentalDatass);
          double asDouble = getEnvAvg(environmentalDatass);

          footMap.put("maxAvgValue" + nFieldName, maxEData.getMaxAvgValue() == null ? "" : maxEData.getMaxAvgValue());
          footMap.put("max" + nFieldName, maxEData.getMaxValue() == null ? "" : maxEData.getMaxValue());
          footMap.put("maxTime" + nFieldName, maxEData.getMaxValueTime() == null ? "" : sdf.format(maxEData.getMaxValueTime()));
          footMap.put("min" + nFieldName, minEData.getMinValue() == null ? "" : minEData.getMinValue());
          footMap.put("minTime" + nFieldName, minEData.getMinValueTime() == null ? "" : sdf.format(minEData.getMinValueTime()));
          footMap.put("avg" + nFieldName, asDouble == -99 ? "" : new BigDecimal(asDouble).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
        }
      } else {
        footMap = putNoThing(footMap, equipmentAttribute);
        if (nFieldName.equals("WEATHERSTATIONglobalRDA") || nFieldName.equals("WEATHERSTATIONdirectRDA") || nFieldName.equals("WEATHERSTATIONdiffuseRDA") || nFieldName.equals("WEATHERSTATIONobliqueRDA") || nFieldName.equals("WEATHERSTATIONhourDA") || explanation.equals("日站外受阻电量") || explanation.equals("日站内受阻电量") || explanation.equals("日受阻电量")) {
          footMap.put("sum" + nFieldName, "");
        }
      }
    }
    return footMap;
  }


  public List<Map<String, Object>> getTableColumn(List<EquipmentAttribute> equipmentAttributes) {
    //按照数据类型分配表头名以及查询数据
    List<Map<String, Object>> tableColumn = new ArrayList<>();
    //提取表格数据项名称
    for (EquipmentAttribute equipmentAttribute : equipmentAttributes) {
      String nFieldName = equipmentAttribute.getEquipmentType().toString() + equipmentAttribute.getFieldName();
      String explanation = equipmentAttribute.getExplanation();
      Map<String, Object> fieldMap = new HashMap<>();
      fieldMap.put("title", equipmentAttribute.getExplanation());
      fieldMap.put("unit", equipmentAttribute.getMeasurementUnits());
      fieldMap.put("max", "max" + nFieldName);
      fieldMap.put("min", "min" + nFieldName);
      fieldMap.put("avg", "avg" + nFieldName);
      fieldMap.put("maxTime", "maxTime" + nFieldName);
      fieldMap.put("minTime", "minTime" + nFieldName);
      fieldMap.put("maxAvgValue", "maxAvgValue" + nFieldName);
      //因为总辐射日累计，直辐射日累计，散射辐射日累计，斜面辐射日累计，日照小时数需要计算统计值，所以加if判断处理
      if (nFieldName.equals("WEATHERSTATIONglobalRDA") || nFieldName.equals("WEATHERSTATIONdirectRDA") || nFieldName.equals("WEATHERSTATIONdiffuseRDA") || nFieldName.equals("WEATHERSTATIONobliqueRDA") || nFieldName.equals("WEATHERSTATIONhourDA") || explanation.equals("日站外受阻电量") || explanation.equals("日站内受阻电量") || explanation.equals("日受阻电量")) {
        fieldMap.put("sum", "sum" + nFieldName);
      }
      tableColumn.add(fieldMap);
    }
    return tableColumn;
  }
}
