package com.usky.ems.enums;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 时间维度枚举：D-日 / M-月 / Y-年
 */
public enum TemporalTypeEnum {

    DAY("D"),
    MONTH("M"),
    YEAR("Y");

    private final String code;

    TemporalTypeEnum(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public static TemporalTypeEnum get(String code) {
        if (code == null) {
            return null;
        }
        for (TemporalTypeEnum e : values()) {
            if (e.code.equalsIgnoreCase(code)) {
                return e;
            }
        }
        return null;
    }

    /**
     * 将开始时间归一化到当前时间维度的起点
     */
    public LocalDateTime normalizeStart(LocalDateTime time) {
        if (time == null) {
            return null;
        }
        LocalDate date = time.toLocalDate();
        switch (this) {
            case DAY:
                return LocalDateTime.of(date, LocalTime.MIN);
            case MONTH:
                LocalDate firstDayOfMonth = date.withDayOfMonth(1);
                return LocalDateTime.of(firstDayOfMonth, LocalTime.MIN);
            case YEAR:
                LocalDate firstDayOfYear = date.withDayOfYear(1);
                return LocalDateTime.of(firstDayOfYear, LocalTime.MIN);
            default:
                return time;
        }
    }

    /**
     * 将结束时间归一化到当前时间维度的结束
     */
    public LocalDateTime normalizeEnd(LocalDateTime time) {
        if (time == null) {
            return null;
        }
        LocalDate date = time.toLocalDate();
        switch (this) {
            case DAY:
                return LocalDateTime.of(date, LocalTime.MAX);
            case MONTH:
                LocalDate lastDayOfMonth = date.withDayOfMonth(date.lengthOfMonth());
                return LocalDateTime.of(lastDayOfMonth, LocalTime.MAX);
            case YEAR:
                LocalDate lastDayOfYear = date.withDayOfYear(date.lengthOfYear());
                return LocalDateTime.of(lastDayOfYear, LocalTime.MAX);
            default:
                return time;
        }
    }
}

