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.PowerStationStatusDataRepository;
import com.jiayue.ipfcst.common.data.repository.WindTowerStatusDataRepository;
import com.jiayue.ipfcst.common.data.service.BaseService;
import com.jiayue.ipfcst.repository.EquipmentAttributeRepository;
import com.jiayue.ipfcst.repository.ProtocolGatherDataPointRepository;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 测风塔数据业务层
 *
 * @author yh
 * @version 1.0
 * @since 2019/8/5 16:02
 */
@Service
public class WindTowerStatusDataService extends BaseService {

  private final WindTowerStatusDataRepository windTowerStatusDataRepository;
  private final ProtocolGatherDataPointRepository protocolGatherDataPointRepository;
  private final PowerStationStatusDataRepository powerStationStatusDataRepository;
  private final EquipmentAttributeRepository equipmentAttributeRepository;
  @Autowired
  public WindTowerStatusDataService(WindTowerStatusDataRepository windTowerStatusDataRepository,
                                    ProtocolGatherDataPointRepository protocolGatherDataPointRepository,
                                    PowerStationStatusDataRepository powerStationStatusDataRepository,
                                    EquipmentAttributeRepository equipmentAttributeRepository){
    this.windTowerStatusDataRepository = windTowerStatusDataRepository;
    this.protocolGatherDataPointRepository= protocolGatherDataPointRepository;
    this.powerStationStatusDataRepository = powerStationStatusDataRepository;
    this.equipmentAttributeRepository = equipmentAttributeRepository;
  }

  /**
   * 分页查询 环境监测仪数据 yh
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param no        设备编号
   * @param page      页码
   * @param size      条数
   * @param sortOrder 排序
   * @return
   */
  @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
  public Map<String, Object> findByTimeBetweenForPaging(Date startTime, Date endTime,
                                                        Integer page, Integer size,
                                                        Integer no, String sortOrder) throws NoSuchFieldException, IllegalAccessException {
    Map<String, Object> map = new HashMap<>();
    Sort sort = Sort.by(Sort.Direction.DESC, "time");
    if (sortOrder.contains("asc")) {
      sort = Sort.by(Sort.Direction.ASC, "time");
    }
    Specification<WindTowerStatusData> specification = this.Specification(startTime, endTime,no);
    Pageable pageable = PageRequest.of(page - 1, size, sort);
    Page windTowerStatusDatas = windTowerStatusDataRepository.findAll(specification,pageable);
    List<String> thList = this.getTableHead(no);
    Map<String,Object> dtoMap;
    List<Map<String,Object>> dataResult = new ArrayList<>();
    List<WindTowerStatusData> wList = windTowerStatusDatas.getContent();
    for(WindTowerStatusData w :wList){
      Class c = w.getClass();
      dtoMap = new LinkedHashMap<>();
      dtoMap.put("time",w.getTime());
      dtoMap.put("equipmentNo",w.getEquipmentNo());
      for(String th:thList){
        Field f = c.getDeclaredField(th);
        f.setAccessible(true);
        dtoMap.put(th, f.get(w));
      }
      dataResult.add(dtoMap);
    }
    map.put("content", dataResult);
    map.put("count", windTowerStatusDatas.getTotalElements());
    map.put("tableHead",thList);
    return map;
  }


