package com.project.common.utils;

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

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 时间工具类
 *
 * @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";
    public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

    private static final 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();
    }

    /**
     * 获取当前日期, 默认格式为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 getTimeString() {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS,new Date());
    }

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

    public static final String dateTimeNowString() {
        return parseDateToStr(YYYYMMDDHHMMSS,new Date());
    }

    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 parseDate(String dateString,String formatter) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatter); // 指定日期格式
        try {
            return sdf.parse(dateString);
        } catch (ParseException e) {
            System.err.println("Error parsing the date string.");
            e.printStackTrace();
        }
        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 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());
    }

    /**
     * 计算两个时间差几天1 时2 分钟3 秒4
     */
    public static long getDatePoorDiff(Date startDate,Date endDate, int type) {
        String formatterText;
        if(type == 1){//天
            formatterText = "yyyy-MM-dd";
        }else if(type == 2 || type == 3){//时
            formatterText = "yyyy-MM-dd HH:mm";
        }else{//秒
            formatterText = "yyyy-MM-dd HH:mm:ss";
        }
        if(type == 1){
            LocalDate date1 = LocalDate.of(Integer.parseInt(parseDateToStr("yyyy", startDate)), Integer.parseInt(parseDateToStr("MM", startDate)), Integer.parseInt(parseDateToStr("dd", startDate)));
            LocalDate date2 = LocalDate.of(Integer.parseInt(parseDateToStr("yyyy", endDate)), Integer.parseInt(parseDateToStr("MM", endDate)), Integer.parseInt(parseDateToStr("dd", endDate)));
            return ChronoUnit.DAYS.between(date1, date2);
        }else{
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatterText);
            LocalDateTime time1 = LocalDateTime.parse(parseDateToStr(formatterText,startDate) , formatter);
            LocalDateTime time2 = LocalDateTime.parse(parseDateToStr(formatterText,endDate), formatter);
            if(type == 2){
                return ChronoUnit.HOURS.between(time1, time2);
            }else if(type == 3){
                return ChronoUnit.MINUTES.between(time1, time2);
            }else{
                return ChronoUnit.SECONDS.between(time1, time2);
            }
        }


    }
    /**
     * 返回指定日期 加/减 n天 yyyy-MM-dd 格式日期
     */
    public static String getDiffDate(String dateStr,int days,int type ){
        // dateStr 日期
        LocalDate startDate = LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endDate;
        if(type == 1){ // 加
            endDate = startDate.plusDays(days); // 增加1天
        }else{// 减
            endDate = startDate.minusDays(days); // 减少1天
        }
        return endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    // 当前时间+5分钟 且格式为yyyyMMddHHmmss
    public static String getAfterTime(){
        LocalDateTime now = LocalDateTime.now().plusMinutes(5);
        return now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    }

    /**
     * 获取近六个月日期
     * @return
     */
    public static List<String> recentSixMonths(){
        // 获取当前日期
        LocalDate now = LocalDate.now();
        // 创建一个列表来保存最近六个月的月份
        List<String> months = new ArrayList<>();

        // 循环获取最近六个月的月份
        for (int i = 0; i < 6; i++) {
            YearMonth yearMonth = YearMonth.from(now.minusMonths(i));
            // 将月份格式化为 "yyyy-MM" 格式
            String formattedMonth = yearMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            months.add(formattedMonth);
        }
        // 倒序输出
        Collections.reverse(months);
        // 打印结果
        return months;
    }

    /**
     * 获取近N天的日期列表
     * @param n
     * @return
     */
    public static List<String> generateDateList(int n) {
        return generateDateList(n, "yyyy-MM-dd");
    }

    /**
     * 获取近N天的日期列表
     * @param n
     * @param dateFormat 日期格式
     * @return
     */
    public static List<String> generateDateList(int n, String dateFormat) {
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);

        return IntStream.rangeClosed(1, n)
                .mapToObj(i -> today.minusDays(n - i))
                .map(formatter::format)
                .collect(Collectors.toList())
                .stream()
                .sorted()
                .collect(Collectors.toList());
    }

}
