package cn.iocoder.yudao.framework.common.util.date;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.google.common.collect.ImmutableMap;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 时间工具类
 *
 * @author 芋道源码
 */
public class DateUtils {

    /**
     * 时区 - 默认
     */
    public static final String TIME_ZONE_DEFAULT = "GMT+8";
    private static final ZoneId ZONE_ID = ZoneId.systemDefault();


    /**
     * 秒转换成毫秒
     */
    public static final long SECOND_MILLIS = 1000;

    public static final String FORMAT_YEAR_MONTH_DAY = "yyyy-MM-dd";

    public static final String FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND = "yyyy-MM-dd HH:mm:ss";

    /**
     * 将 LocalDateTime 转换成 Date
     *
     * @param date LocalDateTime
     * @return LocalDateTime
     */
    public static Date of(LocalDateTime date) {
        if (date == null) {
            return null;
        }
        // 将此日期时间与时区相结合以创建 ZonedDateTime
        ZonedDateTime zonedDateTime = date.atZone(ZoneId.systemDefault());
        // 本地时间线 LocalDateTime 到即时时间线 Instant 时间戳
        Instant instant = zonedDateTime.toInstant();
        // UTC时间(世界协调时间,UTC + 00:00)转北京(北京,UTC + 8:00)时间
        return Date.from(instant);
    }