  /**
   * 分页查询 环境监测仪数据 tl
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param no        设备编号
   * @param sortOrder 排序
   * @return
   */
  @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
  public Map<String, Object> findByTimeBetweenAndNoAndTimeStep(Date startTime, Date endTime,
                                                               Integer no,Long timeStep,String sortOrder) throws NoSuchFieldException, IllegalAccessException {
    Map<String, Object> map = new HashMap<>();

    List<WindTowerStatusData> list;
    List<WindTowerStatusData> resultList = new ArrayList<>();
    list = windTowerStatusDataRepository.findByEquipmentNoAndTimeBetween(no,startTime,endTime);

    long startTimeLong  = startTime.getTime();
    long endTimeLong  = endTime.getTime();
    if(startTimeLong%timeStep !=0){
      startTimeLong = startTimeLong -(startTimeLong%timeStep)+timeStep;
    }
    for(long i = startTimeLong;i<endTimeLong;i=i+timeStep) {
      long finalI =i;
      List<WindTowerStatusData> w = list.stream().filter(t -> t.getTime().getTime() == finalI).collect(Collectors.toList());
      if(w.size()>0){
        resultList.add(w.get(0));
      }
    }
    List<WindTowerStatusData> collect = null;
    if (sortOrder.contains("asc")) {
      collect= resultList.stream().sorted(Comparator.comparing(WindTowerStatusData::getTime)).collect(Collectors.toList());
    }else {
      collect= resultList.stream().sorted(Comparator.comparing(WindTowerStatusData::getTime).reversed()).collect(Collectors.toList());
    }
    List<String> thList = this.getTableHead(no);
    List<String> newThList = new ArrayList<>();

    Map<String,Object> dtoMap;
    List<Map<String,Object>> dataResult = new ArrayList<>();
    for(WindTowerStatusData w :collect){
      Class c = w.getClass();
      dtoMap = new LinkedHashMap<>();
      dtoMap.put("time",w.getTime());
      dtoMap.put("equipmentNo",w.getEquipmentNo());
      for(String th:thList){
        boolean b = hasField(c, th);
        boolean a = hasField(c.getSuperclass(), th);
        Field f;
        if (b){
          f = c.getDeclaredField(th);
          f.setAccessible(true);
          dtoMap.put(th, f.get(w));
        } else if (a){
          f=c.getSuperclass().getDeclaredField(th);
          f.setAccessible(true);
          dtoMap.put(th, f.get(w));
        }

      }
      dataResult.add(dtoMap);
    }

    for(String th:thList){
      WindTowerStatusData windTowerStatusData = new WindTowerStatusData();
      boolean b = hasField(windTowerStatusData.getClass(), th);
      boolean a = hasField(windTowerStatusData.getClass().getSuperclass(), th);
      if (b||a){
        newThList.add(th);
      }

    }
    map.put("content", dataResult);
    map.put("count", resultList.size());
    map.put("tableHead",newThList);


    return map;
  }

  public boolean hasField(Class c, String fieldName){
    Field[] fields = c.getDeclaredFields();
    for (Field f : fields) {
      if (fieldName.equals(f.getName())) {
        return true;
      }
    }
    return false;
  }


  /**
   * 查询条件 yh
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @param no       设备编号
   * @return 过滤条件
   */
  Specification<WindTowerStatusData> Specification(final Date startTime, final Date endTime,final Integer no) {
    return (Specification<WindTowerStatusData>) (root, criteriaQuery, cb) -> {
      List<Predicate> predicates = new ArrayList<>();
      if (startTime!=null) {
        //大于或等于传入时间
        predicates.add(cb.greaterThanOrEqualTo(root.get("time").as(Date.class), startTime));
      }
      if (endTime!=null) {
        //小于传入时间
        predicates.add(cb.lessThan(root.get("time").as(Date.class), endTime));
      }
      if(no!=null){
        predicates.add(cb.equal(root.get("equipmentNo").as(Integer.class), no));
      }
      //添加排序的功能
      return cb.and(predicates.toArray(new Predicate[predicates.size()]));

    };
  }



  /**
   * 获取测风塔数据实体所有私有属性名称集合
   * @return 属性名称集合
   */
  public List<String> getWindTowerStatusDataAttributeName(){
    List<String> attributeName = new ArrayList<>();
    WindTowerStatusData windTowerStatusData = new WindTowerStatusData();

    Class  c  = windTowerStatusData.getClass();
    Field[] fs= c.getDeclaredFields();
    for(Field f :fs){
      attributeName.add(f.getName());
    }

    return attributeName;
  }

  public List<String> getWindTowerStatusDataAttributeNamesForEquipmentAttribute(){
    List<String> attributeName = new ArrayList<>();

    List<EquipmentAttribute> byEquipmentType = equipmentAttributeRepository.findByEquipmentType(EquipmentTypeEnum.WINDTOWER);
    for (EquipmentAttribute equipmentAttribute : byEquipmentType) {
      attributeName.add(equipmentAttribute.getFieldName());
    }

    return attributeName;
  }


  /**
   *接入测风塔点位封装动态表头 yh
   *
   * @param equipmentId 设备ID
   * @return 接入数据类型的集合
   */
  public List<String> getTableHead(Integer equipmentId){
    List<String> allAttributeName = this.getWindTowerStatusDataAttributeNamesForEquipmentAttribute();
    List<String> heads = new ArrayList<>();
    ProtocolGatherDataPoint g=new ProtocolGatherDataPoint();
    g.setEquipmentId(equipmentId);
    g.setEquipmentType(EquipmentTypeEnum.WINDTOWER);
    List<ProtocolGatherDataPoint> pointList= protocolGatherDataPointRepository.findAll(Example.of(g));
    for(ProtocolGatherDataPoint p : pointList){
      String ponitName =  p.getEquipmentAttribute().getFieldName();
      if(ponitName !=null){
        for(String an: allAttributeName){
          if(an.equals(ponitName)){
            heads.add(an);
          }
        }
      }
    }

    return heads;
  }


