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.data.constant.enums.PredictionModelEnum;
import com.jiayue.ipfcst.common.data.entity.*;
import com.jiayue.ipfcst.common.data.repository.*;
import com.jiayue.ipfcst.fileupload.service.BaseUploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 人工干预数据逻辑类
 *
 * @author whc
 * @version 2.0
 * @since 2020/08/24 16:53
 */
@Service
@Slf4j
public class ManualInterventionService extends BaseUploadFileService {

    private final ManualInterventionDataRepository manualInterventionDataRepository;
    private final ManualInterventionLogRepository manualInterventionLogRepository;
    private final ForecastPowerShortTermHisRepository forecastPowerShortTermHisRepository;
    private final ForecastPowerShortTermRepository forecastPowerShortTermRepository;
    private final ElectricFieldService electricFieldService;
private final ForecastPowerUltraShortTermRepository forecastPowerUltraShortTermRepository;
    public ManualInterventionService(ManualInterventionDataRepository manualInterventionDataRepository, ManualInterventionLogRepository manualInterventionLogRepository, ForecastPowerShortTermHisRepository forecastPowerShortTermHisRepository, ForecastPowerShortTermRepository forecastPowerShortTermRepository, ElectricFieldService electricFieldService,ForecastPowerUltraShortTermRepository forecastPowerUltraShortTermRepository) {
        this.manualInterventionDataRepository = manualInterventionDataRepository;
        this.manualInterventionLogRepository = manualInterventionLogRepository;
      this.forecastPowerShortTermHisRepository = forecastPowerShortTermHisRepository;
      this.forecastPowerShortTermRepository = forecastPowerShortTermRepository;
      this.electricFieldService = electricFieldService;
      this.forecastPowerUltraShortTermRepository=forecastPowerUltraShortTermRepository;
    }

