package com.jiayue.ipfcst.console.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONObject;
import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.data.entity.*;
import com.jiayue.ipfcst.common.data.repository.*;
import com.jiayue.ipfcst.common.data.service.BaseService;
import com.jiayue.ipfcst.console.util.GzipUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 实际功率环境数据二维码
 *
 *
 * @Author tl
 * @CreateTime 2021/8/30 9:11
 */
@Service
public class QREnvironmentDataService extends BaseService {
  //  @Autowired
//  private
  /*
   *  获取实际功率数据
   *  获取环境数据
   *  将两数据拼装返回
   *
   */
  private final static String IMAGE_TYPE = "jpg";

  private final PowerStationStatusDataRepository powerStationStatusDataRepository;

  private final WeatherStationStatusDataRepository weatherStationStatusDataRepository;
  private final WindTowerStatusDataRepository windTowerStatusDataRepository;
  private final FileAnalysisRecordRepository fileAnalysisRecordRepository;

  private final ForecastPowerUltraShortTermHisRepository forecastPowerUltraShortTermHisRepository;
  private final WindTurbineInfoRepository windTurbineInfoRepository;
  private final WindTowerInfoService windTowerInfoService;
  private final WindTurbineStatusDataRepository windTurbineStatusDataRepository;
  @Autowired
  public QREnvironmentDataService(PowerStationStatusDataRepository powerStationStatusDataRepository,
                                  WeatherStationStatusDataRepository weatherStationStatusDataRepository,
                                  WindTowerStatusDataRepository windTowerStatusDataRepository,
                                  FileAnalysisRecordRepository fileAnalysisRecordRepository,
                                  ForecastPowerUltraShortTermHisRepository forecastPowerUltraShortTermHisRepository, WindTurbineInfoRepository windTurbineInfoRepository, WindTowerInfoService windTowerInfoService, WindTurbineStatusDataRepository windTurbineStatusDataRepository) {
    this.powerStationStatusDataRepository = powerStationStatusDataRepository;
    this.weatherStationStatusDataRepository = weatherStationStatusDataRepository;
    this.windTowerStatusDataRepository = windTowerStatusDataRepository;
    this.fileAnalysisRecordRepository = fileAnalysisRecordRepository;
    this.forecastPowerUltraShortTermHisRepository = forecastPowerUltraShortTermHisRepository;
    this.windTurbineInfoRepository = windTurbineInfoRepository;
    this.windTowerInfoService = windTowerInfoService;
    this.windTurbineStatusDataRepository = windTurbineStatusDataRepository;
  }

