package com.dayou.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
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.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;

/**
 * 时间工具类
 *
 * @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 YYYYMMDD = "yyyyMMdd";


    public static String EXCELTIME = "yyyy/MM/dd";

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

    public static String MM_DD_C = "MM月dd日";
    public static String YYYY_MM_DD_C = "yyyy年MM月dd日";
    public static String HH_MM_SS = "HH:mm:ss";
    public static String TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    public static String YYYY_MM_C = "yyyy年MM月";
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyyMMdd",
            "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 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) {
        if (date == null) {
            return null;
        }
        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 LocalDateTime parseLocalDateTime(Object str) {
        if (str == null) {
            return null;
        }
        for (String parsePattern : parsePatterns) {
            try {
                LocalDateTime localDateTime = DateUtil.parseLocalDateTime((CharSequence) str, parsePattern);
                return localDateTime;
            } catch (Exception e) {
                continue;
            }
        }
        return null;
    }

    public static LocalDate parseLocalDate(Object str) {
        if (str == null) {
            return null;
        }
        for (String parsePattern : parsePatterns) {
            try {
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(parsePattern);
                LocalDate parse = LocalDate.parse((CharSequence) str, dateTimeFormatter);
                return parse;
            } catch (Exception e) {
                continue;
            }
        }
        return null;
    }

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

    /**
     * 计算两个时间差
     */
    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 + "分钟";
    }

    /**
     * 计算两个时间差(只返回 天数)
     */
    public static Long getDatePoorOnlyDay(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;
    }

    /**
     * 计算两个时间段的交集天数
     * @param aStartTime
     * @param aEndTime
     * @param bStartTime
     * @param bEndTime
     * @return
     */
    public static Long getTwoPeriodBeMixed(Date aStartTime,Date aEndTime,Date bStartTime,Date bEndTime){

        if (aEndTime.getTime()>=bStartTime.getTime() && bStartTime.getTime()>=aStartTime.getTime()
                && aEndTime.getTime()<=bEndTime.getTime() && bStartTime.getTime()<=aEndTime.getTime()){
            return getDatePoorOnlyDay(aEndTime,bStartTime);
        }
        if (bEndTime.getTime()>=aEndTime.getTime() && aStartTime.getTime()>=bStartTime.getTime()){
            return getDatePoorOnlyDay(aEndTime,aStartTime);
        }
        if (bEndTime.getTime()<=aEndTime.getTime() && aStartTime.getTime()<=bStartTime.getTime()){
            return getDatePoorOnlyDay(bEndTime,bStartTime);
        }
        if (aStartTime.getTime()>=bStartTime.getTime() && aStartTime.getTime()<=bEndTime.getTime()
                && bEndTime.getTime()>=aStartTime.getTime() && bEndTime.getTime()<=aEndTime.getTime()){
            return getDatePoorOnlyDay(bEndTime,aStartTime);
        }
        return 0l;
    }

    public static int getYear(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.YEAR);
    }

    public static int getMonth(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.MONTH) + 1;
    }

    // 获得上个月第一天0点时间
    public static Date getLastMonthStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH,-1);
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.getActualMinimum(Calendar.DAY_OF_MONTH), 0, 0, 0);
        return cal.getTime();
    }

    // 获得上个月最后一天24点时间
    public static Date getLastMonthEnd() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH,-1);
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.getActualMaximum(Calendar.DAY_OF_MONTH), 23, 59, 59);
        return cal.getTime();
    }

    public static LocalDate getLastMonth23(int year,int month){

        Calendar cal = Calendar.getInstance();
        cal.set(year,month,1);
        Date date = cal.getTime();
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date);
        cal1.add(Calendar.MONTH,-1);
        cal1.set(Calendar.DAY_OF_MONTH,23);
        LocalDate last23Date = dateToLocalDate(cal1.getTime());
        return last23Date;
    }



    // 获得本月第一天0点时间
    public static Date getCurMonthStart() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        return cal.getTime();
    }

    // 获得本月最后一天24点时间
    public static Date getCurMonthEnd() {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        return cal.getTime();
    }

    //获取某个日期的开始时间
    public static Date getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
                0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    //获取某个日期的结束时间
    public static Date getDayEndTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
                23, 59, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * LocalDateTime转换为Date
     *
     * @param localDateTime
     */
    public static Date localDateTime2Date(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a  ZonedDateTime.
        Date date = Date.from(zdt.toInstant());
        return date;
    }


    //增加天数
    public static Date addDay(Date d, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.DAY_OF_YEAR, day);
        return calendar.getTime();
    }



    //增加分钟
    public static Date addMinute(Date d, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.MINUTE, minute);
        return calendar.getTime();
    }

    //增加秒
    public static Date addSecond(Date d, int seconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.SECOND, seconds);
        return calendar.getTime();
    }

    public static int compTime(String s1, String s2) {
        if (s1.indexOf(":") < 0 || s1.indexOf(":") < 0) {
            throw new IllegalArgumentException("spliter not found");
        } else {
            String[] array1 = s1.split(":");
            int total1 =
                    Integer.valueOf(array1[0]) * 3600 + Integer.valueOf(array1[1]) * 60 + Integer.valueOf(array1[2]);
            String[] array2 = s2.split(":");
            int total2 =
                    Integer.valueOf(array2[0]) * 3600 + Integer.valueOf(array2[1]) * 60 + Integer.valueOf(array2[2]);
            return total1 - total2;
        }

    }

    public static long getHourInterval(Date start, Date end) {
        long hour = (end.getTime() - start.getTime()) / (1000 * 60 * 60);
        return hour;
    }

    public static String format(LocalDate date, String format) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(format);
        String dateStr = date.format(fmt);
        return dateStr;
    }

    public static String format(LocalDateTime date, String format) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern(format);
        String dateStr = date.format(fmt);
        return dateStr;
    }

    /**
     * 获取某月份的所有日期
     * @param date
     * @return
     */
    public static List<Date> getAllTheDateOftheMonth(Date date) {
        List<Date> list = new ArrayList<Date>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DATE, 1);

        int month = cal.get(Calendar.MONTH);
        while(cal.get(Calendar.MONTH) == month){
            list.add(cal.getTime());
            cal.add(Calendar.DATE, 1);
        }
        return list;
    }

    /**
     * 返回两个日期之间的所有日期
     * @param start
     * @param end
     * @return
     */
    public static List<Date> getBetweenDates(Date start, Date end) {
        List<Date> result = new ArrayList<Date>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        while (tempStart.before(tempEnd)) {
            result.add(tempStart.getTime());
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }

    /**
     * Date类型转LocalDate类型
     * @param date
     * @return
     */
    public static LocalDate dateToLocalDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localPriceDate = instant.atZone(zoneId).toLocalDate();
        return localPriceDate;
    }

    /**
     * LocalDate类型转Date类型
     * @param localDate
     * @return Date
     */
    public static Date localDateToDate(LocalDate localDate) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
        Date date = Date.from(zdt.toInstant());
        return date;
    }

    /**
     * 计算两个时间差(天数)
     */
    public static long getDatePoorDay(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long diff = endDate.getTime() - nowDate.getTime();
        long day = diff / nd;
        return day ;
    }

    public static String  getTimeLong(long time){
        long hour = time/(60*60*1000);
        long minute = (time - hour*60*60*1000)/(60*1000);
        long second = (time - hour*60*60*1000 - minute*60*1000)/1000;
        return hour+ "时" + minute + "分" + second+"秒";
    }

    public static String tzTime2ChineseYM(String tzDateTime){
        try {
            return format(LocalDateTime.parse(tzDateTime, DateTimeFormatter.ofPattern(TZ)), YYYY_MM_C);
        } catch (Exception e) {
            return null;
        }
    }

    public static Boolean checkIsDate(String chineseDate){
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM_DD_C);
            simpleDateFormat.parse(chineseDate);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
//    public static void main(String[]agrs){
//        Boolean aBoolean = checkIsDate("2024年年032月22日");
//    }
    /**
     * 月份差
     * @param startTime
     * @param endTime
     * @return
     */
    public static int currentMonth(Date startTime,Date endTime){
        int sYear = startTime.getYear();
        int eYear = endTime.getYear();
        int sMonth = startTime.getMonth();
        int eMonth = endTime.getMonth();
        if (sYear==eYear){
            return eMonth-sMonth;
        }
        return (eYear-sYear)*12 + (eMonth-sMonth);
    }


}
