package com.usky.vpp.util;

import com.usky.vpp.enums.ElectricSeasonEnum;
import com.usky.vpp.enums.ElectricUserTypeEnum;
import com.usky.vpp.enums.TimeSegmentEnum;

import java.time.LocalDateTime;

/**
 * 分时电价工具：根据时间、用户类型判断当前属于哪个时段
 */
public final class ElectricTimeUtil {

    private ElectricTimeUtil() {
    }

    public static TimeSegmentEnum getCurrentSegment(LocalDateTime dateTime, ElectricUserTypeEnum userType) {
        int month = dateTime.getMonthValue();
        int hour = dateTime.getHour();
        ElectricSeasonEnum season = ElectricSeasonEnum.getByMonth(month);

        if (ElectricUserTypeEnum.SINGLE_PART == userType) {
            return hour >= 6 && hour < 22 ? TimeSegmentEnum.PEAK : TimeSegmentEnum.VALLEY;
        }

        if (isSpikeHour(hour, season)) {
            return TimeSegmentEnum.SPIKE;
        }
        if (isPeakHour(hour, season)) {
            return TimeSegmentEnum.PEAK;
        }
        if (isFlatHour(hour, season)) {
            return TimeSegmentEnum.FLAT;
        }
        return TimeSegmentEnum.VALLEY;
    }

    private static boolean isSpikeHour(int hour, ElectricSeasonEnum season) {
        if (ElectricSeasonEnum.SUMMER == season) {
            return hour >= 12 && hour < 14;
        }
        if (ElectricSeasonEnum.WINTER_SPIKE == season) {
            return hour >= 19 && hour < 21;
        }
        return false;
    }

    private static boolean isPeakHour(int hour, ElectricSeasonEnum season) {
        if (ElectricSeasonEnum.SUMMER == season) {
            return (hour >= 8 && hour < 15) || (hour >= 18 && hour < 21);
        }
        return (hour >= 8 && hour < 11) || (hour >= 18 && hour < 21);
    }

    private static boolean isFlatHour(int hour, ElectricSeasonEnum season) {
        if (ElectricSeasonEnum.SUMMER == season) {
            return (hour >= 6 && hour < 8) || (hour >= 15 && hour < 18) || (hour >= 21 && hour < 22);
        }
        return (hour >= 6 && hour < 8) || (hour >= 11 && hour < 18) || (hour >= 21 && hour < 22);
    }

    public static boolean isValleyHour(int hour) {
        return hour >= 22 || hour < 6;
    }
}