  /**
   * 首页实际功率二维码生成
   *
   * @param response 二维码回写流
   * @throws IOException io异常
   */
  public void generateRealPowerCode(HttpServletResponse response, Long startTime, Long endTime) throws IOException, BusinessException {

    ElectricField electricField = this.getElectricField();
    long timeStep = 900000L;
    String contents = "";
    //----------------------------环境数据-----------------------------------
    if(electricField.getElectricFieldTypeEnum().getCode() == 1){
      //光场站
      // 0无意义 1是设备ID 0是总辐射
      String sys = super.getSysParameter("EN_QR_CODE","0,1,0");
      String[] sysData = sys.split(",");
      List<WeatherStationStatusData> wlist = weatherStationStatusDataRepository.findByTimeBetweenAndEquipmentNo(new Date(startTime), new Date(endTime), Integer.parseInt(sysData[1]));
      List<WeatherStationStatusData> collect = wlist.stream().filter(w -> w.getIsGenerated().equals(false)).collect(Collectors.toList());
      //总辐射
      if(sysData[2].equals("0")){
        for (long stepTime = startTime; stepTime <= endTime; stepTime = stepTime + timeStep) {
          long finalTime = stepTime;
          List<WeatherStationStatusData> wFilter = collect.stream().filter(p -> p.getTime().getTime() == finalTime).collect(Collectors.toList());
          if (wFilter != null && wFilter.size() > 0) {
            contents = contents + wFilter.get(0).getGlobalR().toString()+ "|";
          } else {
            contents = contents + "-0.99|";
          }
        }
      }
      //倾斜辐射
      if(sysData[2].equals("1")){
        for (long stepTime = startTime; stepTime <= endTime; stepTime = stepTime + timeStep) {
          long finalTime = stepTime;
          List<WeatherStationStatusData> wFilter = collect.stream().filter(p -> p.getTime().getTime() == finalTime).collect(Collectors.toList());
          if (wFilter != null && wFilter.size() > 0) {
            contents = contents + wFilter.get(0).getObliqueR().toString()+ "|";
          } else {
            contents = contents + "-0.99|";
          }
        }
      }
    }else {
      //风场站
      // 0为测风塔 1是设备ID 70是70米风速
      String sys = super.getSysParameter("EN_QR_CODE","0,1,70");
      String[] sysData = sys.split(",");
      if(sysData[0].equals("0")){
        //测风塔
        List<WindTowerStatusData> wlist = windTowerStatusDataRepository.findByEquipmentNoAndTimeBetween(Integer.parseInt(sysData[1]), new Date(startTime), new Date(endTime));
        List<WindTowerStatusData> collect = wlist.stream().filter(w -> w.getIsGenerated().equals(false)).collect(Collectors.toList());
        for (long stepTime = startTime; stepTime <= endTime; stepTime = stepTime + timeStep) {
          long finalTime = stepTime;
          List<WindTowerStatusData> wFilter = collect.stream().filter(p -> p.getTime().getTime() == finalTime).collect(Collectors.toList());
          if (wFilter != null && wFilter.size() > 0) {
            try{
              switch (sysData[2]){
                case "10":
                  contents = contents + wFilter.get(0).getWsInst10().toString() + "|";
                  break;
                case "30":
                  contents = contents + wFilter.get(0).getWsInst30().toString() + "|";
                  break;
                case "50":
                  contents = contents + wFilter.get(0).getWsInst50().toString() + "|";
                  break;
                case "60":
                  contents = contents + wFilter.get(0).getWsInst60().toString() + "|";
                  break;
                case "70":
                  contents = contents + wFilter.get(0).getWsInst70().toString() + "|";
                  break;
                case "80":
                  contents = contents + wFilter.get(0).getWsInst80().toString() + "|";
                  break;
                case "90":
                  contents = contents + wFilter.get(0).getWsInst90().toString() + "|";
                  break;
                case "100":
                  contents = contents + wFilter.get(0).getWsInst100().toString() + "|";
                  break;
                case "110":
                  contents = contents + wFilter.get(0).getWsInst110().toString() + "|";
                  break;
                case "120":
                  contents = contents + wFilter.get(0).getWsInst120().toString() + "|";
                  break;
                default:
                  contents = contents + "-0.99|";
                  break;
              }
            }catch (Exception e){
              contents = contents + "-0.99|";
            }
          } else {
            contents = contents + "-0.99|";
          }
        }
      }else if(sysData[0].equals("1")){
        //风机样板机
        List<WindTurbineInfo> windTurbineInfoList = windTurbineInfoRepository.findAllByOrderByIdAsc();
        List<WindTurbineInfo> collect = windTurbineInfoList.stream().filter(w -> w.getSample().equals(true)).collect(Collectors.toList());

        for (long stepTime = startTime; stepTime <= endTime; stepTime = stepTime + timeStep) {
          long finalTime = stepTime;
          BigDecimal countWs = new BigDecimal(0);
          try{
            for(int i = 0; i< collect.size() ; i++){
              List<WindTurbineStatusData> wlist = windTurbineStatusDataRepository.findByTimeBetweenAndEquipmentNo( new Date(startTime), new Date(endTime),collect.get(i).getId());
              List<WindTurbineStatusData> wFilter = wlist.stream().filter(p -> p.getTime().getTime() == finalTime).collect(Collectors.toList());
              if(wFilter != null && wFilter.size() > 0){
                countWs = countWs.add(wFilter.get(0).getWs());
              }else{
                countWs = countWs.add(new BigDecimal(0));
              }
            }
            contents = contents + countWs.divide(BigDecimal.valueOf(collect.size()),2,BigDecimal.ROUND_HALF_UP).toString() + "|";
          }catch (Exception e){
            contents = contents + "-0.99|";
          }
        }
      }else{
        //全场风机风速
        List<WindTurbineInfo> windTurbineInfoList = windTurbineInfoRepository.findAllByOrderByIdAsc();
        for (long stepTime = startTime; stepTime <= endTime; stepTime = stepTime + timeStep) {
          long finalTime = stepTime;
          BigDecimal countWs = new BigDecimal(0);
          try{
            for(int i = 0; i< windTurbineInfoList.size() ; i++){
              List<WindTurbineStatusData> wlist = windTurbineStatusDataRepository.findByTimeBetweenAndEquipmentNo( new Date(startTime), new Date(endTime),windTurbineInfoList.get(i).getId());
              List<WindTurbineStatusData> wFilter = wlist.stream().filter(p -> p.getTime().getTime() == finalTime).collect(Collectors.toList());
              if(wFilter != null && wFilter.size() > 0){
                countWs = countWs.add(wFilter.get(0).getWs());
              } else{
                countWs = countWs.add(new BigDecimal(0));
              }
            }
            contents = contents + countWs.divide(BigDecimal.valueOf(windTurbineInfoList.size()),2,BigDecimal.ROUND_HALF_UP).toString() + "|";
          }catch (Exception e){
            contents = contents + "-0.99|";
          }
        }
      }
    }
    //----------------------------实际功率-----------------------------------
    String content = electricField.getStationCode() + "|" + startTime + "|rp|";

    List<PowerStationStatusData> pList = powerStationStatusDataRepository.findByTimeBetween(new Date(startTime), new Date(endTime));
    for (long stepTime = startTime; stepTime <= endTime; stepTime = stepTime + timeStep) {
      long finalTime = stepTime;
      List<PowerStationStatusData> pFilter = pList.stream().filter(p -> p.getTime().getTime() == finalTime).collect(Collectors.toList());
      if (pFilter != null && pFilter.size() > 0) {
        content = content + pFilter.get(0).getRealValue().setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "|";
      } else {
        content = content + "-0.99|";
      }
    }

    String zipContent = GzipUtil.zip(content+contents).replace("\r\n", "");

    String taskNo = getTaskNo(electricField);

    JSONObject jsonObject = new JSONObject();
    jsonObject.putOnce("taskNo", taskNo);
    jsonObject.putOnce("taskType", "stationData-rp");
    jsonObject.putOnce("partNo", 1);
    jsonObject.putOnce("partTotal", 1);
    jsonObject.putOnce("data", zipContent);

    String qrCodeContent = jsonObject.toString();

    QrConfig config = this.getQrConfig(500, 500, Color.black, Color.white);

    ServletOutputStream out = response.getOutputStream();

    QrCodeUtil.generate(qrCodeContent, config, IMAGE_TYPE, out);
  }



  /**
   * 获取taskNo编号
   *
   * @param electricField 场站对象
   * @return 编号
   */
  private String getTaskNo(ElectricField electricField) {
    Date date = DateUtil.date();
    return electricField.getStationCode() + DateUtil.format(date, "yyMMddHHmmss");
  }


  /**
   * 二维码生成配置
   *
   * @param width  宽度
   * @param height 高度
   * @param c      二维码颜色
   * @param bc     二维码背景颜色
   * @return
   */
  public QrConfig getQrConfig(int width, int height, Color c, Color bc) {
    QrConfig config = new QrConfig(width, height);
    // 设置边距，既二维码和背景之间的边距
    config.setMargin(1);
    // 设置前景色，既二维码颜色（青色）
    config.setForeColor(c);
    // 设置背景色（灰色）
    config.setBackColor(bc);
    return config;
  }
}
