package com.sundot.airport.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 月份工具类-人事绩效模块
 */
public class MonthUtils {

    /**
     * 月份范围对象
     */
    public static class MonthRange {
        private String startMonth;
        private String endMonth;

        public MonthRange(String startMonth, String endMonth) {
            this.startMonth = startMonth;
            this.endMonth = endMonth;
        }

        public String getStartMonth() {
            return startMonth;
        }

        public String getEndMonth() {
            return endMonth;
        }

        @Override
        public String toString() {
            return "MonthRange{startMonth='" + startMonth + "', endMonth='" + endMonth + "'}";
        }
    }

    private static final DateTimeFormatter MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyyMM");

    /**
     * 根据月份值查询上个月月份值
     * @param month 月份值，格式：yyyyMM
     * @return 上个月月份值，格式：yyyyMM
     */
    public static String getPreviousMonth(String month) {
        if (month == null || month.length() != 6) {
            throw new IllegalArgumentException("月份格式错误，应为yyyyMM");
        }

        try {
            YearMonth yearMonth = YearMonth.parse(month, MONTH_FORMATTER);
            YearMonth previousMonth = yearMonth.minusMonths(1);
            return previousMonth.format(MONTH_FORMATTER);
        } catch (Exception e) {
            throw new IllegalArgumentException("月份解析失败: " + month);
        }
    }

    /**
     * 根据月份值查询下个月月份值
     * @param month 月份值，格式：yyyyMM
     * @return 下个月月份值，格式：yyyyMM
     */
    public static String getNextMonth(String month) {
        if (month == null || month.length() != 6) {
            throw new IllegalArgumentException("月份格式错误，应为yyyyMM");
        }

        try {
            YearMonth yearMonth = YearMonth.parse(month, MONTH_FORMATTER);
            YearMonth nextMonth = yearMonth.plusMonths(1);
            return nextMonth.format(MONTH_FORMATTER);
        } catch (Exception e) {
            throw new IllegalArgumentException("月份解析失败: " + month);
        }
    }

    /**
     * 查询近3个月月份值（不包含当月）
     * @param month 月份值，格式：yyyyMM
     * @return 开始月份和结束月份
     */
    public static MonthRange getLast3Months(String month) {
        return getLastNMonths(month, 3);
    }

    /**
     * 查询近12个月月份值（不包含当月）
     * @param month 月份值，格式：yyyyMM
     * @return 开始月份和结束月份
     */
    public static MonthRange getLast12Months(String month) {
        return getLastNMonths(month, 12);
    }

    /**
     * 查询近N个月月份值（不包含当月）
     * @param month 月份值，格式：yyyyMM
     * @param n 月数
     * @return 开始月份和结束月份
     */
    private static MonthRange getLastNMonths(String month, int n) {
        if (month == null || month.length() != 6) {
            throw new IllegalArgumentException("月份格式错误，应为yyyyMM");
        }

        try {
            YearMonth currentMonth = YearMonth.parse(month, MONTH_FORMATTER);
            YearMonth startMonth = currentMonth.minusMonths(n);
            YearMonth endMonth = currentMonth.minusMonths(1);

            return new MonthRange(
                    startMonth.format(MONTH_FORMATTER),
                    endMonth.format(MONTH_FORMATTER)
            );
        } catch (Exception e) {
            throw new IllegalArgumentException("月份解析失败: " + month);
        }
    }

    /**
     * 查询此年度12个月月份值
     * @param month 月份值，格式：yyyyMM
     * @return 开始月份（当年1月）和结束月份（当年12月）
     */
    public static MonthRange getCurrentYearMonths(String month) {
        if (month == null || month.length() != 6) {
            throw new IllegalArgumentException("月份格式错误，应为yyyyMM");
        }

        try {
            YearMonth currentMonth = YearMonth.parse(month, MONTH_FORMATTER);
            int year = currentMonth.getYear();

            YearMonth startMonth = YearMonth.of(year, 1);
            YearMonth endMonth = YearMonth.of(year, 12);

            return new MonthRange(
                    startMonth.format(MONTH_FORMATTER),
                    endMonth.format(MONTH_FORMATTER)
            );
        } catch (Exception e) {
            throw new IllegalArgumentException("月份解析失败: " + month);
        }
    }

    /**
     * 查询近3个月月份值（包含当月）
     * @param month 月份值，格式：yyyyMM
     * @return 开始月份和结束月份
     */
    public static MonthRange getLast3MonthsIncludeCurrent(String month) {
        return getLastNMonthsIncludeCurrent(month, 3);
    }

