package com.yeejoin.amos.boot.module.ymt.api.common;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils {

    public static Date calculateEndOfYear(Date currentDate) {
        LocalDateTime localDateTime = toLocalDateTime(currentDate);
        LocalDateTime endOfYear = localDateTime.with(LocalDateTime.of(localDateTime.getYear(), 12, 31, 23, 59, 59, 999999999));
        return toDate(endOfYear);
    }

    public static Date calculateEndOfMonth(Date currentDate) {
        LocalDateTime localDateTime = toLocalDateTime(currentDate);
        // 获取当前月份的实际天数（考虑闰年）
        int lastDay = localDateTime.getMonth().length(localDateTime.toLocalDate().isLeapYear());
        // 直接设置为本月最后一天 23:59:59.999
        LocalDateTime endOfMonth = localDateTime
                .withDayOfMonth(lastDay)
                .withHour(23)
                .withMinute(59)
                .withSecond(59)
                .withNano(999_999_999);
        return toDate(endOfMonth);
    }

    public static Date calculateEndOfDay(Date currentDate) {
        LocalDateTime localDateTime = toLocalDateTime(currentDate);
        LocalDateTime endOfDay = localDateTime.with(LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MAX));
        return toDate(endOfDay);
    }

    private static LocalDateTime toLocalDateTime(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    private static Date toDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
}