    /**
     * 根据开始结束时间和文件类型查询人工干预数据
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param fileType 文件类型
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public List<ManualInterventionData> queryManualIntervention(Long startTime, Long endTime, String fileType){
        List<ManualInterventionData> manualInterventionDataList = new ArrayList<>();
        if(fileType.equals("0")||fileType == "0"){
            manualInterventionDataList = manualInterventionDataRepository.findByInterveneTimeBetweenAndInterveneType(startTime,endTime,"0");
        }else {
            manualInterventionDataList = manualInterventionDataRepository.findByInterveneTimeBetweenAndInterveneType(startTime,endTime,"1");
        }
        manualInterventionDataList.sort(Comparator.comparing(ManualInterventionData::getInterveneTime));

        return manualInterventionDataList;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean saveManualIntervention(List<Map<String,String>> list){
        Map<String,String> map1 = new HashMap<>();
        try{
            List<ManualInterventionData> lists =queryManualIntervention(Long.parseLong(list.get(0).get("lastModifyTime")),Long.parseLong(list.get(0).get("lastModifyTime"))+60*60*24*1000 -1000,list.get(0).get("fileType"));
            manualInterventionDataRepository.deleteByInterveneTimeBetweenAndInterveneType(Long.parseLong(list.get(0).get("lastModifyTime")),Long.parseLong(list.get(0).get("lastModifyTime"))+60*60*24*1000 -1000,list.get(0).get("fileType"));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date systemDate = new Date();
            List<ManualInterventionData> manualInterventionDataList = new ArrayList<>();
            for(int i = 0 ;i< list.size() ;i++){
                map1 = list.get(i);
                if(!map1.get("data1").equals("") || map1.get("data1") != ""){
                    ManualInterventionData manualInterventionData = new ManualInterventionData();
                    String strDate = map1.get("time1");
                    Date date =simpleDateFormat.parse(strDate);
                    manualInterventionData.setInterveneData(new BigDecimal(map1.get("data1")));
                    manualInterventionData.setInterveneTime(date.getTime());
                    manualInterventionData.setInterveneType(list.get(0).get("fileType"));
                    manualInterventionDataList.add(manualInterventionData);
                }
                /*if(!map1.get("data2").equals("") || map1.get("data2") != ""){
                    ManualInterventionData manualInterventionData = new ManualInterventionData();
                    String strDate = map1.get("time2");
                    Date date =simpleDateFormat.parse(strDate);
                    manualInterventionData.setInterveneData(new BigDecimal(map1.get("data2")));
                    manualInterventionData.setInterveneTime(date.getTime());
                    manualInterventionData.setInterveneType(list.get(0).get("fileType"));
                    manualInterventionDataList.add(manualInterventionData);
                }*/
        /*        if(!map1.get("data3").equals("") || map1.get("data3") != ""){
                    ManualInterventionData manualInterventionData = new ManualInterventionData();
                    String strDate = map1.get("time3");
                    Date date =simpleDateFormat.parse(strDate);
                    manualInterventionData.setInterveneData(new BigDecimal(map1.get("data3")));
                    manualInterventionData.setInterveneTime(date.getTime());
                    manualInterventionData.setInterveneType(list.get(0).get("fileType"));
                    manualInterventionDataList.add(manualInterventionData);
                }*/
                /*if(!map1.get("data4").equals("") || map1.get("data4") != ""){
                    ManualInterventionData manualInterventionData = new ManualInterventionData();
                    String strDate = map1.get("time4");
                    Date date =simpleDateFormat.parse(strDate);
                    manualInterventionData.setInterveneData(new BigDecimal(map1.get("data4")));
                    manualInterventionData.setInterveneTime(date.getTime());
                    manualInterventionData.setInterveneType(list.get(0).get("fileType"));
                    manualInterventionDataList.add(manualInterventionData);
                }*/
              manualInterventionDataRepository.saveAll(manualInterventionDataList);
            }
            List<ManualInterventionData> listss =queryManualIntervention(Long.parseLong(list.get(0).get("lastModifyTime")),Long.parseLong(list.get(0).get("lastModifyTime"))+60*60*24*1000 -1000,list.get(0).get("fileType"));
            ManualInterventionLog manualInterventionLog = new ManualInterventionLog();
            List<String> strings = new ArrayList<>();
            String a;
            String b;
            String c;
            String d = new String();
            listss.sort(Comparator.comparing(ManualInterventionData::getInterveneTime));
            if(lists.size() > 0&&listss.size() > 0){
                //保存前有数据 保存后有数据 修改
                for(int i = 0; i < listss.size(); i++){
                    a = simpleDateFormat.format(listss.get(i).getInterveneTime());
                    b = listss.get(i).getInterveneData().toString();
                    if(listss.get(i).getInterveneType().equals("0") || listss.get(i).getInterveneType() == "0"){
                        c = "短期";
                    }else{
                        c = "超短期";
                    }
                    d= d + a+" "+b +" "+ c+System.getProperty("line.separator");
                }
                manualInterventionLog.setFileType(list.get(0).get("fileType"));
                manualInterventionLog.setOperationalTime(systemDate.getTime());
                manualInterventionLog.setOperationalContext(d);
                manualInterventionLog.setOperationalStatus(1);
                manualInterventionLog.setInterveneTime(Long.parseLong(list.get(0).get("lastModifyTime")));
                manualInterventionLogRepository.save(manualInterventionLog);
            }
            if(lists.size()==0&&listss.size() > 0){
                //保存前没数据 保存后有数据  新增
                for(int i = 0; i < listss.size(); i++){
                    a = simpleDateFormat.format(listss.get(i).getInterveneTime());
                    b = listss.get(i).getInterveneData().toString();
                    if(listss.get(i).getInterveneType().equals("0") || listss.get(i).getInterveneType() == "0"){
                        c = "短期";
                    }else{
                        c = "超短期";
                    }
                    d=d+a+" "+b +" "+ c+System.getProperty("line.separator");
                }
                manualInterventionLog.setFileType(list.get(0).get("fileType"));
                manualInterventionLog.setOperationalTime(systemDate.getTime());
                manualInterventionLog.setOperationalContext(d);
                manualInterventionLog.setOperationalStatus(0);
                manualInterventionLog.setInterveneTime(Long.parseLong(list.get(0).get("lastModifyTime")));
                manualInterventionLogRepository.save(manualInterventionLog);
            }
            if(lists.size()>0&&listss.size() == 0){
                //保存前有数据 保存后没数据  删除
                manualInterventionLog.setFileType(list.get(0).get("fileType"));
                manualInterventionLog.setOperationalTime(systemDate.getTime());
                manualInterventionLog.setOperationalContext("");
                manualInterventionLog.setOperationalStatus(2);
                manualInterventionLog.setInterveneTime(Long.parseLong(list.get(0).get("lastModifyTime")));
                manualInterventionLogRepository.save(manualInterventionLog);
            }

        }catch (Exception e){
            e.getStackTrace();
            return false;
        }
        return true;
    }
  /**
   * 更新首页短期
   * @return
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public Boolean refreshSt(){
    Boolean b = false;
    List<ForecastPowerShortTermHis> fpList = new ArrayList<>();
    ForecastPowerShortTermHis fpsth;
    Date nowDate = new Date();
    Long startTime = DateMomentUtil.getDayStartTime(nowDate.getTime());
    Long endTime = DateMomentUtil.getDayLastTime(nowDate.getTime());

    List<ForecastPowerShortTerm> forecastPowerShortTermList = forecastPowerShortTermRepository.findByForecastTimeBetween(startTime, endTime);
    // 查询场站信息
    ElectricField electricFieldInfo = electricFieldService.get();
    // 查询预测时间点对应的开机容量
    Map<Long, BigDecimal> openCapacityMap = null;
    try {
      openCapacityMap = super.queryOpenCapacity(startTime, endTime, electricFieldInfo.getCapacity());
    } catch (BusinessException e) {
      log.error("更新短期数据获取开机容量出错：" + CommonUtil.printStackTraceToString(e));
    }
    if(forecastPowerShortTermList.size()!=96){
      b=false;
    }else{
      for(ForecastPowerShortTerm f : forecastPowerShortTermList){
        fpsth = new ForecastPowerShortTermHis();
        fpsth.setForecastTime(f.getForecastTime());
        fpsth.setPredictionModelEnum(PredictionModelEnum.E8);
        fpsth.setGenDate(nowDate);
        fpsth.setTheoryValue(f.getFpValue());
        fpsth.setAbleValue(f.getFpValue());
        fpsth.setSuCapacity(openCapacityMap.get(f.getForecastTime()));
        fpsth.setForecastHowLongAgo(1);
        fpsth.setCapacity(electricFieldInfo.getCapacity());
        fpList.add(fpsth);
      }
      fpList.sort(Comparator.comparing(ForecastPowerShortTermHis::getForecastTime));
      forecastPowerShortTermHisRepository.deleteByForecastTimeBetweenAndForecastHowLongAgo(startTime,endTime,1);
      forecastPowerShortTermHisRepository.saveAll(fpList);
      b=true;
    }
    return b;
  }

  /**
   * 根据条件查询升级版（tl）
   * 用于人工干预曲线拖拽
   * 曲线查询
   *
   * @param startTime 开始时间
   * @param endTime   结束时间
   * @return map
   */
  @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
  public List<List<Object>> getForecastPowerShortTermForDrawing(Long startTime, Long endTime, String fileType) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    List<List<Object>> lists = new ArrayList<>();
    //判断要查询是的是短期还是超短期
    if (fileType.equals("0")) {
      makeForecastPowerShortTerm(startTime, endTime, simpleDateFormat, lists);
    } else {
      makeForecastPowerUltraShortTerm(startTime, endTime, simpleDateFormat, lists);
    }
    System.out.println("可拖拽的数据"+lists);
    return lists;
  }

  private void makeForecastPowerShortTerm(Long startTime, Long endTime, SimpleDateFormat simpleDateFormat, List<List<Object>> lists) {
    List<ForecastPowerShortTerm> forecastPowerShortTermList = forecastPowerShortTermRepository.findByForecastTimeBetween(startTime, endTime);
    for (long i = startTime; i < endTime; i = i + 900000L) {
      List<Object> list = new ArrayList<>();
      long finalI = i;
      list.add(simpleDateFormat.format(new Date(finalI)));
      List<ForecastPowerShortTerm> p = forecastPowerShortTermList.stream().filter(t -> t.getForecastTime() == finalI).collect(Collectors.toList());
      if (p != null && p.size() > 0) {
        list.add(p.get(0).getFpValue().floatValue());
      } else {
        list.add("");
      }
      lists.add(list);
    }
  }

  private void makeForecastPowerUltraShortTerm(Long startTime, Long endTime, SimpleDateFormat simpleDateFormat, List<List<Object>> lists) {
    List<ForecastPowerUltraShortTerm> forecastPowerUltraShortTermList = forecastPowerUltraShortTermRepository.findByForecastTimeBetween(startTime, endTime);
    for (long i = startTime; i < endTime; i = i + 900000L) {
      List<Object> list = new ArrayList<>();
      long finalI = i;
      list.add(simpleDateFormat.format(new Date(finalI)));
      List<ForecastPowerUltraShortTerm> p = forecastPowerUltraShortTermList.stream().filter(t -> t.getForecastTime() == finalI).collect(Collectors.toList());
      if (p != null && p.size() > 0) {
        list.add(p.get(0).getFpValue().floatValue());
      } else {
        list.add("");
      }
      lists.add(list);
    }
  }


}
