export interface CalendarDay {
    date: string;
    isCurrentMonth: boolean;
    day: number;
}

export const generateMonthCalendar = date => {
    const year = date.getFullYear();
    const month = date.getMonth(); // 月份从0开始
    const firstDayOfMonth = new Date(year, month, 1);
    const lastDayOfMonth = new Date(year, month + 1, 0); // 下个月第一天的前一天
    const daysInMonth = lastDayOfMonth.getDate();
    const dayOfWeekFirst = (firstDayOfMonth.getDay() + 6) % 7; // 调整为星期一为一周的开始

    // 获取上个月的信息
    const prevMonth = month === 0 ? 11 : month - 1;
    const prevYear = month === 0 ? year - 1 : year;
    const lastDayOfPrevMonth = new Date(prevYear, prevMonth + 1, 0).getDate();

    // 获取下个月的信息
    const nextMonth = month === 11 ? 0 : month + 1;
    const nextYear = month === 11 ? year + 1 : year;

    // 创建一个二维数组来存储每个月的数据
    const calendar = [];
    let week: CalendarDay[] = [];
    let day = 1;
    let padding = dayOfWeekFirst; // 补充空白的天数

    // 合并填充和实际日期填充的逻辑
    for (let i = 0; i < 7 * 6; i++) {
        // 最多6周
        if (padding > 0) {
            // 填充上个月的日期
            week.push({
                date: formatDate(prevYear, prevMonth + 1, lastDayOfPrevMonth - padding + 1),
                isCurrentMonth: false,
                day: lastDayOfPrevMonth - padding + 1,
            });
            padding--;
        } else if (day <= daysInMonth) {
            // 填充当前月的日期
            week.push({
                date: formatDate(year, month + 1, day),
                isCurrentMonth: true,
                day,
            });
            day++;
        } else {
            // 填充下个月的日期
            week.push({
                date: formatDate(nextYear, nextMonth + 1, day - daysInMonth),
                isCurrentMonth: false,
                day: day - daysInMonth,
            });
            day++;
        }

        if (week.length === 7) {
            // 如果一周填满了
            calendar.push(week);
            week = [];
        }
    }

    return calendar;
};

function formatDate(year, month, day) {
    return `${year}-${padZero(month)}-${padZero(day)}`;
}

function padZero(value) {
    return value < 10 ? `0${value}` : `${value}`;
}
