package com.gyee.frame.schdule.windturbinestatetime;

import com.gyee.frame.common.feign.RemoteServiceBuilder;
import com.gyee.frame.model.auto.WindTurbineTestingPointAi2;
import com.gyee.frame.model.auto.WindTurbineTestingPointAi2Example;
import com.gyee.frame.model.config.FilePathConfig;
import com.gyee.frame.model.custom.export.TsPointData;
import com.gyee.frame.service.WindTurbineTestingPointAiService;
import com.gyee.frame.service.export.LoadrateHourlyService;
import com.gyee.frame.util.DateUtils;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 光伏负荷率、利用小时计算
 */
@Component
public class TaskLoadrateHourlyStatistics {

    @Resource
    private WindTurbineTestingPointAiService windTurbineTestingPointAiService;
    @Resource
    private RemoteServiceBuilder remoteServiceBuilder;
    @Resource
    private LoadrateHourlyService loadrateHourlyService;

    private String powerTags;
    private String electricityTags;
    private List<WindTurbineTestingPointAi2> ai2ForPower;
    private List<WindTurbineTestingPointAi2> ai2ForElectricity;
    //场站、风机、标签点
    Map<String, List<String>> powerCollect;
    Map<String, List<String>> electricityCollect;

    //利用小时计算
    private void creatExcel(XSSFWorkbook sheets) {
        getPowerTags();
        getElectricityTags();
        Calendar instance = Calendar.getInstance();
        //Map<String,TsPointData> powerPoint = remoteServiceBuilder.ShardingService().getHistorySection(powerTags, instance.getTimeInMillis());
        Map<String,TsPointData> electricityPoint = remoteServiceBuilder.ShardingService().getHistorySection(electricityTags, instance.getTimeInMillis());
        //getPowerCollect();
        getElectricityCollect();
        Map<Integer, String> ptMap = loadrateHourlyService.getPtMap();
        int i2 = sheets.getNumberOfSheets();
        for (int i = 0; i <i2; i++) {
            XSSFSheet sheetAt = sheets.getSheetAt(i);
            for (int i1 = 0; i1 < sheetAt.getLastRowNum()-1; i1++) {
                sheetAt.getRow(i1+2).getCell(4).setCellValue(DateUtils.format(instance.getTime(),"yyyy-MM-dd HH:mm:ss"));
                //sheetAt.getRow(i1+2).getCell(5).setCellValue(powerPoint.get(powerCollect.get(ptMap.get(i)).get(i1)).getDoubleValue());
                sheetAt.getRow(i1+2).getCell(5).setCellValue(electricityPoint.get(electricityCollect.get(ptMap.get(i)).get(i1)).getDoubleValue());
            }
        }
        FormulaEvaluator evaluator = new XSSFFormulaEvaluator(sheets);
        evaluator.evaluateAll();
        //通过输出流将workbook对象下载到磁盘
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(FilePathConfig.getDataPath()+"\\光伏逆变器负荷率利用小时计算\\"+DateUtils.format(new Date(),"yyyyMMdd")+"2200.xlsx");
            sheets.write(out);
            out.flush();
            out.close();
            //sheets.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //负荷率计算
    private void creatExcel(String t) {
        XSSFWorkbook sheets = readExceltemplate();
        getPowerTags();
        getElectricityTags();
        Calendar instance = Calendar.getInstance();
        Map<String,TsPointData> powerPoint = remoteServiceBuilder.ShardingService().getHistorySection(powerTags, instance.getTimeInMillis());
        getPowerCollect();
        Map<Integer, String> ptMap = loadrateHourlyService.getPtMap();
        int i2 = sheets.getNumberOfSheets();
        for (int i = 0; i <i2; i++) {
            XSSFSheet sheetAt = sheets.getSheetAt(i);
            for (int i1 = 0; i1 < sheetAt.getLastRowNum()-1; i1++) {
                sheetAt.getRow(i1+2).getCell(4).setCellValue(DateUtils.format(instance.getTime(),"yyyy-MM-dd HH:mm:ss"));
                sheetAt.getRow(i1+2).getCell(5).setCellValue(powerPoint.get(powerCollect.get(ptMap.get(i)).get(i1)).getDoubleValue());
            }
        }
        FormulaEvaluator evaluator = new XSSFFormulaEvaluator(sheets);
        evaluator.evaluateAll();
        //通过输出流将workbook对象下载到磁盘
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(FilePathConfig.getDataPath()+"\\光伏逆变器负荷率利用小时计算\\"+DateUtils.format(new Date(),"yyyyMMdd")+t+".xlsx");
            sheets.write(out);
            out.flush();
            out.close();
            //sheets.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 9点半
     */
    @Scheduled(cron = "0 30 9 * * ?")
    public void getLoadrateHourly930(){
        creatExcel("0930");
    }

    /**
     * 12点半
     */
    @Scheduled(cron = "0 30 12 * * ?")
    public void getLoadrateHourly1230(){
        creatExcel("1230");
    }

    /**
     * 18点半
     */
    @Scheduled(cron = "0 0 16 * * ?")
    public void getLoadrateHourly1830(){
        creatExcel("1830");
    }

    /**
     * 22点
     */
    @Scheduled(cron = "0 0 20 * * ?")
    public void getLoadrateHourly2200(){
        String path = FilePathConfig.getFilePath()+"\\template\\公司光伏逆变器利用小时计算模板.xlsx";
        XSSFWorkbook sheets = readExceltemplate(path);
        creatExcel(sheets);
    }

    private XSSFWorkbook readExceltemplate(String path){
        //在内存中创建一个Excel文件
        XSSFWorkbook sheets = null;
        try {
            sheets = new XSSFWorkbook(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sheets;
    }

    private XSSFWorkbook readExceltemplate(){
        String path = FilePathConfig.getFilePath()+"\\template\\公司光伏逆变器负荷率计算模板.xlsx";
        return readExceltemplate(path);
    }

    public String getPowerTags() {
        if(powerTags==null){
            getAi2ForPower();
            powerTags = ai2ForPower.stream().map(wttpai2 -> wttpai2.getId()).collect(Collectors.joining(","));
        }
        return powerTags;
    }

    public String getElectricityTags() {
        if(electricityTags==null){
            getAi2ForElectricity();
            electricityTags = ai2ForElectricity.stream().map(wttpai2 -> wttpai2.getId()).collect(Collectors.joining(","));
        }
        return electricityTags;
    }

    public List<WindTurbineTestingPointAi2> getAi2ForPower() {
        if(ai2ForPower==null){
            WindTurbineTestingPointAi2Example example = new WindTurbineTestingPointAi2Example();
            example.createCriteria().andUniformcodeEqualTo("AI130").andWindpowerstationidLike("%GDC");
            ai2ForPower = windTurbineTestingPointAiService.selectByExample(example);
        }
        return ai2ForPower;
    }

    public List<WindTurbineTestingPointAi2> getAi2ForElectricity() {
        if(ai2ForElectricity==null){
            WindTurbineTestingPointAi2Example example = new WindTurbineTestingPointAi2Example();
            example.createCriteria().andUniformcodeEqualTo("RFDL").andWindpowerstationidLike("%GDC");
            ai2ForElectricity = windTurbineTestingPointAiService.selectByExample(example);
        }
        return ai2ForElectricity;
    }

    public Map<String, List<String>> getPowerCollect() {
        if(powerCollect==null){
            powerCollect = ai2ForPower.stream().sorted((ai1,ai2)->{
                return Integer.parseInt(ai1.getWindturbineid().substring(ai1.getWindturbineid().indexOf("_")+1))
                        - Integer.parseInt(ai2.getWindturbineid().substring(ai2.getWindturbineid().indexOf("_")+1));
            }).collect(Collectors.groupingBy(WindTurbineTestingPointAi2::getWindpowerstationid,Collectors.mapping(WindTurbineTestingPointAi2::getId,Collectors.toList())));
        }
        return powerCollect;
    }

    public Map<String, List<String>> getElectricityCollect() {
        if(electricityCollect==null){
            electricityCollect = ai2ForElectricity.stream().sorted((ai1,ai2)->{
                return Integer.parseInt(ai1.getWindturbineid().substring(ai1.getWindturbineid().indexOf("_")+1))
                        - Integer.parseInt(ai2.getWindturbineid().substring(ai2.getWindturbineid().indexOf("_")+1));
            }).collect(Collectors.groupingBy(WindTurbineTestingPointAi2::getWindpowerstationid,Collectors.mapping(WindTurbineTestingPointAi2::getId,Collectors.toList())));
        }
        return electricityCollect;
    }
}
