package com.jiayue.ipfcst.console.service;

import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.core.util.CommonUtil;
import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
import com.jiayue.ipfcst.common.core.util.DateTimeUtil;
import com.jiayue.ipfcst.common.core.util.NumberUtils;
import com.jiayue.ipfcst.common.data.constant.enums.ElectricFieldTypeEnum;
import com.jiayue.ipfcst.common.data.constant.enums.PredictionModelEnum;
import com.jiayue.ipfcst.common.data.entity.*;
import com.jiayue.ipfcst.common.data.repository.DataLimitationRepository;
import com.jiayue.ipfcst.common.data.repository.ForecastPowerShortTermHisRepository;
import com.jiayue.ipfcst.common.data.repository.ForecastPowerShortTermRepository;
import com.jiayue.ipfcst.common.data.service.BaseService;
import com.jiayue.ipfcst.console.util.Constant;
import com.sun.istack.internal.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Slf4j
public class ForecastPowerShortTermService extends BaseService {

  @Autowired
  ForecastPowerShortTermRepository forecastPowerShortTermRepository;
  @Autowired
  ForecastPowerShortTermHisRepository forecastPowerShortTermHisRepository;
  @Autowired
  ElectricFieldService electricFieldService;
  @Autowired
  ManualInterventionService manualInterventionService;
  @Autowired
  DataLimitationRepository dataLimitationRepository;
  @Autowired
  ManualInterventionRatioService manualInterventionRatioService;


  /**
   * 保存
   *
   * @param forecastPowerShortTermList
   * @return
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public void saveAll(List<ForecastPowerShortTerm> forecastPowerShortTermList) {
    forecastPowerShortTermRepository.saveAll(forecastPowerShortTermList);
  }

  /**
   * 按时间段删除数据
   *
   * @param startTime
   * @param endTime
   * @param listDq
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public void deleteBetweenAndGenTime(Long startTime, Long endTime, List<ForecastPowerShortTerm> listDq) {
    forecastPowerShortTermRepository.deleteByForecastTimeBetween(startTime, endTime);
    //保存短期数据
    forecastPowerShortTermRepository.saveAll(listDq);
  }

  /**
   * 生成短期预测功率,短期预测功率为云下载数据，这里不进行覆盖更新，只针对短期预测数据不足时补充
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public void buildForecastPowerShortTerm(@NotNull final Long startTime, @NotNull final Long endTime) {
    this.getForecastPowerShortTerm(startTime, endTime);
  }

  /**
   * 获取短期预测功率，当数据库中短期预测记录不足查询所需时，进行本地化计算, 用于上报专用
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return 预测功率结果集
   */
  @SuppressWarnings("WeakerAccess")
  @Transactional(propagation = Propagation.REQUIRED)
  public List<ForecastPowerShortTermHis> getForecastPowerShortTerm(@NotNull final Long startTime,
                                                                   @NotNull final Long endTime) {
    List<ForecastPowerShortTermHis> forecastPowerShortTermHiss = getForecastPowerShortTermHis(startTime, endTime);
    // 删除当日生成的短期历史记录
    this.forecastPowerShortTermHisRepository.deleteToday(forecastPowerShortTermHiss.get(0).getForecastTime(),
      forecastPowerShortTermHiss.get(forecastPowerShortTermHiss.size() - 1).getForecastTime());
    // 保存短期历史记录
    this.forecastPowerShortTermHisRepository.saveAll(forecastPowerShortTermHiss);
    return forecastPowerShortTermHiss;
  }


