package quant.rich.emoney.util;

import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class DateUtils {

    // 缓存 formatter，行为接近 fastjson2
    private static final Map<String, DateTimeFormatter> FORMATTER_CACHE =
            new ConcurrentHashMap<>();

    private DateUtils() {
    }

    /**
     * 格式化 LocalDateTime
     *
     * @param dateTime LocalDateTime
     * @param pattern  日期格式，如 yyyy-MM-dd HH:mm:ss
     * @return 格式化后的字符串
     */
    public static String format(LocalDateTime dateTime, String pattern) {
        if (dateTime == null) {
            return null;
        }
        if (pattern == null || pattern.isEmpty()) {
            throw new IllegalArgumentException("pattern must not be null or empty");
        }

        DateTimeFormatter formatter =
                FORMATTER_CACHE.computeIfAbsent(pattern, DateTimeFormatter::ofPattern);

        return dateTime.format(formatter);
    }
    
    /**
     * 将给定字符串转换成 LocalDate
     * @param value 如 "20260101"
     * @param pattern 日期格式，如 yyyyMMdd
     * @return
     */
    public static LocalDate parse(String value, String pattern) {
        if (value == null) {
            return null;
        }
        if (pattern == null || pattern.isEmpty()) {
            throw new IllegalArgumentException("pattern must not be null or empty");
        }
        DateTimeFormatter formatter =
                FORMATTER_CACHE.computeIfAbsent(pattern, DateTimeFormatter::ofPattern);
        
        LocalDate date = LocalDate.parse(value, formatter);
        return date;
    }
    
    /**
     * 将数字类型日期转换成相应的 LocalDateTime
     * <p>
     * <li> 2309191130 → 2023-09-19 11:30:00
     * <li> 230919 → 2023-09-19
     */
    public static LocalDateTime longDatetimeToLocalDateTime(long dateTime) {
        if (dateTime <= 0) {
            throw new IllegalArgumentException("dateTime must be positive, got: " + dateTime);
        }

        try {
            if (dateTime > 99_999_999L) {
                // yyMMddHHmm 例如：2309191130 -> 2023-09-19 11:30
                int yy = (int) (dateTime / 100_000_000L);                 // 23
                int year = 2000 + yy;                                     // 2023
                int month = (int) ((dateTime % 100_000_000L) / 1_000_000L); // 09
                int day = (int) ((dateTime % 1_000_000L) / 10_000L);        // 19
                int hour = (int) ((dateTime % 10_000L) / 100L);             // 11
                int minute = (int) (dateTime % 100L);                       // 30

                return LocalDateTime.of(year, month, day, hour, minute, 0);
            } else {
                // yyyyMMdd 例如：20230919 -> 2023-09-19 00:00
                int year = (int) (dateTime / 10_000L);            // 2023
                int month = (int) ((dateTime % 10_000L) / 100L);   // 09
                int day = (int) (dateTime % 100L);                 // 19

                return LocalDateTime.of(year, month, day, 0, 0, 0);
            }
        } catch (DateTimeException ex) {
            // 月/日/时/分越界会进这里（比如 month=13）
            throw new IllegalArgumentException("Invalid dateTime value: " + dateTime, ex);
        }
    }
}