  public Map<String,Object> queryCharts(Long startTime,Long endTime,Integer no) throws NoSuchFieldException, IllegalAccessException {
    Map<String ,Object> map = new HashMap<>();
    List<String> thList = this.getTableHead(no);
    List<WindTowerStatusData> allList = new ArrayList<>();
    List<String> wsList = new ArrayList<>();
    List<String> wdList = new ArrayList<>();
    List<String> times = new ArrayList<>();
    allList =  windTowerStatusDataRepository.findByEquipmentNoAndTimeBetween(no,new Date(startTime),new Date(endTime));
    Collections.sort(allList, Comparator.comparing(WindTowerStatusData::getTime));
    wsList = thList.stream().filter(t -> t.contains("wsInst")).collect(Collectors.toList());
    Map<String,List<BigDecimal>> wsMap = new LinkedHashMap<>();
    for(String ws:wsList){
      wsMap.put(ws, new ArrayList<>());
    }

    wdList = thList.stream().filter(t -> t.contains("wdInst")).collect(Collectors.toList());
    Map<String,List<BigDecimal>> wdMap = new LinkedHashMap();
    for(String wd:wdList){
      wdMap.put(wd, new ArrayList<>());
    }

    Long amendStartTime = startTime;
    Long timeStep = 300000L;
    if(startTime%timeStep !=0){
      amendStartTime = startTime - (startTime%timeStep) +timeStep;
    }

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for(long i = amendStartTime;i<endTime;i=i+1000*60*5L){
      long filterI = i;
      times.add(formatter.format(new Date(i)));
      List<WindTowerStatusData> filterList = allList.stream().filter(t -> t.getTime().getTime() == filterI).collect(Collectors.toList());
      if(filterList !=null && filterList.size()>0){
        WindTowerStatusData w = filterList.get(0);
        Class c = w.getClass();
        Field f;
        for(String wsKey : wsMap.keySet()){
          f = c.getDeclaredField(wsKey);
          f.setAccessible(true);
          if(new BigDecimal(-99).compareTo((BigDecimal)f.get(w))==0){
            wsMap.get(wsKey).add(null);
          }else{
            wsMap.get(wsKey).add((BigDecimal) f.get(w));
          }
        }

        for(String wdKey : wdMap.keySet()){
          f = c.getDeclaredField(wdKey);
          f.setAccessible(true);
          if(new BigDecimal(-99).compareTo((BigDecimal)f.get(w))==0){
            wdMap.get(wdKey).add(null);
          }else{
            wdMap.get(wdKey).add((BigDecimal) f.get(w));
          }
        }

      }else{

        for(String wsKey : wsMap.keySet()){
          wsMap.get(wsKey).add(null);
        }
        for(String wsKey : wdMap.keySet()){
          wdMap.get(wsKey).add(null);
        }

      }

    }
    Map<String,Object> wdFrequencyMap = new LinkedHashMap<>();

    for(String wdMapKey:wdMap.keySet()){
      int[] frequency16 = new int[16];
      Float[] frequency16Rate = new Float[16];
      for(BigDecimal b: wdMap.get(wdMapKey)){

        if(b!=null){
          float wdfloat = b.floatValue();
          //N 北 0 348.76-11.25
          if( (wdfloat>=348.76F && wdfloat<=360F) || (wdfloat>=0 && wdfloat<= 11.25)){
            frequency16[0]++;
          }
          //NNE 北东北 22.5 11.26-33.75
          if(wdfloat>=11.26F && wdfloat<=33.75F){
            frequency16[15]++;
          }
          //NE 东北 45 33.76-56.25
          if(wdfloat>=33.76F && wdfloat<=56.25F){
            frequency16[14]++;
          }
          //ENE 东东北 67.5 56.26-78.75
          if(wdfloat>=56.26F && wdfloat<=78.75F){
            frequency16[13]++;
          }
          //E 东 90 78.76-101.25
          if(wdfloat>=78.76F && wdfloat<=101.25F){
            frequency16[12]++;
          }
          //ESE 东东南 112.5 101.26-123.75
          if(wdfloat>=101.26F && wdfloat<=123.75F){
            frequency16[11]++;
          }
          //SE 东南 135 123.76-146.25
          if(wdfloat>=123.76F && wdfloat<=146.25F){
            frequency16[10]++;
          }
          //SSE 南东南 157.5 146.26-168.75
          if(wdfloat>=146.26F && wdfloat<=168.75F){
            frequency16[9]++;
          }
          //S 南 180 168.76-191.25
          if(wdfloat>=168.76F && wdfloat<=191.25F){
            frequency16[8]++;
          }
          //SSW 南西南 202.5 191.26-213.75
          if(wdfloat>=191.26F && wdfloat<=213.75F){
            frequency16[7]++;
          }
          //SW 西南  225 213.76-236.25
          if(wdfloat>=213.76F && wdfloat<=236.25F){
            frequency16[6]++;
          }
          //WSW 西西南 247.5 236.26-258.75
          if(wdfloat>=236.26F && wdfloat<=258.75F){
            frequency16[5]++;
          }
          //W 西 270 258.76-281.25
          if(wdfloat>=258.76F && wdfloat<=281.25F){
            frequency16[4]++;
          }
          //WNW 西西北 295.5 281.26-303.75
          if(wdfloat>=281.26F && wdfloat<=303.75F){
            frequency16[3]++;
          }
          //NW 西北 315 303.76-326.25
          if(wdfloat>=303.76F && wdfloat<=326.25F){
            frequency16[2]++;
          }
          //NNW 北西北 337.5 326.26-348.
          if(wdfloat>=326.26F && wdfloat<=348.75F){
            frequency16[1]++;
          }
        }
      }

      if(wdMapKey.equals("wdInst50")||wdMapKey.equals("wdInst70")){
        String[] d = {"北","北西北","西北","西西北","西","西西南","西南","南西南","南","南东南","东南","东东南","东","东北北","东北","北东北"};
        int result = 0;
        String dr = "无";
        for (int i = 0; i < d.length; i++) {
          if(frequency16[i]>result){
            result = frequency16[i];
            dr = d[i];
          }
        }
        map.put(wdMapKey,dr);
      }


      BigDecimal sumToltal= new BigDecimal(0);
      for(int wdf:frequency16){
        BigDecimal b = new BigDecimal(wdf);
        sumToltal = sumToltal.add(b);
      }

      for(int i =0; i<frequency16.length;i++){
        if(frequency16[i] ==0){
          frequency16Rate[i]= 0f;
        }else{
          BigDecimal dividend = new BigDecimal(frequency16[i]);
          frequency16Rate[i] =dividend.divide(sumToltal,2, BigDecimal.ROUND_HALF_UP).floatValue();
        }
      }
      wdFrequencyMap.put(wdMapKey,frequency16Rate);
    }

    Map<String,Object> wsFrequencyMap = new LinkedHashMap<>();

    for(String wsMapKey:wsMap.keySet()){
      int[] wsFrequency = new int[10];
      float[] wsFrequencyRate = new float[16];
      for(BigDecimal b: wsMap.get(wsMapKey)){

        if(b!=null){
          float wsfloat = b.floatValue();
          //0-3米风速
          if(wsfloat >=0 && wsfloat<=3){
            wsFrequency[0]++;
          }
          //3-6米风速
          if(wsfloat >3 && wsfloat<=6){
            wsFrequency[1]++;
          }
          //6-9米风速
          if(wsfloat >6 && wsfloat<=9){
            wsFrequency[2]++;
          }
          //9-12米风速
          if(wsfloat >9 && wsfloat<=12){
            wsFrequency[3]++;
          }
          //12-15米风速
          if(wsfloat >12 && wsfloat<=15){
            wsFrequency[4]++;
          }
          //15-18米风速
          if(wsfloat >15 && wsfloat<=18){
            wsFrequency[5]++;
          }
          //18-21米风速
          if(wsfloat >18 && wsfloat<=21){
            wsFrequency[6]++;
          }
          //21-24米风速
          if(wsfloat >21 && wsfloat<=24){
            wsFrequency[7]++;
          }
          //24-27米风速
          if(wsfloat >24 && wsfloat<=27){
            wsFrequency[8]++;
          }
          //27米以上风速
          if(wsfloat >27){
            wsFrequency[9]++;
          }
        }
      }

      BigDecimal sumToltal= new BigDecimal(0);

      for(int wdf:wsFrequency){
        BigDecimal b = new BigDecimal(wdf);
        sumToltal = sumToltal.add(b);
      }

      for(int i =0; i<wsFrequency.length;i++){
        if(wsFrequency[i] ==0){
          wsFrequencyRate[i]= 0f;
        }else{
          BigDecimal dividend = new BigDecimal(wsFrequency[i]);
          wsFrequencyRate[i] =dividend.divide(sumToltal,2, BigDecimal.ROUND_HALF_UP).floatValue();
        }
      }

      wsFrequencyMap.put(wsMapKey,wsFrequencyRate);
    }


    map.put("ws",wsMap);
    map.put("wd",wdFrequencyMap);
    map.put("wf",wsFrequencyMap);
    map.put("times",times);

    return map;
  }

