package com.jiayue.ipfcst.fileupload.integration.job;

import cn.hutool.core.date.DateUtil;
import com.jiayue.ipfcst.common.core.integration.constant.DataTypeConstant;
import com.jiayue.ipfcst.common.core.integration.constant.StatusConstant;
import com.jiayue.ipfcst.common.core.integration.correct.dq.IForePowerShortTermCorrect;
import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
import com.jiayue.ipfcst.common.data.constant.enums.ElectricFieldTypeEnum;
import com.jiayue.ipfcst.common.data.entity.ElectricField;
import com.jiayue.ipfcst.common.data.entity.ForecastPowerShortTermHis;
import com.jiayue.ipfcst.common.data.entity.Nwp;
import com.jiayue.ipfcst.common.data.entity.integration.InForecastPowerShortTerm;
import com.jiayue.ipfcst.common.data.entity.integration.IntegrationRecord;
import com.jiayue.ipfcst.common.data.repository.IntegrationRecordRepository;
import com.jiayue.ipfcst.console.service.ElectricFieldService;
import com.jiayue.ipfcst.console.service.ForecastPowerShortTermService;
import com.jiayue.ipfcst.console.service.NwpService;
import com.jiayue.ipfcst.fileupload.integration.service.InForecastPowerShortTermService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 上送数据
 * @author: yuanhao
 * @createDate: 2021/8/26
 * @version: 1.0
 */
@Slf4j
public class CorrectDQJob {
  @Autowired
  private IntegrationRecordRepository integrationRecordRepository;
  @Autowired
  private IForePowerShortTermCorrect inForePowerShortTermCorrect;
  @Autowired
  private ForecastPowerShortTermService forecastPowerShortTermService;
  @Autowired
  private InForecastPowerShortTermService inForecastPowerShortTermService;
  @Autowired
  private NwpService nwpService;
  @Autowired
  private ElectricFieldService electricFieldService;


  /*@Scheduled(cron = "10 0/10 3-4 * * ?")
  @Scheduled(cron = "10 0/10 18-19 * * ?")*/
  public void dqUpTasks() {

    if (inForePowerShortTermCorrect.beanType().equals(StatusConstant.BEAN_TYPE_REAL)) {
      long time = DateUtil.parse(DateUtil.today(), "yyyy-MM-dd").getTime();
      String ampm = StatusConstant.AM_DAY;
      boolean am = DateUtil.isAM(new Date());
      if (!am) {
        ampm = StatusConstant.PM_DAY;
      }

      IntegrationRecord irecord = integrationRecordRepository.findByTypeAndTimeAndAmPm(DataTypeConstant.FORE_TYPE, time, ampm);

      if (irecord != null) {

        if (!irecord.getUpStatus().equals(StatusConstant.REQUEST_SUCCESS)) {
          String result = pushData();
          irecord.setUpTime(DateUtil.now());
          irecord.setUpStatus(result);
          integrationRecordRepository.save(irecord);
        }

      } else {

        String result = pushData();
        IntegrationRecord record = new IntegrationRecord();
        record.setType(DataTypeConstant.FORE_TYPE);
        record.setAmPm(ampm);
        record.setTime(time);
        record.setUpTime(DateUtil.now());
        record.setUpStatus(result);
        integrationRecordRepository.save(record);
      }

    } else {
      log.info("没有一体化短期实现");
    }

  }

