package com.gyee.generation.task.thread;

import com.gyee.generation.init.CacheContext;
import com.gyee.generation.model.auto.ProBasicEquipment;
import com.gyee.generation.model.auto.ProEconEquipmentInfoDay1;
import com.gyee.generation.model.auto.ProEconWindturbineGoodness;
import com.gyee.generation.model.auto.TurbineInfoMin;
import com.gyee.generation.model.vo.WpType;
import com.gyee.generation.service.CoefficientService;
import com.gyee.generation.service.GoodnessOfFitService;
import com.gyee.generation.service.auto.ITurbineInfoMinService;
import com.gyee.generation.util.DateUtils;
import com.gyee.generation.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;

public class GoodnessOfFitThreadPool implements Callable<String>, Serializable {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final long serialVersionUID = 0;

    // 保存任务所需要的数据

    private Object threadPoolTaskData;
    private int i;
    private Date recordDate;

    private CoefficientService coefficientService;
    private GoodnessOfFitService goodnessOfFitService;

    private Map<String, ProEconEquipmentInfoDay1> equipmentInfoDay1Map;
    private List<ProEconWindturbineGoodness> vos;
    private ITurbineInfoMinService turbineInfoMinService;

    public GoodnessOfFitThreadPool(Object tasks, int i, Date recordDate, CoefficientService coefficientService,
                                   GoodnessOfFitService goodnessOfFitService,ITurbineInfoMinService turbineInfoMinService,
                                   Map<String, ProEconEquipmentInfoDay1> equipmentInfoDay1Map, List<ProEconWindturbineGoodness> vos
    ) {

        this.threadPoolTaskData = tasks;
        this.i = i;
        this.recordDate = recordDate;
        this.coefficientService = coefficientService;
        this.goodnessOfFitService = goodnessOfFitService;
        this.turbineInfoMinService = turbineInfoMinService;
        this.equipmentInfoDay1Map = equipmentInfoDay1Map;
        this.vos = vos;

    }