  /**
   * 条件查询
   *
   */
  public List<WindTowerStatusData> findByEquipmentNoAndTimeBetweenOrderByTimeAsc(Date startTime,Date endTime,Integer no,Long timeStep){
    List<WindTowerStatusData> list;

    List<WindTowerStatusData> resultList = new ArrayList<>();
    list = windTowerStatusDataRepository.findByEquipmentNoAndTimeBetween(no,startTime,endTime);

    long startTimeLong  = startTime.getTime();
    long endTimeLong  = endTime.getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    List<String> times = new ArrayList<>();

    if(startTimeLong%timeStep !=0){
      startTimeLong = startTimeLong -(startTimeLong%timeStep)+timeStep;
    }
    BigDecimal nullValue = new BigDecimal(-99);
    for(long i = startTimeLong;i<endTimeLong;i=i+timeStep) {
      long finalI =i;
      List<WindTowerStatusData> w = list.stream().filter(t -> t.getTime().getTime() == finalI).collect(Collectors.toList());
      if(w.size()>0){
        resultList.add(w.get(0));
      }
    }

    return resultList;
  }


  /**
   * （统计查询：测风塔风速统计）
   * 根据数据类型查询风速数据
   * @param startTime        起始时间
   * @param endTime          截止时间
   * @param dateType          数据类型
   * @param dateType         统计频率
   * @return 数据集合
   */
  public List<Map<String,Object>> queryAnemometerSpeed(Long startTime, Long endTime,String dateType,Integer no,String dataType){
    List<WindTowerStatusData> list = windTowerStatusDataRepository.findByEquipmentNoAndTimeBetween(no,new Date(startTime),new Date(endTime));

    Map<String, List<Float>> afterFormatting = null;
    String date = "yyyyMMdd";
    //进行年月日判断
    if(dateType.equals("year")){
      date = "yyyy";
    }else if(dateType.equals("month")) {
      date = "yyyyMM";
    }
    List<Map<String,Float>> beforeFormatting = new ArrayList<>();
    for (WindTowerStatusData n:list) {
      Map<String,Float> map1 = new HashMap();
      if(dataType.equals("10")){
        map1.put(DateFormatUtils.format(n.getTime(),date),n.getWsInst10().floatValue()==-99?0:n.getWsInst10().floatValue());
      }else if(dataType.equals("30")){
        map1.put(DateFormatUtils.format(n.getTime(),date),n.getWdInst30().floatValue()==-99?0:n.getWsInst30().floatValue());
      }else if(dataType.equals("50")){
        map1.put(DateFormatUtils.format(n.getTime(),date),n.getWsInst50().floatValue()==-99?0:n.getWsInst50().floatValue());
      }else if(dataType.equals("70")){
        map1.put(DateFormatUtils.format(n.getTime(),date),n.getWsInst70().floatValue()==-99?0:n.getWsInst70().floatValue());
      }else if(dataType.equals("80")){
        map1.put(DateFormatUtils.format(n.getTime(),date),n.getWsInst80().floatValue()==-99?0:n.getWsInst80().floatValue());
      }else if(dataType.equals("90")){
        map1.put(DateFormatUtils.format(n.getTime(),date),n.getWsInst90().floatValue()==-99?0:n.getWsInst90().floatValue());
      }else if(dataType.equals("100")){
        map1.put(DateFormatUtils.format(n.getTime(),date),n.getWsInst100().floatValue()==-99?0:n.getWsInst100().floatValue());
      }else if(dataType.equals("110")){
        map1.put(DateFormatUtils.format(n.getTime(),date),n.getWsInst110().floatValue()==-99?0:n.getWsInst110().floatValue());
      }
      beforeFormatting.add(map1);
    }
    afterFormatting = beforeFormatting.stream().flatMap(m -> m.entrySet().stream()).collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
    List<Map<String,Object>> dataList = new ArrayList<>();
    //排序
    Map<String, List<Float>> resultMap = new LinkedHashMap<>();
    afterFormatting.entrySet().stream()
      .sorted(Map.Entry.<String, List<Float>>comparingByKey()).forEachOrdered(e -> resultMap.put(e.getKey(), e.getValue()));
    //遍历集合计算出每个时间段集合的最大值、最小值，平均值
    for (String key : resultMap.keySet()) {
      List<Float> n = resultMap.get(key);

      Float maxValue = Collections.max(n);
      Float minValue = Collections.min(n);
      Float init = 0f;
      BigDecimal sum = new BigDecimal(init);
      for (int i = 0;i<n.size();i++){
        BigDecimal value = new BigDecimal(n.get(i));
        sum = sum.add(value);
      }
      BigDecimal size = new BigDecimal(n.size());
      BigDecimal avgValue = sum.divide(size,4,BigDecimal.ROUND_HALF_UP);
      Map<String,Object> map2 = new HashMap<>();
      map2.put("time",key);
      map2.put("maxValue",maxValue);
      map2.put("avgValue",avgValue);
      map2.put("minValue",minValue);
      dataList.add(map2);
    }
    return dataList;
  }