  private String pushData() {
    Date systemDate = new Date();
    // 开始时间
    Long startTime = DateMomentUtil.getDayStartTime(DateUtils.addDays(systemDate, 0).getTime());
    // 结束时间（开始加24小时再减去1秒）
    Long endTime = DateMomentUtil.getDayLastTime(DateUtils.addDays(systemDate, 9).getTime()) + 1L;
    // 查询短期预测功率
    List<ForecastPowerShortTermHis> forecastPowerShortTermHisList = this.forecastPowerShortTermService.getInForecastPowerShortTerm(startTime, endTime);
    // 按照预测时间进行升序
    if (forecastPowerShortTermHisList.size() > 0) {
      forecastPowerShortTermHisList.sort(Comparator.comparing(ForecastPowerShortTermHis::getForecastTime));
    }

    List<Nwp> nwpDataList = nwpService.getNwpData(startTime, endTime);
    if (nwpDataList.size() > 0) {
      nwpDataList.sort(Comparator.comparing(Nwp::getPreTime));
    }
    String esign = "";
    Integer elType = ElectricFieldTypeEnum.E1.getCode();
    try {
      ElectricField electricField = electricFieldService.getElectricField();
      Integer code = electricField.getElectricFieldTypeEnum().getCode();
      if (code == ElectricFieldTypeEnum.E2.getCode()) {
        elType = ElectricFieldTypeEnum.E2.getCode();
      }
      esign = electricField.getSign();
    } catch (Exception e) {
      e.printStackTrace();
    }

    String result = inForePowerShortTermCorrect.pushData(esign, elType, forecastPowerShortTermHisList, nwpDataList, startTime, endTime);

    //如果上送数据成功就保存到历史表中的数据
    if (result.equals(StatusConstant.REQUEST_SUCCESS)) {
      // 保存
      this.forecastPowerShortTermService.inSaveHis(forecastPowerShortTermHisList);
    }

    return result;
  }

  /*@Scheduled(cron = "10 0/10 5-6 * * ?")
  @Scheduled(cron = "10 0/10 20-21 * * ?")*/
  public void dqGetTasks() {
    if (inForePowerShortTermCorrect != null) {

      long time = DateUtil.parse(DateUtil.today(), "yyyy-MM-dd").getTime();
      String ampm = StatusConstant.AM_DAY;
      boolean am = DateUtil.isAM(new Date());
      if (!am) {
        ampm = StatusConstant.PM_DAY;
      }

      IntegrationRecord irecord = integrationRecordRepository.findByTypeAndTimeAndAmPm(DataTypeConstant.FORE_TYPE, time, ampm);
      if (irecord != null) {
        //如果上送数据成功
        if (irecord.getUpStatus().equals(StatusConstant.REQUEST_SUCCESS)) {
          //如果下载修正状态为null
          if (irecord.getCorrectStatus() == null) {
            getData(irecord);
          } else {
            //如果下载修正状态不为成功
            if (!irecord.getCorrectStatus().equals(StatusConstant.REQUEST_SUCCESS)) {
              getData(irecord);
            }
          }
        } else {
          //上送短期待修正数据
          /*this.dqUpTasks();*/
          log.error("一体化短期请求修正数据失败:未查询到上送数据成功记录");
        }

      } else {
        //上送短期待修正数据
        /*this.dqUpTasks();*/
        log.error("一体化短期请求修正数据失败:未查询到上送数据成功记录");
      }

    } else {
      log.info("没有一体化短期实现");
    }

  }

  public void getData(IntegrationRecord irecord) {
    Integer code = ElectricFieldTypeEnum.E1.getCode();
    try {
      ElectricField electricField = electricFieldService.getElectricField();
      if (electricField.getElectricFieldTypeEnum().getCode() == ElectricFieldTypeEnum.E2.getCode()) {
        code = ElectricFieldTypeEnum.E2.getCode();
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    Map<String, Object> correctData = inForePowerShortTermCorrect.getCorrectData(code);
    boolean result = (boolean) correctData.get("result");
    String status = (String) correctData.get("status");
    List<InForecastPowerShortTerm> data = (List<InForecastPowerShortTerm>) correctData.get("data");
    irecord.setCorrectTime(DateUtil.now());
    if (result) {
      if (data.size() > 0) {
        data.sort(Comparator.comparing(InForecastPowerShortTerm::getForecastTime));
        inForecastPowerShortTermService.deleteBetweenAndPreTime(data.get(0).getForecastTime(), data.get(data.size() - 1).getForecastTime(), data);
        irecord.setCorrectStatus(status);
      }
    }
    integrationRecordRepository.save(irecord);
  }


}
