package com.ttstd.dialer.utils;

import android.os.Build;

import androidx.annotation.RequiresApi;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateUtil {
    private static SimpleDateFormat day = new SimpleDateFormat("M月d日");
    private static SimpleDateFormat hour = new SimpleDateFormat("HH:mm");
    private static SimpleDateFormat minute = new SimpleDateFormat("mm");

    /**
     * 格式化日期(精确到天)
     */
    public static String formatDateDay() {
        return day.format(new Date());
    }

    public static String formatDateTime() {
        return day.format(new Date());
    }

    /**
     * 格式化日期(hour)
     */
    public static String formatDateHour() {
        return hour.format(new Date());
    }

    public static boolean isTodayAll(String dateStr) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return isToday26(dateStr);
        } else {
            return isToday(dateStr);
        }
    }

    // 根据日期取得星期几
    public static String getWeek() {
        Date date = new Date();
        String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int weekIndex = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (weekIndex < 0) {
            weekIndex = 0;
        }
        return weeks[weekIndex];
    }

    public static boolean isToday(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            Date inputDate = sdf.parse(dateStr);

            Calendar today = Calendar.getInstance();
            Calendar target = Calendar.getInstance();
            target.setTime(inputDate);

            return today.get(Calendar.YEAR) == target.get(Calendar.YEAR) &&
                    today.get(Calendar.MONTH) == target.get(Calendar.MONTH) &&
                    today.get(Calendar.DAY_OF_MONTH) == target.get(Calendar.DAY_OF_MONTH);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static boolean isToday26(String dateStr) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate inputDate = LocalDate.parse(dateStr, formatter);
            LocalDate today = LocalDate.now();

            return today.isEqual(inputDate);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String getWeekDayFromDateAll(String dateStr, Locale locale) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return getWeekDayFromDate26(dateStr, locale);
        } else {
            return getWeekDayFromDate(dateStr, locale);
        }
    }


    /**
     * 将 yyyy-MM-dd 格式的日期字符串转换为星期几
     *
     * @param dateStr 日期字符串，格式：yyyy-MM-dd
     * @param locale  地区设置，如 Locale.CHINA
     * @return 星期几的中文表示（如：星期一）
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String getWeekDayFromDate26(String dateStr, Locale locale) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析日期字符串
        LocalDate date = LocalDate.parse(dateStr, formatter);
        // 获取星期几并格式化为中文
        return date.getDayOfWeek().getDisplayName(TextStyle.FULL, locale);
    }

    /**
     * 将 yyyy-MM-dd 格式的日期字符串转换为星期几
     *
     * @param dateStr 日期字符串，格式：yyyy-MM-dd
     * @param locale  地区设置，如 Locale.CHINA
     * @return 星期几的中文表示
     */
    public static String getWeekDayFromDate(String dateStr, Locale locale) {
        try {
            // 定义日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", locale);
            Date date = sdf.parse(dateStr);

            // 创建用于格式化星期的 SimpleDateFormat
            SimpleDateFormat weekFormat = new SimpleDateFormat("EEEE", locale);
            return weekFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String convertToChineseWeekdayAll() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 设置时区（可选，默认为系统时区）
        // sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        long timestamp = System.currentTimeMillis();
        Date date = new Date(timestamp);
        String dateStr = sdf.format(date);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return convertToChineseWeekdayWithLocalDate(dateStr);
        } else {
            return convertToChineseWeekday(dateStr);
        }
    }

    public static String convertToChineseWeekdayAll(String dateStr) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return convertToChineseWeekdayWithLocalDate(dateStr);
        } else {
            return convertToChineseWeekday(dateStr);
        }
    }

    /**
     * 将yyyy-MM-dd格式的日期字符串转换为"周几"格式
     * 例如：2026-02-17 → 周二
     */
    public static String convertToChineseWeekday(String dateStr) {
        try {
            // 解析日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            Date date = sdf.parse(dateStr);

            if (date == null) {
                return "日期解析失败";
            }

            // 使用Calendar获取星期几
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

            // Calendar中周日=1,周一=2,...,周六=7
            // 转换为中文"周几"格式
            String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};

            // 注意：Calendar的DAY_OF_WEEK从周日开始（1=周日），所以要减1
            return weekDays[dayOfWeek - 1];

        } catch (Exception e) {
            e.printStackTrace();
            return "日期格式错误";
        }
    }

    /**
     * 另一种实现方式：使用LocalDate（需要API 26+）
     * 推荐在Android 8.0及以上使用
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String convertToChineseWeekdayWithLocalDate(String dateStr) {
        try {
            // 注意：以下代码需要Android API 26+（Android 8.0）
            java.time.LocalDate localDate = java.time.LocalDate.parse(dateStr);
            int dayOfWeekValue = localDate.getDayOfWeek().getValue();

            // java.time中周一=1,周二=2,...,周日=7
            String[] weekDays = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};

            return weekDays[dayOfWeekValue - 1];

        } catch (Exception e) {
            e.printStackTrace();
            return "日期格式错误";
        }
    }

}