  /**
   * （统计查询：功率与风速统计（吉林22））
   * 实际功率与70米风速瞬时值统计
   * @param startTime 开始时间
   * @param endTime 结束时间
   * @param type 统计类型
   * @return Map
   */
  public List<Map> queryRealPowerWsStatistic(Long startTime, Long endTime,String type,Integer no){
    List<Map> returnList = new ArrayList<>();
    List<PowerStationStatusData> powerStationStatusDataList = powerStationStatusDataRepository.findByTimeBetween(new Date(startTime),new Date(endTime));
    String dateFormatVar = "";
    if ("day".equals(type)){
      dateFormatVar = "yyyyMMdd";
    }
    else{
      dateFormatVar = "yyyyMM";
    }

    List<Map<String,PowerStationStatusData>> beforeFormatting = new ArrayList<>();
    for (PowerStationStatusData realPower:powerStationStatusDataList) {
      Map<String,PowerStationStatusData> map1 = new HashMap();
      map1.put(DateFormatUtils.format(realPower.getTime(),dateFormatVar),realPower);
      beforeFormatting.add(map1);
    }
    Map<String, List<PowerStationStatusData>> afterFormatting = beforeFormatting.stream().flatMap(m -> m.entrySet().stream()).collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
    Map<String, List<PowerStationStatusData>> result = new LinkedHashMap<>();
    // 对map按照key升序排列，如果降序在comparingByKey()后面加上.reversed()
    afterFormatting.entrySet().stream()
      .sorted(Map.Entry.<String, List<PowerStationStatusData>>comparingByKey()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));

