package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

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

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    public static Date getNowDate(final String format) {
        try {
            String nowDate = parseDateToStr(format, new Date());
            return parseDate(nowDate, format);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算相差小时
     */
    public static float differentHoursByMillisecond(Date date1, Date date2) {
        return (float) (date2.getTime() - date1.getTime()) / (1000 * 60 * 60);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    public static List<String> dateList(Date start, Date end) {

        List<String> list = new ArrayList();

        long s = start.getTime();

        long e = end.getTime();

        Long oneDay = 1000 * 60 * 60 * 24l;

        while (s <= e) {

            start = new Date(s);

            list.add(new SimpleDateFormat("yyyy-MM-dd").format(start));

            s += oneDay;

        }

        return list;

    }

    public static List<String> dateList2(Date start, Date end) {
        List<String> list = new ArrayList<>();

        // 使用 Calendar 只保留年月日（清除时分秒）
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(start);
        startCal.set(Calendar.HOUR_OF_DAY, 0);
        startCal.set(Calendar.MINUTE, 0);
        startCal.set(Calendar.SECOND, 0);
        startCal.set(Calendar.MILLISECOND, 0);

        Calendar endCal = Calendar.getInstance();
        endCal.setTime(end);
        endCal.set(Calendar.HOUR_OF_DAY, 0);
        endCal.set(Calendar.MINUTE, 0);
        endCal.set(Calendar.SECOND, 0);
        endCal.set(Calendar.MILLISECOND, 0);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        while (!startCal.after(endCal)) {
            list.add(sdf.format(startCal.getTime()));
            startCal.add(Calendar.DAY_OF_MONTH, 1); // 增加一天
        }

        return list;
    }

    public static String[] getBeginEndTimeStr(String beginTimeStr, String endTimeStr, Integer countCycle) throws Exception {
        Date endDate = null;
        Date beginDate = null;
        if (countCycle != null) {
            endDate = DateUtils.getNowDate();
            beginDate = DateUtils.addDays(endDate, countCycle == 0 ? 0 : 1 - countCycle);
            beginTimeStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, beginDate) + " 00:00:00";
            endTimeStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endDate) + " 23:59:59";
        } else {
            if (StringUtils.isNotEmpty(beginTimeStr) && StringUtils.isEmpty(endTimeStr)) {
                throw new RuntimeException("开始时间不为空时，结束时间不能为空");
            }
            if (StringUtils.isNotEmpty(endTimeStr) && StringUtils.isEmpty(beginTimeStr)) {
                throw new RuntimeException("结束时间不为空时，开始时间不能为空");
            }
            if ((StringUtils.isEmpty(beginTimeStr) && StringUtils.isEmpty(endTimeStr)) && countCycle == null) {
                throw new RuntimeException("开始时间/结束时间、统计周期不能同时为空");
            }
            // 转换目的：校验日期格式是否正确，不正确会报错
            beginDate = DateUtils.parseDate(beginTimeStr, DateUtils.YYYY_MM_DD_HH_MM_SS);
            endDate = DateUtils.parseDate(endTimeStr, DateUtils.YYYY_MM_DD_HH_MM_SS);
            //beginTimeStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, beginDate);
            //endTimeStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endDate);
        }
        return new String[]{beginTimeStr, endTimeStr};
    }

    public static Date[] getBeginEndTime(String beginTimeStr, String endTimeStr, Integer countCycle) throws Exception {
        Date endDate = null;
        Date beginDate = null;
        if (countCycle != null) {
            endDate = DateUtils.getNowDate();
            beginDate = DateUtils.addDays(endDate, countCycle == 0 ? 0 : 1 - countCycle);
        } else {
            if (StringUtils.isNotEmpty(beginTimeStr) && StringUtils.isEmpty(endTimeStr)) {
                throw new RuntimeException("开始时间不为空时，结束时间不能为空");
            }
            if (StringUtils.isNotEmpty(endTimeStr) && StringUtils.isEmpty(beginTimeStr)) {
                throw new RuntimeException("结束时间不为空时，开始时间不能为空");
            }
            if ((StringUtils.isEmpty(beginTimeStr) && StringUtils.isEmpty(endTimeStr)) && countCycle == null) {
                throw new RuntimeException("开始时间/结束时间、统计周期不能同时为空");
            }
            // 转换目的：校验日期格式是否正确，不正确会报错
            beginDate = DateUtils.parseDate(beginTimeStr, DateUtils.YYYY_MM_DD_HH_MM_SS);
            endDate = DateUtils.parseDate(endTimeStr, DateUtils.YYYY_MM_DD_HH_MM_SS);
            //beginTimeStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, beginDate);
            //endTimeStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endDate);
        }
        return new Date[]{beginDate, endDate};
    }

    public static Date[] getBeginEndDate(String beginDateStr, String endDateStr, Integer countCycle) throws Exception {
        Date endDate = null;
        Date beginDate = null;
        if (countCycle != null) {
            endDate = DateUtils.getNowDate();
            beginDate = DateUtils.addDays(endDate, countCycle == 0 ? 0 : 1 - countCycle);
        } else {
            if (StringUtils.isNotEmpty(beginDateStr) && StringUtils.isEmpty(endDateStr)) {
                throw new RuntimeException("开始日期不为空时，结束日期不能为空");
            }
            if (StringUtils.isNotEmpty(endDateStr) && StringUtils.isEmpty(beginDateStr)) {
                throw new RuntimeException("结束日期不为空时，开始日期不能为空");
            }
            if ((StringUtils.isEmpty(beginDateStr) && StringUtils.isEmpty(endDateStr)) && countCycle == null) {
                throw new RuntimeException("开始日期/结束日期、统计周期不能同时为空");
            }
            // 转换目的：校验日期格式是否正确，不正确会报错
            beginDate = DateUtils.parseDate(beginDateStr, DateUtils.YYYY_MM_DD);
            endDate = DateUtils.parseDate(endDateStr, DateUtils.YYYY_MM_DD);
        }
        return new Date[]{beginDate, endDate};
    }

    public static LocalDate toLocalDate(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * 时间戳（秒）转日期字符串
     *
     * @param timestampSeconds
     * @return
     */
    public static String timestampSecondsToDate(Long timestampSeconds) {
        Instant instant = Instant.ofEpochSecond(timestampSeconds);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
        String formattedDate = formatter.format(instant);
        // 输出转换后的日期
        return formattedDate;
    }

    /**
     * 毫秒转x天x时x分x秒
     * @param millis
     * @return
     */
    public static String convertMillisToTime(long millis) {
        long seconds = millis / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        seconds %= 60;
        minutes %= 60;
        hours %= 24;

        StringBuilder timeString = new StringBuilder();

        if (days > 0) {
            timeString.append(days).append("天");
        }

        if (hours > 0) {
            timeString.append(hours).append("小时");
        }

        if (minutes > 0) {
            timeString.append(minutes).append("分钟");
        }

        if (seconds > 0 || timeString.length() == 0) { // 即使所有值为0时，显示0秒
            timeString.append(seconds).append("秒");
        }

        return timeString.toString();
    }

    /**
     * 毫秒转x天x时x分x秒
     * @param millis
     * @return
     */
    public static String convertMillisToTimeByLanguage(long millis, String language) {
        String dayLabel = "天";
        String hourLabel = "小时";
        String minuteLabel = "分钟";
        String secondLabel = "秒";

        if ("en".equals(language)) {
            dayLabel = " d ";
            hourLabel = " h ";
            minuteLabel = " m ";
            secondLabel = " s ";
        }

        long seconds = millis / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        seconds %= 60;
        minutes %= 60;
        hours %= 24;

        StringBuilder timeString = new StringBuilder();

        if (days > 0) {
            timeString.append(days).append(dayLabel);
        }

        if (hours > 0) {
            timeString.append(hours).append(hourLabel);
        }

        if (minutes > 0) {
            timeString.append(minutes).append(minuteLabel);
        }

        if (seconds > 0 || timeString.length() == 0) { // 即使所有值为0时，显示0秒
            timeString.append(seconds).append(secondLabel);
        }

        return timeString.toString();
    }

    /**
     * 日期字符串转时间戳（秒）
     *
     * @param dateStr
     * @return
     */
    public static Long dateStrToTimestamp(String dateStr) {
        // 先把字符串解析为 LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr.replace(" ", "T"));
        // 指定时区，比如中国是 Asia/Shanghai
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
        // 转换为时间戳（秒）
        long timestamp = zonedDateTime.toEpochSecond();
        return  timestamp;
    }

    public static void main(String[] args) {
        String dateStr = "2025-07-03 18:00:00";
        System.out.println(dateStrToTimestamp(dateStr));
    }
}
