package com.gyee.runeconomy.service.WindDirection;


import com.gyee.runeconomy.init.CacheContext;
import com.gyee.runeconomy.model.auto.*;
import com.gyee.runeconomy.service.auto.IStationInfoDayService;
import com.gyee.runeconomy.service.auto.ITurbineInfoDayService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WindMachineService {


    @Resource
    private ITurbineInfoDayService turbineInfoDayService;
    @Resource
    private IStationInfoDayService stationInfoDayService;


    public Object machine(String wpid,int year) throws Exception {
        // 获取当前日期
        int currentYear = LocalDate.now().getYear();
        currentYear = year;

        List<ProBasicEquipment> collect = CacheContext.wtls.stream()
                .filter(wt -> wpid.equals(wt.getWindpowerstationId()))
                .collect(Collectors.toList());

        Map<String, List> monthlyData = new LinkedHashMap<>();


        // 风机循环：每台风机每个月一个 WindData 对象
        for (ProBasicEquipment eq : collect) {

            // 获取当前年份的开始日期（1月1日）
            LocalDate startOfYear = LocalDate.of(currentYear, 1, 1);

            // 获取当前年份的结束日期（12月31日）
            LocalDate endOfYear = LocalDate.of(currentYear, 12, 31);

            // 使用 DateTimeFormatter 格式化日期为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 转换为字符串
            String startOfYearStr = startOfYear.format(formatter);
            String endOfYearStr = endOfYear.format(formatter);

            List<TurbineInfoDay> turbineList = turbineInfoDayService.getTurbineList(eq.getId(), startOfYearStr, endOfYearStr);
            List<StationInfoDay> infoDays = stationInfoDayService.getTurbineList(wpid, startOfYearStr, endOfYearStr);
            List<String> zb = new ArrayList<>();
            zb.add("fsavg");
            zb.add("cftfsavg");
            zb.add("fspc");
            zb.add("fxavg");
            zb.add("cftfxavg");
            zb.add("fxpc");

            for (String z : zb) {
                // 循环从1月到12月
                List<Double> result = new ArrayList<>();
                String zbwz = "";
                for (int month = 1; month <= 12; month++) {
                    // 过滤 turbineList 中的记录，筛选出对应月份的数据
                    int finalMonth = month;
                    List<TurbineInfoDay> filteredList = turbineList.stream()
                            .filter(turbine -> {
                                // 获取 turbineInfoDay 的 recordDate（类型为 LocalDate）
                                Date dateFromTurbine = turbine.getRecordDate();

                                // 将 Date 转换为 LocalDate
                                ZonedDateTime zonedDateTime = dateFromTurbine.toInstant().atZone(ZoneId.systemDefault());
                                LocalDate recordDate = zonedDateTime.toLocalDate();

                                // 获取记录的月份（注意，月份从 1 开始，1 表示1月）
                                int recordMonth = recordDate.getMonthValue();

                                // 判断记录的月份是否等于给定的 time
                                return recordMonth == finalMonth;  // 比较 int 类型的月份和 time 变量
                            })
                            .collect(Collectors.toList());

                    List<StationInfoDay> dayfilteredList = infoDays.stream()
                            .filter(turbine -> {
                                // 获取 turbineInfoDay 的 recordDate（类型为 LocalDate）
                                LocalDate dateFromTurbine = turbine.getRecordDate();

                                // 获取记录的月份（注意，月份从 1 开始，1 表示1月）
                                int recordMonth = dateFromTurbine.getMonthValue();

                                // 判断记录的月份是否等于给定的 time
                                return recordMonth == finalMonth;  // 比较 int 类型的月份和 time 变量
                            })
                            .collect(Collectors.toList());

                    // 风速
                    double fsaverage = filteredList.stream()
                            .mapToDouble(turbineInfoDay -> Optional.ofNullable(turbineInfoDay.getPjfs()).map(Number::doubleValue).orElse(0.0))
                            .average()
                            .orElse(0.0);  // 默认值0.0

                    // 风向
                    double fxaverage = filteredList.stream()
                            .mapToDouble(turbineInfoDay -> Optional.ofNullable(turbineInfoDay.getFx()).map(Number::doubleValue).orElse(0.0))
                            .average()
                            .orElse(0.0);  // 默认值0.0

                    // 测风塔风速
                    double cftfsaverage = dayfilteredList.stream()
                            .mapToDouble(turbineInfoDay -> Optional.ofNullable(turbineInfoDay.getCftfs()).map(Number::doubleValue).orElse(0.0))
                            .average()
                            .orElse(0.0); // 默认值0.0

                    // 测风塔风向
                    double cftfxaverage = dayfilteredList.stream()
                            .mapToDouble(turbineInfoDay -> Optional.ofNullable(turbineInfoDay.getCftfx()).map(Number::doubleValue).orElse(0.0))
                            .average()
                            .orElse(0.0);  // 默认值0.0


                    double zbsj = 0.0;

                    if (z.toString().equals("fsavg")) {
                        // 保留两位小数并转换回 double
                        zbsj = Double.parseDouble(String.format("%.2f", fsaverage));
                        zbwz = "风速";
                    } else if (z.toString().equals("fxavg")) {
                        zbsj = Double.parseDouble(String.format("%.2f", fxaverage));
                        zbwz = "风向";
                    } else if (z.toString().equals("cftfsavg")) {
                        zbsj = Double.parseDouble(String.format("%.2f", cftfsaverage));
                        zbwz = "测风塔风速";
                    } else if (z.toString().equals("cftfxavg")) {
                        zbsj = Double.parseDouble(String.format("%.2f", cftfxaverage));
                        zbwz = "测风塔风向";
                    } else if (z.toString().equals("fspc")) {
                        zbsj = Deviation.calculateSpeedDeviation(
                                fsaverage,
                                cftfsaverage
                        );
                        zbwz = "风速偏差";
                    } else if (z.toString().equals("fxpc")) {
                        zbsj = Deviation.calculateDirectionDeviation(
                                fxaverage,
                                cftfxaverage
                        );
                        zbwz = "风向偏差";
                    }
                    result.add(zbsj);
                }
                monthlyData.put(eq.getAname() + zbwz, result);
            }

        }

        return monthlyData;
    }

    /**
     * 气象单机偏差分析
     * @param wpid
     * @return
     * @throws Exception
     */
    public Object weathermachine(String wpid,int year) throws Exception {
        // 获取当前日期
        int currentYear = LocalDate.now().getYear();
        currentYear= year;

        List<ProBasicEquipment> collect = CacheContext.wtls.stream()
                .filter(wt -> wpid.equals(wt.getWindpowerstationId()))
                .collect(Collectors.toList());

        Map<String, List> monthlyData = new LinkedHashMap<>();


        // 风机循环：每台风机每个月一个 WindData 对象
        for (ProBasicEquipment eq : collect) {

            // 获取当前年份的开始日期（1月1日）
            LocalDate startOfYear = LocalDate.of(currentYear, 1, 1);

            // 获取当前年份的结束日期（12月31日）
            LocalDate endOfYear = LocalDate.of(currentYear, 12, 31);

            // 使用 DateTimeFormatter 格式化日期为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 转换为字符串
            String startOfYearStr = startOfYear.format(formatter);
            String endOfYearStr = endOfYear.format(formatter);

            List<TurbineInfoDay> turbineList = turbineInfoDayService.getTurbineList(eq.getId(), startOfYearStr, endOfYearStr);
            List<StationInfoDay> infoDays = stationInfoDayService.getTurbineList(wpid, startOfYearStr, endOfYearStr);
            List<String> zb = new ArrayList<>();
            zb.add("fsavg");
            zb.add("cftfsavg");
            zb.add("fspc");
            zb.add("fxavg");
            zb.add("cftfxavg");
            zb.add("fxpc");

            for (String z : zb) {
                // 循环从1月到12月
                List<Double> result = new ArrayList<>();
                String zbwz = "";
                for (int month = 1; month <= 12; month++) {
                    // 过滤 turbineList 中的记录，筛选出对应月份的数据
                    int finalMonth = month;
                    List<TurbineInfoDay> filteredList = turbineList.stream()
                            .filter(turbine -> {
                                // 获取 turbineInfoDay 的 recordDate（类型为 LocalDate）
                                Date dateFromTurbine = turbine.getRecordDate();

                                // 将 Date 转换为 LocalDate
                                ZonedDateTime zonedDateTime = dateFromTurbine.toInstant().atZone(ZoneId.systemDefault());
                                LocalDate recordDate = zonedDateTime.toLocalDate();

                                // 获取记录的月份（注意，月份从 1 开始，1 表示1月）
                                int recordMonth = recordDate.getMonthValue();

                                // 判断记录的月份是否等于给定的 time
                                return recordMonth == finalMonth;  // 比较 int 类型的月份和 time 变量
                            })
                            .collect(Collectors.toList());

                    List<StationInfoDay> dayfilteredList = infoDays.stream()
                            .filter(turbine -> {
                                // 获取 turbineInfoDay 的 recordDate（类型为 LocalDate）
                                LocalDate dateFromTurbine = turbine.getRecordDate();

                                // 获取记录的月份（注意，月份从 1 开始，1 表示1月）
                                int recordMonth = dateFromTurbine.getMonthValue();

                                // 判断记录的月份是否等于给定的 time
                                return recordMonth == finalMonth;  // 比较 int 类型的月份和 time 变量
                            })
                            .collect(Collectors.toList());

                    // 风速
                    double fsaverage = filteredList.stream()
                            .mapToDouble(turbineInfoDay -> Optional.ofNullable(turbineInfoDay.getPjfs()).map(Number::doubleValue).orElse(0.0))
                            .average()
                            .orElse(0.0);  // 默认值0.0

                    // 风向
                    double fxaverage = filteredList.stream()
                            .mapToDouble(turbineInfoDay -> Optional.ofNullable(turbineInfoDay.getFx()).map(Number::doubleValue).orElse(0.0))
                            .average()
                            .orElse(0.0);  // 默认值0.0

                    // 测风塔风速
                    double cftfsaverage = dayfilteredList.stream()
                            .mapToDouble(turbineInfoDay -> Optional.ofNullable(turbineInfoDay.getCftfs()).map(Number::doubleValue).orElse(0.0))
                            .average()
                            .orElse(0.0); // 默认值0.0

                    // 测风塔风向
                    double cftfxaverage = dayfilteredList.stream()
                            .mapToDouble(turbineInfoDay -> Optional.ofNullable(turbineInfoDay.getCftfx()).map(Number::doubleValue).orElse(0.0))
                            .average()
                            .orElse(0.0);  // 默认值0.0


                    double zbsj = 0.0;

                    if (z.toString().equals("fsavg")) {
                        // 保留两位小数并转换回 double
                        zbsj = Double.parseDouble(String.format("%.2f", fsaverage));
                        zbwz = "风速";
                    } else if (z.toString().equals("fxavg")) {
                        zbsj = Double.parseDouble(String.format("%.2f", fxaverage));
                        zbwz = "风向";
                    } else if (z.toString().equals("cftfsavg")) {
                        zbsj = Double.parseDouble(String.format("%.2f", cftfsaverage));
                        zbwz = "测风塔风速";
                    } else if (z.toString().equals("cftfxavg")) {
                        zbsj = Double.parseDouble(String.format("%.2f", cftfxaverage));
                        zbwz = "测风塔风向";
                    } else if (z.toString().equals("fspc")) {
                        zbsj = Deviation.calculateSpeedDeviation(
                                fsaverage,
                                cftfsaverage
                        );
                        zbwz = "风速偏差";
                    } else if (z.toString().equals("fxpc")) {
                        zbsj = Deviation.calculateDirectionDeviation(
                                fxaverage,
                                cftfxaverage
                        );
                        zbwz = "风向偏差";
                    }
                    result.add(zbsj);
                }
                monthlyData.put(eq.getAname() + zbwz, result);
            }

        }

        return monthlyData;
    }
}
