package link.at17.mid.tushare.system.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

public class LocalDateTimeUtils {
    
    /**
     * 将 LocalDateTime 格式化为指定格式的字符串
     * @param date
     * @param format
     * @return
     */
    public static String format(LocalDateTime date, String format) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return formatter.format(date);
    }
    
    /**
     * 获取本年度最后一天的 LocalDate
     * @return
     */
    public static LocalDate getLastDayOfThisYear() {
        LocalDate today = LocalDate.now();
        return today.with(TemporalAdjusters.lastDayOfYear());
    }
    
    /**
     * 判断给定 LocalDate 是否是本年度最后一天
     * @param date
     * @return
     */
    public static boolean isLastDayOfThisYear(LocalDate date) {
        return getLastDayOfThisYear().equals(date);
    }
    
    /**
     * 判断给定 LocalDateTime 是否处于本年度最后一天
     * @param date
     * @return
     */
    public static boolean isLastDayOfThisYear(LocalDateTime date) {
        return getLastDayOfThisYear().equals(date.toLocalDate());
    }
    
    /**
     * 根据常见的日期字符串转换为时间
     * @param input
     * @return
     */
    public static LocalDateTime parseDate(String input) {
        String[] patterns = {
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd HH:mm",
            "yyyy-MM-dd",
            "yyyy/MM/dd",
            "yyyyMMdd"
        };
        for (String p : patterns) {
            try {
                DateTimeFormatter f = DateTimeFormatter.ofPattern(p);
                if (p.contains("H")) {
                    return LocalDateTime.parse(input, f);
                } else {
                    return LocalDate.parse(input, f).atStartOfDay();
                }
            } catch (Exception ignored) {}
        }
        throw new IllegalArgumentException("无法识别的日期格式: " + input);
    }
    
    /**
     * 判断两个 LocalDateTime 是否是同一天
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameDay(LocalDateTime date1, LocalDateTime date2) {
        return date1.toLocalDate().equals(date2.toLocalDate());
    }

    
}