  //
  public List<ForecastPowerShortTermHis> getForecastPowerShortTermHis(@NotNull final Long startTime, @NotNull final Long endTime) {
    log.info("开始获取短期预测功率" + DateFormatUtils.format(startTime, "yyyy-MM-dd HH:mm:ss") + " 至 " + DateFormatUtils.format(endTime, "yyyy-MM-dd HH:mm:ss"));

    // 查询场站信息
    ElectricField electricFieldInfo = electricFieldService.get();
    electricFieldInfo.setElectricFieldTypeEnum(ElectricFieldTypeEnum.E1);
    electricFieldInfo.setCapacity(new BigDecimal(electricFieldInfo.getBackupE()));
    // 查询预测时间点对应的开机容量
    Map<Long, BigDecimal> openCapacityMap = null;
    try {
      openCapacityMap = super.queryOpenCapacity(startTime, endTime, electricFieldInfo.getCapacity());
    } catch (BusinessException e) {
      log.error("预测数据生成获取开机容量出错：" + CommonUtil.printStackTraceToString(e));
    }
    // 查询短期预测功率
    List<ForecastPowerShortTerm> forecastPowerShortTerms =
      this.forecastPowerShortTermRepository.findByForecastTimeBetween(startTime, endTime);
    forecastPowerShortTerms.sort(Comparator.comparing(ForecastPowerShortTerm::getForecastTime));
    log.info("查询现有短期预测记录数:" + forecastPowerShortTerms.size());
    // 判断查询结果是否满足查询所需
    Long momentTime = 15 * 60 * 1000L; // 15分钟一个时刻
    Integer moments = Math.toIntExact((endTime - startTime) / momentTime + 1);
    log.info("获取所需记录数:" + moments);
    if (moments > forecastPowerShortTerms.size()) {
      Map<Long, List<ForecastPowerShortTerm>> forecastPowerShortTermsMap =
        forecastPowerShortTerms.stream().collect(Collectors.groupingBy(ForecastPowerShortTerm::getForecastTime));
      // 如果查询结果少于所需预测数，则进行本地化计算，补齐预测记录
      List<ForecastPowerShortTerm> addForecastPowerShortTermList = new ArrayList<>();
      for (Long tempTime = startTime; tempTime <= endTime; tempTime = tempTime + momentTime) {
        if (forecastPowerShortTermsMap.get(tempTime) == null) {
          // 缺失时间点
          ForecastPowerShortTerm _forecastPowerShortTerms = this.generateForecastPowerShortTerm(tempTime,
            electricFieldInfo, openCapacityMap.get(tempTime));
          addForecastPowerShortTermList.add(_forecastPowerShortTerms);
        }
      }

      if (!addForecastPowerShortTermList.isEmpty()) {
        // 保存短期预测
        this.forecastPowerShortTermRepository.saveAll(addForecastPowerShortTermList);
        // 将补齐的预测功率追加到查询预测功率结果集中
        forecastPowerShortTerms.addAll(addForecastPowerShortTermList);
      }
    }
    forecastPowerShortTerms.sort(Comparator.comparing(ForecastPowerShortTerm::getForecastTime));
    //-----------------------------------------------------开始预测数据上下限的判断----------------------------------------------------
    List<DataLimitation> dataLimitationList = dataLimitationRepository.findByLimitTimeBetween(startTime, endTime);
    dataLimitationList.sort(Comparator.comparing(DataLimitation::getLimitTime));
    Map<Long, Map> limitMap = new HashMap<>();
    int limitFlag = 0;
    if (dataLimitationList.size() > 0) {
      for (DataLimitation dataLimitation : dataLimitationList) {
        Map<String, BigDecimal> limitValMap = new HashMap<>();
        limitValMap.put("max", dataLimitation.getUpperLimit());
        limitValMap.put("min", dataLimitation.getLowerLimit());
        limitMap.put(dataLimitation.getLimitTime(), limitValMap);
      }

      for (Long tempDateTime = startTime; tempDateTime < endTime; tempDateTime = tempDateTime + 15 * 60 * 1000) {
        Map map = limitMap.get(tempDateTime);
        if (map != null) {
          BigDecimal maxBig = (BigDecimal) map.get("max");
          BigDecimal minBig = (BigDecimal) map.get("min");
          BigDecimal fps = forecastPowerShortTerms.get(limitFlag).getFpValue();
          if (maxBig!=null){
            if (fps.compareTo(maxBig) == 1) {
              // 预测值大于设置的上限，用上限值替换
              ForecastPowerShortTerm forecastPowerShortTerm = new ForecastPowerShortTerm();
              forecastPowerShortTerm.setFpValue(maxBig);
              forecastPowerShortTerm.setPredictionModelEnum(PredictionModelEnum.E7);
              forecastPowerShortTerm.setForecastTime(forecastPowerShortTerms.get(limitFlag).getForecastTime());
              forecastPowerShortTerms.set(limitFlag, forecastPowerShortTerm);
            }
          }
          if (minBig!=null){
            if (fps.compareTo(minBig) == -1) {
              // 预测值小于设置的下限，用下限值替换
              ForecastPowerShortTerm forecastPowerShortTerm = new ForecastPowerShortTerm();
              forecastPowerShortTerm.setFpValue(minBig);
              forecastPowerShortTerm.setPredictionModelEnum(PredictionModelEnum.E7);
              forecastPowerShortTerm.setForecastTime(forecastPowerShortTerms.get(limitFlag).getForecastTime());
              forecastPowerShortTerms.set(limitFlag, forecastPowerShortTerm);
            }
          }
        }
        limitFlag++;
      }
    }
    //-----------------------------------------------------结束预测数据上下限的判断----------------------------------------------------

    //-----------------------------------------------------开始进行人工干预数值的判断----------------------------------------------------

    List<ManualInterventionData> manualInterventionDataList = manualInterventionService.queryManualIntervention(startTime, endTime, "0");
    manualInterventionDataList.sort(Comparator.comparing(ManualInterventionData::getInterveneTime));
    Map<Long, BigDecimal> mMap = new HashMap<>();
    int flag = 0;
    if (manualInterventionDataList.size() > 0) {
      for (ManualInterventionData manualInterventionData : manualInterventionDataList) {
        mMap.put(manualInterventionData.getInterveneTime(), manualInterventionData.getInterveneData());
      }
      for (Long tempDateTime = startTime; tempDateTime < endTime; tempDateTime = tempDateTime + 15 * 60 * 1000) {
        ForecastPowerShortTerm forecastPowerShortTerm = new ForecastPowerShortTerm();
        BigDecimal ma = mMap.get(tempDateTime);
        if (ma != null) {
          forecastPowerShortTerm.setFpValue(ma);
          forecastPowerShortTerm.setPredictionModelEnum(PredictionModelEnum.E6);
          // 如果有人工设置的数据 则改点替换为人工设置的数据
          forecastPowerShortTerm.setForecastTime(forecastPowerShortTerms.get(flag).getForecastTime());
          forecastPowerShortTerms.set(flag, forecastPowerShortTerm);
        }
        flag++;
      }
    }

    //-----------------------------------------------------人工干预数据判断结束----------------------------------------------------

    // 处理短期历史记录
    List<ForecastPowerShortTermHis> forecastPowerShortTermHiss = new ArrayList<>();
    ForecastPowerShortTermHis forecastPowerShortTermHis;
    Long systemTime = System.currentTimeMillis();

    //获取数据下限参数
    String lowerPredictionLimit = super.getSysParameter("LowerPredictionLimit", "0");
    BigDecimal lpl = new BigDecimal(lowerPredictionLimit);
    for (ForecastPowerShortTerm _forecastPowerShortTerm : forecastPowerShortTerms) {
      forecastPowerShortTermHis = new ForecastPowerShortTermHis();
      forecastPowerShortTermHis.setForecastTime(_forecastPowerShortTerm.getForecastTime());
      forecastPowerShortTermHis.setTheoryValue(_forecastPowerShortTerm.getFpValue());
      forecastPowerShortTermHis.setCapacity(electricFieldInfo.getCapacity());
      // 预测可用功率=预测*（开机容量/装机容量）
      BigDecimal ableValue =
        _forecastPowerShortTerm.getFpValue().multiply(openCapacityMap.get(_forecastPowerShortTerm.getForecastTime()))
          .divide(electricFieldInfo.getCapacity(), 2, BigDecimal.ROUND_HALF_UP);

      forecastPowerShortTermHis.setAbleValue(ableValue.compareTo(lpl) == -1?lpl:ableValue);
      forecastPowerShortTermHis.setPredictionModelEnum(_forecastPowerShortTerm.getPredictionModelEnum());
      forecastPowerShortTermHis.setGenDate(new Date());
      forecastPowerShortTermHis.setSuCapacity(openCapacityMap.get(_forecastPowerShortTerm.getForecastTime()));
      // 设置提前几天预测
      forecastPowerShortTermHis.setForecastHowLongAgo(DateMomentUtil.getDaysBetweenTwoDate(systemTime,
        forecastPowerShortTermHis.getForecastTime()));
      forecastPowerShortTermHiss.add(forecastPowerShortTermHis);
    }
    //-----------------------------------------------------系数判断开始----------------------------------------------------
    List<ManualInterventionRatioData> manualInterventionRatioDataList = manualInterventionRatioService.queryManualInterventionRatio(startTime, endTime, "0");

    //如果有人工干预系数设置记录
    if(manualInterventionRatioDataList.size() > 0){
      //循环所有记录
      for(ManualInterventionRatioData manualInterventionRatioData :manualInterventionRatioDataList){
        for (Long tempTime = manualInterventionRatioData.getInterveneStartTime(); tempTime <= manualInterventionRatioData.getInterveneEndTime(); tempTime = tempTime + 15 * 60 * 1000L) {
          //循环所有超短期的值
          int mrflag = 0;
          for (ForecastPowerShortTermHis f : forecastPowerShortTermHiss) {
            //如果该时间设置了系数则数值*系数
            if(f.getForecastTime().equals(tempTime)){
              BigDecimal fpValue = f.getAbleValue().multiply(new BigDecimal(manualInterventionRatioData.getRatio().toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
              //如果计算后的数据大于装机容量 则fpValue=装机容量
              if((fpValue).compareTo(new BigDecimal(electricFieldInfo.getCapacity().toString())) > 0){
                fpValue = new BigDecimal(electricFieldInfo.getCapacity().toString());
              }
              f.setAbleValue(fpValue);
              f.setTheoryValue(fpValue);
              f.setGenDate(new Date());
              f.setPredictionModelEnum(PredictionModelEnum.E10);
              forecastPowerShortTermHiss.set(mrflag, f);

            }
            mrflag++;
          }
        }
      }
    }
    //-----------------------------------------------------系数判断结束----------------------------------------------------

    //-----------------------------------------------------浙江光伏负偏差---------------------------------------------------
    try {
      String negative_deviation = super.getSysParameter("negative_deviation", "0");
      if (electricFieldInfo.getProvinceEnum().toString().equals("E33")&&electricFieldInfo.getElectricFieldTypeEnum().toString().equals("E1")&&!negative_deviation.equals("0")&&!negative_deviation.equals("")){
        int mrflag = 0;
        for (ForecastPowerShortTermHis f : forecastPowerShortTermHiss) {
          f.setAbleValue(f.getAbleValue().subtract(new BigDecimal(negative_deviation)));
          f.setTheoryValue(f.getTheoryValue().subtract(new BigDecimal(negative_deviation)));
          f.setGenDate(new Date());
          f.setPredictionModelEnum(PredictionModelEnum.E10);
          forecastPowerShortTermHiss.set(mrflag, f);
          mrflag++;
        }
      }
    }catch (Exception e){
      e.printStackTrace();
      log.info("负偏差计算错误，请检查negative_deviation参数是否为数字");
    }

    //-----------------------------------------------------浙江光伏负偏差---------------------------------------------------

    //-----------------------------------------------------系数判断结束----------------------------------------------------

    // 按预测时间升序
    forecastPowerShortTermHiss.sort(Comparator.comparing(ForecastPowerShortTermHis::getForecastTime));
    return forecastPowerShortTermHiss;
  }


  /**
   * 获取一体化短期预测功率，当数据库中短期预测记录不足查询所需时，进行本地化计算, 用于上报专用
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return 预测功率结果集
   */
  @SuppressWarnings("WeakerAccess")
  @Transactional(propagation = Propagation.REQUIRED)
  public List<ForecastPowerShortTermHis> getInForecastPowerShortTerm(@NotNull final Long startTime,
                                                                   @NotNull final Long endTime) {
    log.info("开始获取短期预测功率" + DateFormatUtils.format(startTime, "yyyy-MM-dd HH:mm:ss") + " 至 " + DateFormatUtils.format(endTime, "yyyy-MM-dd HH:mm:ss"));
    // 查询场站信息
    ElectricField electricFieldInfo = electricFieldService.get();
    electricFieldInfo.setElectricFieldTypeEnum(ElectricFieldTypeEnum.E1);
    electricFieldInfo.setCapacity(new BigDecimal(electricFieldInfo.getBackupE()));
    // 查询预测时间点对应的开机容量
    Map<Long, BigDecimal> openCapacityMap = null;
    try {
      openCapacityMap = super.queryOpenCapacity(startTime, endTime, electricFieldInfo.getCapacity());
    } catch (BusinessException e) {
      log.error("预测数据生成获取开机容量出错：" + CommonUtil.printStackTraceToString(e));
    }
    // 查询短期预测功率
    List<ForecastPowerShortTerm> forecastPowerShortTerms =
      this.forecastPowerShortTermRepository.findByForecastTimeBetween(startTime, endTime);
    forecastPowerShortTerms.sort(Comparator.comparing(ForecastPowerShortTerm::getForecastTime));
    log.info("查询现有短期预测记录数:" + forecastPowerShortTerms.size());
    // 判断查询结果是否满足查询所需
    Long momentTime = 15 * 60 * 1000L; // 15分钟一个时刻
    Integer moments = Math.toIntExact((endTime - startTime) / momentTime + 1);
    log.info("获取所需记录数:" + moments);
    if (moments > forecastPowerShortTerms.size()) {
      Map<Long, List<ForecastPowerShortTerm>> forecastPowerShortTermsMap =
        forecastPowerShortTerms.stream().collect(Collectors.groupingBy(ForecastPowerShortTerm::getForecastTime));
      // 如果查询结果少于所需预测数，则进行本地化计算，补齐预测记录
      List<ForecastPowerShortTerm> addForecastPowerShortTermList = new ArrayList<>();
      for (Long tempTime = startTime; tempTime <= endTime; tempTime = tempTime + momentTime) {
        if (forecastPowerShortTermsMap.get(tempTime) == null) {
          // 缺失时间点
          ForecastPowerShortTerm _forecastPowerShortTerms = this.generateForecastPowerShortTerm(tempTime,
            electricFieldInfo, openCapacityMap.get(tempTime));
          addForecastPowerShortTermList.add(_forecastPowerShortTerms);
        }
      }

      if (!addForecastPowerShortTermList.isEmpty()) {
        // 保存短期预测
        this.forecastPowerShortTermRepository.saveAll(addForecastPowerShortTermList);
        // 将补齐的预测功率追加到查询预测功率结果集中
        forecastPowerShortTerms.addAll(addForecastPowerShortTermList);
      }
    }
    forecastPowerShortTerms.sort(Comparator.comparing(ForecastPowerShortTerm::getForecastTime));

    // 处理短期历史记录
    List<ForecastPowerShortTermHis> forecastPowerShortTermHiss = new ArrayList<>();
    ForecastPowerShortTermHis forecastPowerShortTermHis;
    Long systemTime = System.currentTimeMillis();


    for (ForecastPowerShortTerm _forecastPowerShortTerm : forecastPowerShortTerms) {
      forecastPowerShortTermHis = new ForecastPowerShortTermHis();
      forecastPowerShortTermHis.setForecastTime(_forecastPowerShortTerm.getForecastTime());
      forecastPowerShortTermHis.setTheoryValue(_forecastPowerShortTerm.getFpValue());
      forecastPowerShortTermHis.setCapacity(electricFieldInfo.getCapacity());
      // 预测可用功率=预测*（开机容量/装机容量）
      BigDecimal ableValue =
        _forecastPowerShortTerm.getFpValue().multiply(openCapacityMap.get(_forecastPowerShortTerm.getForecastTime()))
          .divide(electricFieldInfo.getCapacity(), 2, BigDecimal.ROUND_HALF_UP);

      forecastPowerShortTermHis.setAbleValue(ableValue);
      forecastPowerShortTermHis.setPredictionModelEnum(_forecastPowerShortTerm.getPredictionModelEnum());
      forecastPowerShortTermHis.setGenDate(new Date());
      forecastPowerShortTermHis.setSuCapacity(openCapacityMap.get(_forecastPowerShortTerm.getForecastTime()));
      // 设置提前几天预测
      forecastPowerShortTermHis.setForecastHowLongAgo(DateMomentUtil.getDaysBetweenTwoDate(systemTime,
        forecastPowerShortTermHis.getForecastTime()));
      forecastPowerShortTermHiss.add(forecastPowerShortTermHis);
    }

    // 按预测时间升序
    forecastPowerShortTermHiss.sort(Comparator.comparing(ForecastPowerShortTermHis::getForecastTime));

    return forecastPowerShortTermHiss;
  }

  @Transactional(propagation = Propagation.REQUIRED)
  public void inSaveHis(List<ForecastPowerShortTermHis> forecastPowerShortTermHiss) {

    // 删除当日生成的短期历史记录
    this.forecastPowerShortTermHisRepository.deleteToday(forecastPowerShortTermHiss.get(0).getForecastTime(),
      forecastPowerShortTermHiss.get(forecastPowerShortTermHiss.size() - 1).getForecastTime());
    // 保存短期历史记录
    this.forecastPowerShortTermHisRepository.saveAll(forecastPowerShortTermHiss);
  }

  /**
   * 补数生成单点短期预测功率
   *
   * @param tempTime 预测时间
   * @return 预测功率
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public ForecastPowerShortTerm generateForecastPowerShortTerm(@NotNull final Long tempTime,
                                                               ElectricField electricFieldInfo,
                                                               BigDecimal openCapacity) {
    ForecastPowerShortTerm forecastPowerShortTerms;
    // 根据场站类型调用不同的短期预测模型
    if (ElectricFieldTypeEnum.E2.equals(electricFieldInfo.getElectricFieldTypeEnum())) {
      // 风预测
      forecastPowerShortTerms = this.generateWindPowerShortTerm(tempTime, openCapacity);
    } else {
      // 光预测
      forecastPowerShortTerms = this.generateSolarPowerShortTerm(tempTime, openCapacity, electricFieldInfo);
    }
    return forecastPowerShortTerms;
  }

  /**
   * 光短期功率预测
   *
   * @param tempTime 预测时间
   * @return 短期预测功率
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public ForecastPowerShortTerm generateSolarPowerShortTerm(@NotNull final Long tempTime, BigDecimal openCapacity,
                                                            ElectricField electricFieldInfo) {
    ForecastPowerShortTerm forecastPowerShortTerm = new ForecastPowerShortTerm();
    forecastPowerShortTerm.setForecastTime(tempTime);
    BigDecimal tempValue;
    BigDecimal randomValue = new BigDecimal(CommonUtil.getRandom(97, 99) / 100.0);
    if (DateTimeUtil.checkInSunriseAndSunset(tempTime, electricFieldInfo.getLongitude().doubleValue(),
      electricFieldInfo.getLatitude().doubleValue())) {
      // 2021-4-22 xsl修改补数取固定系数
      String a = Constant.forecastCoe(tempTime,electricFieldInfo.getElectricFieldTypeEnum());
      System.out.println(a);
      tempValue = new BigDecimal(a);
    } else {
      // 日升日落
      tempValue = BigDecimal.ZERO;
    }

    forecastPowerShortTerm.setFpValue(NumberUtils.multiply(tempValue, openCapacity).multiply(randomValue).setScale(2, BigDecimal.ROUND_HALF_UP));
    forecastPowerShortTerm.setGenDate(new Date());
    forecastPowerShortTerm.setPredictionModelEnum(PredictionModelEnum.E4);
    return forecastPowerShortTerm;
  }


  /**
   * 风短期功率预测
   *
   * @param tempTime 预测时间
   * @return 短期预测功率
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public ForecastPowerShortTerm generateWindPowerShortTerm(@NotNull final Long tempTime, BigDecimal openCapacity) {
    ForecastPowerShortTerm forecastPowerShortTerm = new ForecastPowerShortTerm();
    forecastPowerShortTerm.setForecastTime(tempTime);
    BigDecimal randomValue = new BigDecimal(CommonUtil.getRandom(97, 99) / 100.0d);
    // 2021-4-22 xsl修改补数取固定系数
    BigDecimal tempValue = new BigDecimal(Constant.forecastCoe(tempTime,ElectricFieldTypeEnum.E2));
    forecastPowerShortTerm.setFpValue(NumberUtils.multiply(tempValue, openCapacity).multiply(randomValue).setScale(2, BigDecimal.ROUND_HALF_UP));
    forecastPowerShortTerm.setGenDate(new Date());
    forecastPowerShortTerm.setPredictionModelEnum(PredictionModelEnum.E4);
    return forecastPowerShortTerm;
  }

  /**
   * 根据条件查询
   *
   * @param startTimeStr 开始时间
   * @param endTimeStr   结束时间
   * @return map
   */
  @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
  public Map<String, Object> getForecastPowerShortTermDrawing(String startTimeStr, String endTimeStr) {
    Map<String, Object> map = new HashMap<>();
    Long startTime = 0L;
    Long endTime = 0L;
    if (StringUtils.isNotEmpty(startTimeStr)) {
      startTime = Long.parseLong(startTimeStr);
    } else {
      Calendar c = Calendar.getInstance();

      startTime = c.getTimeInMillis() - DateUtils.getFragmentInMilliseconds(c, Calendar.DAY_OF_MONTH) + 24 * 60 * 60 * 1000;
    }
    if (StringUtils.isNotEmpty(endTimeStr)) {
      endTime = Long.parseLong(endTimeStr);
    } else {
      Calendar c = Calendar.getInstance();

      endTime = c.getTimeInMillis() - DateUtils.getFragmentInMilliseconds(c, Calendar.DAY_OF_MONTH) + 4 * 24 * 60 * 60 * 1000;
    }



    map.put("list", forecastPowerShortTermRepository.findByForecastTimeBetween(startTime, endTime));// 结果集

    return map;
  }
  /**
   * 查询回传数据
   * @param stTime         开始时间
   * @param eTime          结束时间
   * @return
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public String[] findSendData(Long stTime,Long eTime,List<ForecastPowerShortTerm> list){

    List<ForecastPowerShortTerm> collect = list.stream().filter(s -> s.getForecastTime() >= stTime && s.getForecastTime() <= eTime).collect(Collectors.toList());
    String[] datas = new String[list.size()];
    if(null != collect && collect.size() > 0){
      int index = 0;
      for(ForecastPowerShortTerm f:collect){
        datas[index] = String.valueOf(f.getFpValue());
        index++;
      }
    }
    return datas;
  }
}