    public synchronized String call() throws Exception {


        // 处理一个任务，这里的处理方式太简单了，仅仅是一个打印语句

        //System.out.println("开始执行任务：" + threadPoolTaskData);

        String result = "";

        // //便于观察，等待一段时间


        try {

            System.out.println("拟合优度当前风机数" + i);
            ProBasicEquipment wt = CacheContext.wtfdls.get(i);
            Map<String, Map<String, Double>> coefficientMap = new HashMap<>();
            Map<String, Map<String, Double>> fitMap = new HashMap<>();
            try {
                coefficientMap = coefficientService.coefficient(wt.getId(), DateUtils.truncate(recordDate));
                fitMap = goodnessOfFitService.goodnessOfFit(wt.getId(), DateUtils.truncate(recordDate));
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

            Date beginDate = DateUtils.addDays(recordDate, -1);


            Calendar c = Calendar.getInstance();
            c.setTime(beginDate);

            c.set(Calendar.DAY_OF_MONTH, 1);
            Date monthbeginDate = c.getTime();
            c.set(Calendar.MONTH, 0);
            Date yearbeginDate = c.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String beginDateString = sdf.format(beginDate);
            String monthbeginDateString = sdf.format(monthbeginDate);
            String yearbeginDateString = sdf.format(yearbeginDate);

            Date endDate = recordDate;
            String endDateString = sdf.format(endDate);

            ProEconWindturbineGoodness po = new ProEconWindturbineGoodness();
            po.setModelId(wt.getModelId());
            po.setWindturbineId(wt.getId());
            po.setRecordDate(DateUtils.truncate(recordDate));
            po.setWindtpowerstationId(wt.getWindpowerstationId());
            po.setCompanyId(wt.getCompanyId());
            po.setRegionId(wt.getRegionId());
            if (wt.getWindpowerstationId().contains(WpType.FDC.id)) {
                po.setTypes("-1");
            } else {
                po.setTypes("-2");
            }
            po.setDayGoodness(0.0);
            po.setYearGoodness(0.0);
            po.setMonthGoodness(0.0);
            po.setDayCoefficient(0.0);
            po.setMonthCoefficient(0.0);
            po.setYearCoefficient(0.0);
            po.setDaySpeed(0.0);
            po.setMonthSpeed(0.0);
            po.setYearSpeed(0.0);


            double dayfs = 0.0;
            double monthfs = 0.0;
            double yearfs = 0.0;

            List<TurbineInfoMin> infoMinsday = turbineInfoMinService.selectByTurbineId(wt.getId(), beginDateString, endDateString);

            if (infoMinsday.size()>0){
                OptionalDouble optionalAverage = infoMinsday.stream()
                        .map(TurbineInfoMin::getPjfs)
                        .filter(Objects::nonNull) // 过滤掉 null 值
                        .mapToDouble(Double::doubleValue)
                        .average();

                dayfs = optionalAverage.orElse(0.0); // 如果没有值，返回默认值 0.0
            }

            List<TurbineInfoMin> infoMinsmonth = turbineInfoMinService.selectByTurbineId(wt.getId(), monthbeginDateString, endDateString);

            if (infoMinsmonth.size()>0){
                OptionalDouble optionalAverage = infoMinsmonth.stream()
                        .map(TurbineInfoMin::getPjfs)
                        .filter(Objects::nonNull) // 过滤掉 null 值
                        .mapToDouble(Double::doubleValue)
                        .average();

                monthfs = optionalAverage.orElse(0.0); // 如果没有值，返回默认值 0.0
            }
            List<TurbineInfoMin> infoMinsyear = turbineInfoMinService.selectByTurbineId(wt.getId(), yearbeginDateString, endDateString);

            if (infoMinsyear.size()>0){
                OptionalDouble optionalAverage = infoMinsyear.stream()
                        .map(TurbineInfoMin::getPjfs)
                        .filter(Objects::nonNull) // 过滤掉 null 值
                        .mapToDouble(Double::doubleValue)
                        .average();

                yearfs = optionalAverage.orElse(0.0); // 如果没有值，返回默认值 0.0
            }

//            if (equipmentInfoDay1Map.containsKey(wt.getId())) {
//                ProEconEquipmentInfoDay1 ed1 = equipmentInfoDay1Map.get(wt.getId());
//                po.setDaySpeed(ed1.getRpjfs());
//                po.setMonthSpeed(ed1.getYpjfs());
//                po.setYearSpeed(ed1.getNpjfs());
//            } else {
//                po.setDaySpeed(0.0);
//                po.setMonthSpeed(0.0);
//                po.setYearSpeed(0.0);
//            }

            po.setDaySpeed(dayfs);
            po.setMonthSpeed(monthfs);
            po.setYearSpeed(yearfs);

            if (fitMap.containsKey(wt.getId())) {
                Map<String, Double> map = fitMap.get(wt.getId());

                if (map.containsKey("day")) {
                    double temp = map.get("day") * 100;
                    if (temp > 100) {
                        temp = 100;
                    } else if (temp < 0) {
                        temp = 0.0;
                    }

                    po.setDayGoodness(StringUtils.round(temp, 2));
                } else {
                    po.setDayGoodness(0.0);
                }

                if (map.containsKey("month")) {
                    double temp = map.get("month") * 100;
                    if (temp > 100) {
                        temp = 100;
                    } else if (temp < 0) {
                        temp = 0.0;
                    }

                    po.setMonthGoodness(StringUtils.round(temp, 2));
                } else {
                    po.setMonthGoodness(0.0);
                }

                if (map.containsKey("year")) {
                    double temp = map.get("year") * 100;
                    if (temp > 100) {
                        temp = 100;
                    } else if (temp < 0) {
                        temp = 0.0;
                    }

                    po.setYearGoodness(StringUtils.round(temp, 2));
                } else {
                    po.setYearGoodness(0.0);
                }


                //				po.setMonthGoodness(null!=map.get("month")?map.get("month"):0.0);
                //				po.setYearGoodness(null!=map.get("year")?map.get("year"):0.0);
                //
                //				po.setDayGoodness(StringUtils.round(po.getDayGoodness()*100,2));
                //				po.setYearGoodness(StringUtils.round(po.getYearGoodness()*100,2));
                //				po.setMonthGoodness(StringUtils.round(po.getMonthGoodness()*100,2));
            } else {
                po.setDayGoodness(0.0);
                po.setYearGoodness(0.0);
                po.setMonthGoodness(0.0);
            }

            if (coefficientMap.containsKey(wt.getId())) {
                Map<String, Double> map = coefficientMap.get(wt.getId());
                if (map.containsKey("day")) {
                    double temp = map.get("day") * 100;
                    if (temp > 100) {
                        temp = 100;
                    } else if (temp < 0) {
                        temp = 0.0;
                    }

                    po.setDayCoefficient(StringUtils.round(temp, 2));
                } else {
                    po.setDayCoefficient(0.0);
                }

                if (map.containsKey("month")) {
                    double temp = map.get("month") * 100;
                    if (temp > 100) {
                        temp = 100;
                    } else if (temp < 0) {
                        temp = 0.0;
                    }

                    po.setMonthCoefficient(StringUtils.round(temp, 2));
                } else {
                    po.setMonthCoefficient(0.0);
                }

                if (map.containsKey("year")) {
                    double temp = map.get("year") * 100;
                    if (temp > 100) {
                        temp = 100;
                    } else if (temp < 0) {
                        temp = 0.0;
                    }

                    po.setYearCoefficient(StringUtils.round(temp, 2));
                } else {
                    po.setYearCoefficient(0.0);
                }
                //				po.setDayCoefficient(null!=map.get("day")?map.get("day"):0.0);
                //				po.setMonthCoefficient(null!=map.get("month")?map.get("month"):0.0);
                //				po.setYearCoefficient(null!=map.get("year")?map.get("year"):0.0);

            } else {

                po.setDayCoefficient(0.0);
                po.setMonthCoefficient(0.0);
                po.setYearCoefficient(0.0);
            }


            vos.add(po);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        threadPoolTaskData = null;

        return result;

    }


}