    // 遍历日期分组map
    for (Map.Entry<String, List<PowerStationStatusData>> entry : result.entrySet()) {
      Map returnMap = new HashMap();
      // 日期
      returnMap.put("time", entry.getKey());

      List<PowerStationStatusData> tempRealPowerList = entry.getValue();
      // 对日期分组list获取最大记录
      PowerStationStatusData maxRealPowerObj = tempRealPowerList.stream().max(Comparator.comparing(PowerStationStatusData::getRealValue)).get();
      // 实际功率最大值对应时刻
      returnMap.put("realPowerTime", DateFormatUtils.format(maxRealPowerObj.getTime(), "yyyy-MM-dd HH:mm:ss"));
      // 实际功率最大值
      returnMap.put("realPowerMax", maxRealPowerObj.getRealValue());
      // 查询最大功率时刻对应的测风塔70米风速瞬时值
      List<WindTowerStatusData> windTowerStatusDatas = windTowerStatusDataRepository.findByEquipmentNoAndTimeBetween(no, maxRealPowerObj.getTime(), maxRealPowerObj.getTime());
      if (windTowerStatusDatas.size() > 0) {
        WindTowerStatusData anemometerTowerRmData = windTowerStatusDatas.get(0);
        returnMap.put("wsSs70Val", anemometerTowerRmData.getWsInst70());
      } else {
        returnMap.put("wsSs70Val", "");
      }

      returnList.add(returnMap);
    }

    return returnList;
  }


}