    /**
     * 将 Date 转换成 LocalDateTime
     *
     * @param date Date
     * @return LocalDateTime
     */
    public static LocalDateTime of(Date date) {
        if (date == null) {
            return null;
        }
        // 转为时间戳
        Instant instant = date.toInstant();
        // UTC时间(世界协调时间,UTC + 00:00)转北京(北京,UTC + 8:00)时间
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    public static Date addTime(Duration duration) {
        return new Date(System.currentTimeMillis() + duration.toMillis());
    }

    public static boolean isExpired(LocalDateTime time) {
        LocalDateTime now = LocalDateTime.now();
        return now.isAfter(time);
    }

    /**
     * 创建指定时间
     *
     * @param year  年
     * @param mouth 月
     * @param day   日
     * @return 指定时间
     */
    public static Date buildTime(int year, int mouth, int day) {
        return buildTime(year, mouth, day, 0, 0, 0);
    }

    /**
     * 创建指定时间
     *
     * @param year   年
     * @param mouth  月
     * @param day    日
     * @param hour   小时
     * @param minute 分钟
     * @param second 秒
     * @return 指定时间
     */
    public static Date buildTime(int year, int mouth, int day,
                                 int hour, int minute, int second) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, mouth - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, 0); // 一般情况下，都是 0 毫秒
        return calendar.getTime();
    }

    public static Date max(Date a, Date b) {
        if (a == null) {
            return b;
        }
        if (b == null) {
            return a;
        }
        return a.compareTo(b) > 0 ? a : b;
    }

    public static LocalDateTime max(LocalDateTime a, LocalDateTime b) {
        if (a == null) {
            return b;
        }
        if (b == null) {
            return a;
        }
        return a.isAfter(b) ? a : b;
    }

    /**
     * 是否今天
     *
     * @param date 日期
     * @return 是否
     */
    public static boolean isToday(LocalDateTime date) {
        return LocalDateTimeUtil.isSameDay(date, LocalDateTime.now());
    }

    /**
     * 是否昨天
     *
     * @param date 日期
     * @return 是否
     */
    public static boolean isYesterday(LocalDateTime date) {
        return LocalDateTimeUtil.isSameDay(date, LocalDateTime.now().minusDays(1));
    }


    public static ImmutableMap<String, LocalDateTime> getBeginEndDay(Integer day) {
        // 昨天开始时间（00:00:00）
        LocalDateTime yesterdayStart = LocalDate.now().minusDays(day).atStartOfDay();
        // 昨天结束时间（23:59:59.999999999）
        LocalDateTime yesterdayEnd = LocalDateTime.of(LocalDate.now().minusDays(day), LocalTime.MAX);
        return ImmutableMap.of("start", yesterdayStart, "end", yesterdayEnd);
    }

    public static ImmutableMap<String, LocalDateTime> getBeginEndWeek() {
        // 近一周开始时间（如今天是2025-05-09，则此值为2025-05-03 00:00）
        LocalDateTime weekStart = LocalDate.now().minusDays(6).atStartOfDay();
        // 近一周结束时间（当前日期的23:59:59.999999999）
        LocalDateTime weekEnd = LocalDateTime.now().with(LocalTime.MAX);

        return ImmutableMap.of("start", weekStart, "end", weekEnd);
    }
    /**
     * 获取上个月第一天 00:00:00
     */
    public static LocalDateTime getFirstDayOfLastMonth() {
        LocalDate now = LocalDate.now(ZONE_ID);
        // 上个月
        LocalDate lastMonth = now.minusMonths(1);
        // 上个月第一天
        LocalDate firstDay = lastMonth.withDayOfMonth(1);
        return firstDay.atStartOfDay();
    }

    /**
     * 获取上个月最后一天 23:59:59
     */
    public static LocalDateTime getLastDayOfLastMonth() {
        LocalDate now = LocalDate.now(ZONE_ID);
        // 上个月
        LocalDate lastMonth = now.minusMonths(1);
        // 上个月最后一天
        LocalDate lastDay = lastMonth.plusMonths(1).withDayOfMonth(1).minusDays(1);
        return lastDay.atTime(23, 59, 59);
    }
    public static ImmutableMap<String, LocalDateTime> getBeginEndMonth() {
        // 近一月开始时间（如今天是2025-05-09，此值为2025-04-10 00:00）
        LocalDateTime monthStart = LocalDate.now().minusDays(29).atStartOfDay();
        // 近一月结束时间（当前日期的23:59:59.999999999）
        LocalDateTime monthEnd = LocalDateTime.now().with(LocalTime.MAX);
        return ImmutableMap.of("start", monthStart, "end", monthEnd);
    }
    public static List<MonthRange> getLastYearMonthRanges() {
        List<MonthRange> result = new ArrayList<>();
        YearMonth currentYearMonth = YearMonth.now();
        YearMonth startYearMonth = currentYearMonth.minusMonths(11);

        for (int i = 0; i < 12; i++) {
            YearMonth yearMonth = startYearMonth.plusMonths(i);
            String formattedMonth = yearMonth.toString(); // 格式为 yyyy-MM
            LocalDateTime start = yearMonth.atDay(1).atStartOfDay();
            LocalDateTime end = yearMonth.atEndOfMonth().atTime(LocalTime.MAX);
            result.add(new MonthRange(formattedMonth, start, end, 0));
        }

        return result;
    }

    /**
     * 获取近6个月的日期范围
     * @return
     */
    public static List<MonthRange> getRecentSixMonthRanges() {
        List<MonthRange> result = new ArrayList<>();
        YearMonth currentYearMonth = YearMonth.now();
        YearMonth startYearMonth = currentYearMonth.minusMonths(5);

        for (int i = 0; i < 6; i++) {
            YearMonth yearMonth = startYearMonth.plusMonths(i);
            String formattedMonth = yearMonth.toString(); // 格式为 yyyy-MM
            LocalDateTime start = yearMonth.atDay(1).atStartOfDay();
            LocalDateTime end = yearMonth.atEndOfMonth().atTime(LocalTime.MAX);
            result.add(new MonthRange(formattedMonth, start, end, 0));
        }

        return result;
    }

    public static class MonthRange {
        private  String yearMonth;
        private  LocalDateTime start;
        private  LocalDateTime end;
        private  Integer count;

        public MonthRange(String yearMonth, LocalDateTime start, LocalDateTime end, Integer count) {
            this.yearMonth = yearMonth;
            this.start = start;
            this.end = end;
            this.count = count;
        }

        public void setYearMonth(String yearMonth) {
            this.yearMonth = yearMonth;
        }

        public void setStart(LocalDateTime start) {
            this.start = start;
        }

        public void setEnd(LocalDateTime end) {
            this.end = end;
        }

        public void setCount(Integer count) {
            this.count = count;
        }

        public String getYearMonth() {
            return yearMonth;
        }

        public LocalDateTime getStart() {
            return start;
        }

        public LocalDateTime getEnd() {
            return end;
        }

        public Integer getCount() {
            return count;
        }

    }

    public static BigDecimal calculateHoursDiff(LocalDateTime start, LocalDateTime end) {
        Duration duration = Duration.between(start, end);
        double hoursDiff = duration.toHours() + (duration.toMinutes() % 60) / 60.0;
        return new BigDecimal(hoursDiff).setScale(1, RoundingMode.HALF_UP);
    }
    public static List<String> getLastSevenDays() {
        List<String> dates = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 获取今天的日期
        LocalDate today = LocalDate.now();

        // 生成近七天的日期
        for (int i = 0; i < 7; i++) {
            LocalDate date = today.minusDays(i);
            dates.add(date.format(formatter));
        }

        return dates;
    }

    /**
     * 获取指定日期的开始时间
     * @param dateStr 日期字符串，格式为yyyy-MM-dd
     * @return 当天的开始时间LocalDateTime (00:00:00)
     */
    public static LocalDateTime getStartOfDay(String dateStr) {
        LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);
        return date.atStartOfDay();
    }

    /**
     * 获取指定日期的结束时间
     * @param dateStr 日期字符串，格式为yyyy-MM-dd
     * @return 当天的结束时间LocalDateTime (23:59:59.999999999)
     */
    public static LocalDateTime getEndOfDay(String dateStr) {
        LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);
        return date.atTime(LocalTime.MAX);
    }

    public static Timestamp generateTimestamp(String dateStr) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 解析字符串为LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr, formatter);

        // 转换为java.sql.Timestamp
        Timestamp timestamp = Timestamp.valueOf(localDateTime);
        return timestamp;
    }

        public static boolean checkIfFullDayDifference(String timeStr) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime givenTime = LocalDateTime.parse(timeStr, formatter);
            LocalDateTime now = LocalDateTime.now();

            long hoursDifference = ChronoUnit.MINUTES.between(givenTime, now);
            return Math.abs(hoursDifference) >= 5;
        }

        public static LocalDateTime contactTime(LocalDateTime targetTime ) {
            LocalDateTime now = LocalDateTime.now();
            int currentYear = now.getYear();       // 当前年（如2024）
            int currentMonth = now.getMonthValue();// 当前月（1-12，如10）
            int currentDay = now.getDayOfMonth();  // 当前日（1-31，如8）

            // 3. 获取指定时间的「时、分、秒」
            int targetHour = targetTime.getHour();     // 指定时（0-23，如14）
            int targetMinute = targetTime.getMinute(); // 指定分（0-59，如30）
            int targetSecond = targetTime.getSecond(); // 指定秒（0-59，如45）

            // 4. 拼接：当前年月日 + 指定时分秒 → 新的LocalDateTime
            LocalDateTime mergedDateTime = LocalDateTime.of(
                    currentYear, currentMonth, currentDay,
                    targetHour, targetMinute, targetSecond
            );
            return mergedDateTime;
        }

        public static String convertTimeToString(String time) {
            // 定义时间戳（毫秒级）
            long timestamp = Long.parseLong(time);

            // 转换步骤：
            // 1. 将时间戳转为Instant对象
            Instant instant = Instant.ofEpochMilli(timestamp);
            // 2. 转换为本地日期（默认时区，也可指定如ZoneId.of("Asia/Shanghai")）
            LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
            // 3. 定义格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 4. 格式化日期
            String dateStr = localDate.format(formatter);

            return dateStr;
        }
}
