package com.bonus.canteen.core.utils;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author xliu
 * @date 2025/4/17 18:45
 */
public class CurrentToNextSunday {
    public static void main(String[] args) {
        // 假设今天是周四（可以替换为LocalDate.now()获取真实当前日期）
        LocalDate today = LocalDate.of(2025, 4, 26); // 2025-04-17 周四
        System.out.println("当前日期: " + today.format(DateTimeFormatter.ISO_LOCAL_DATE));

        // 获取从今天到下周日的日期信息
        Map<DayOfWeek, DateInfo> dateMap = getDatesFromTodayToNextSunday(today);

        // 打印结果
        System.out.println("\n从今天到下周日的日期信息:");
        System.out.println("星期\t日期\t\t天数差");
        dateMap.forEach((day, info) ->
                System.out.printf("%s\t%s\t%s%n",
                        getChineseWeekday(day),
                        info.date.format(DateTimeFormatter.ISO_LOCAL_DATE),
                        formatDayDifference(info.difference))
        );
    }

    /**
     * 获取从今天到下周日的日期信息
     * @param today 当前日期（周四）
     * @return 有序的日期信息Map
     */
    public static Map<DayOfWeek, DateInfo> getDatesFromTodayToNextSunday(LocalDate today) {
        Map<DayOfWeek, DateInfo> result = new LinkedHashMap<>();

        // 获取下周日日期
        LocalDate nextSunday = today.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));

        // 从今天开始，直到下周日，逐个日期处理
        LocalDate currentDate = today;
        while (!currentDate.isAfter(nextSunday)) {
            long difference = currentDate.toEpochDay() - today.toEpochDay();
            result.put(currentDate.getDayOfWeek(), new DateInfo(currentDate, difference));
            currentDate = currentDate.plusDays(1);
        }

        return result;
    }

    // 以下辅助方法与之前相同
    private static String getChineseWeekday(DayOfWeek day) {
        switch (day) {
            case MONDAY: return "周一";
            case TUESDAY: return "周二";
            case WEDNESDAY: return "周三";
            case THURSDAY: return "周四";
            case FRIDAY: return "周五";
            case SATURDAY: return "周六";
            case SUNDAY: return "周日";
            default: return day.toString();
        }
    }

    private static String formatDayDifference(long difference) {
        if (difference == 0) return "今天";
        else if (difference < 0) return Math.abs(difference) + "天前";
        else return difference + "天后";
    }

    public static class DateInfo {
        LocalDate date;
        long difference;

        DateInfo(LocalDate date, long difference) {
            this.date = date;
            this.difference = difference;
        }
    }
}