    /**
     * 查询近12个月月份值（包含当月）
     * @param month 月份值，格式：yyyyMM
     * @return 开始月份和结束月份
     */
    public static MonthRange getLast12MonthsIncludeCurrent(String month) {
        return getLastNMonthsIncludeCurrent(month, 12);
    }

    /**
     * 查询近N个月月份值（包含当月）
     * @param month 月份值，格式：yyyyMM
     * @param n 月数
     * @return 开始月份和结束月份
     */
    private static MonthRange getLastNMonthsIncludeCurrent(String month, int n) {
        if (month == null || month.length() != 6) {
            throw new IllegalArgumentException("月份格式错误，应为yyyyMM");
        }

        try {
            YearMonth currentMonth = YearMonth.parse(month, MONTH_FORMATTER);
            YearMonth startMonth = currentMonth.minusMonths(n - 1);

            return new MonthRange(
                    startMonth.format(MONTH_FORMATTER),
                    month  // 结束月份就是传入的月份（包含当月）
            );
        } catch (Exception e) {
            throw new IllegalArgumentException("月份解析失败: " + month);
        }
    }

    /**
     * 查询此年度12个月月份值（1月份到输入的月份）
     * @param month 月份值，格式：yyyyMM
     * @return 开始月份（当年1月）和结束月份（输入的月份）
     */
    public static MonthRange getCurrentYearToMonth(String month) {
        if (month == null || month.length() != 6) {
            throw new IllegalArgumentException("月份格式错误，应为yyyyMM");
        }

        try {
            YearMonth currentMonth = YearMonth.parse(month, MONTH_FORMATTER);
            int year = currentMonth.getYear();

            YearMonth startMonth = YearMonth.of(year, 1);

            return new MonthRange(
                    startMonth.format(MONTH_FORMATTER),
                    month  // 结束月份就是传入的月份
            );
        } catch (Exception e) {
            throw new IllegalArgumentException("月份解析失败: " + month);
        }
    }

    /**
     * 获取指定月份范围内的所有月份列表
     * @param startMonth 开始月份，格式：yyyyMM
     * @param endMonth 结束月份，格式：yyyyMM
     * @return 月份列表
     */
    public static List<String> getMonthList(String startMonth, String endMonth) {
        List<String> monthList = new ArrayList<>();

        try {
            YearMonth start = YearMonth.parse(startMonth, MONTH_FORMATTER);
            YearMonth end = YearMonth.parse(endMonth, MONTH_FORMATTER);

            while (!start.isAfter(end)) {
                monthList.add(start.format(MONTH_FORMATTER));
                start = start.plusMonths(1);
            }

            return monthList;
        } catch (Exception e) {
            throw new IllegalArgumentException("月份解析失败");
        }
    }


    /**
     * 获取指定月份的第一天开始时间（yyyy-MM-dd 00:00:00）
     * @param yearMonth 月份字符串，格式 yyyyMM
     * @return 开始时间的 Date 对象
     */
    public static Date getMonthStartTime(String yearMonth) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            Date date = sdf.parse(yearMonth);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            return calendar.getTime();
        } catch (ParseException e) {
            throw new IllegalArgumentException("月份格式无效,请使用【yyyyMM】格式");
        }
    }

    /**
     * 获取指定月份的最后一天开始时间（yyyy-MM-dd 00:00:00）
     * @param yearMonth 月份字符串，格式 yyyyMM
     * @return 最后一天开始时间的 Date 对象
     */
    public static Date getMonthLastDayStartTime(String yearMonth) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            Date date = sdf.parse(yearMonth);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            // 获取该月的最大天数
            int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            calendar.set(Calendar.DAY_OF_MONTH, lastDay);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            return calendar.getTime();
        } catch (ParseException e) {
            throw new IllegalArgumentException("Invalid month format. Please use yyyyMM.");
        }
    }

    /**
     * 获取指定月份的最后一天结束时间（yyyy-MM-dd 23:59:59）
     * @param yearMonth 月份字符串，格式 yyyyMM
     * @return 结束时间的 Date 对象
     */
    public static Date getMonthEndTime(String yearMonth) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            Date date = sdf.parse(yearMonth);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            // 设置为下个月第一天
            calendar.add(Calendar.MONTH, 1);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            // 减去一秒得到当月最后一秒
            calendar.add(Calendar.SECOND, -1);

            return calendar.getTime();
        } catch (ParseException e) {
            throw new IllegalArgumentException("月份格式无效,请使用【yyyyMM】格式");
        }
    }

}
