package com.multictrl.common.utils;

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 日期处理
 *
 * @author Sdy
 */
public class DateUtils {
    /**
     * 时间格式(yyyy-MM-dd)
     */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    /**
     * 时间格式(yyyyMMddHHmmss)
     */
    public final static String DATE_TIME_PATTERN_COMPACT = "yyyyMMddHHmmss";

    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    /**
     * 日期格式化 日期格式为：yyyy-MM-dd
     *
     * @param date 日期
     * @return 返回yyyy-MM-dd格式日期
     */
    public static String format(Date date) {
        return format(date, DATE_PATTERN);
    }

    /**
     * 日期格式化 日期格式为：yyyy-MM-dd
     *
     * @param date    日期
     * @param pattern 格式，如：DateUtils.DATE_TIME_PATTERN
     * @return 返回yyyy-MM-dd格式日期
     */
    public static String format(Date date, String pattern) {
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 日期解析
     *
     * @param date    日期
     * @param pattern 格式，如：DateUtils.DATE_TIME_PATTERN
     * @return 返回Date
     */
    public static Date parse(String date, String pattern) {
        try {
            return new SimpleDateFormat(pattern).parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 转换成UTC时区
     */
    public static String toUtc(String localTimeStr) {
        try {
            DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN);
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
            LocalDateTime localDateTime = LocalDateTime.parse(localTimeStr, inputFormatter);
            ZonedDateTime zonedLocalTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));
            ZonedDateTime utcTime = zonedLocalTime.withZoneSameInstant(ZoneId.of("UTC"));

            return outputFormatter.format(utcTime);
        } catch (Exception e) {
            System.out.println("UTC时间转换失败，输入时间={" + localTimeStr + "}");
            System.out.println(e);
            return null; // 或抛出异常，根据业务需要决定
        }
    }

    /**
     * UTC时间戳转换为北京时间
     */
    public static String utcToTime(Instant instant) {
        // 把时间戳转成 Instant
//        Instant instant = Instant.ofEpochMilli(timestamp);
        if (instant == null) {
            return null;
        }

        // 转为北京时间格式输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)
                .withZone(ZoneId.of("Asia/Shanghai"));

        return formatter.format(instant);
    }

    /**
     * UTC时间戳转换为北京时间
     * yyyy-MM-dd'T'HH:mm:ss'Z'
     */
    public static String utcToTime(String utcTimeStr) {
        // 解析为 UTC 时间
        ZonedDateTime utcTime = ZonedDateTime.parse(utcTimeStr);

        // 转换为北京时间（UTC+8）
        ZonedDateTime beijingTime = utcTime.withZoneSameInstant(java.time.ZoneId.of("Asia/Shanghai"));

        // 格式化输出
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateUtils.DATE_TIME_PATTERN);
        return formatter.format(beijingTime);
    }

    /**
     * 获取n天后的时间戳
     */
    public static Long getNextNDaysTimestamp(int n) {
        Instant now = Instant.now();
        Instant instant = now.plusSeconds(24L * 60 * 60 * n);
        return instant.toEpochMilli();
    }

    /**
     * 两个时间相差几时几分几秒
     */
    public static String formatDifference(Date startDate, Date endDate) {
        long startMillis = startDate.getTime();
        long endMillis = endDate.getTime();
        long diffSeconds = Math.abs((endMillis - startMillis) / 1000);

        if (diffSeconds < 60) {
            return MessageFormat.format("{0}秒", diffSeconds);
        } else if (diffSeconds < 3600) {
            long minutes = diffSeconds / 60;
            long seconds = diffSeconds % 60;
            return MessageFormat.format("{0}分{1}秒", minutes, seconds);
        } else {
            long hours = diffSeconds / 3600;
            long remaining = diffSeconds % 3600;
            long minutes = remaining / 60;
            long seconds = remaining % 60;
            return MessageFormat.format("{0}小时{1}分{2}秒", hours, minutes, seconds);
        }
    }

    /**
     * 时间往前/后推多少秒
     */
    public static Date getBeforeTime(Date date, int seconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, seconds);

        return calendar.getTime();
    }

    /**
     * 时间往前/后推多少小时
     */
    public static Date getBeforeHour(Date date, int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR, hour);

        return calendar.getTime();
    }

    /**
     * 获取范围内所有时间
     */
    public static List<String> getAllDate(String startTime, String endTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(startTime, formatter);
        LocalDate endDate = LocalDate.parse(endTime, formatter);
        return startDate.datesUntil(endDate.plusDays(1)).map(v -> v.format(formatter)).toList();
    }

    /**
     * 假设 breakMinTime 和 breakMaxTime 格式为 "HH:mm:ss"
     */
    public static boolean isCurrentTimeInInterval(String breakMinTime, String breakMaxTime) {
        try {
            // 解析时间字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
            LocalTime minTime = LocalTime.parse(breakMinTime, formatter);
            LocalTime maxTime = LocalTime.parse(breakMaxTime, formatter);
            LocalTime currentTime = LocalTime.now();

            // 判断当前时间是否在区间内
            if (minTime.isBefore(maxTime)) {
                // 正常情况：开始时间小于结束时间
                return !currentTime.isBefore(minTime) && !currentTime.isAfter(maxTime);
            } else {
                // 跨天情况：比如 22:00:00 到 02:00:00
                return !currentTime.isBefore(minTime) || !currentTime.isAfter(maxTime);
            }
        } catch (Exception e) {
            // 处理解析异常
            return false;
        }
    }

    /**
     * 时间戳转日期
     */
    public static String longToDateString(long time) {
        // 确保startTime是毫秒级时间戳（不是秒级）
        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());

        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 计算两个时间点的间隔（秒）
     */
    public static long calculateTimeDifference(String time1, String time2) {
        try {
            LocalDateTime t1 = LocalDateTime.parse(time1, TIME_FORMATTER);
            LocalDateTime t2 = LocalDateTime.parse(time2, TIME_FORMATTER);
            return ChronoUnit.SECONDS.between(t1, t2);
        } catch (Exception e) {
            return 1; // 解析失败视为间隔1秒（避免死循环）
        }
    }

    /**
     * 在时间基础上增加秒数
     */
    public static String addSeconds(String time, int seconds) {
        try {
            LocalDateTime dt = LocalDateTime.parse(time, TIME_FORMATTER);
            return dt.plusSeconds(seconds).format(TIME_FORMATTER);
        } catch (Exception e) {
            return time; // 解析失败返回原时间
        }
    }
}
