package com.ruixuan.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.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    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 String getNowDateStr() {
        SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd");
        return simp.format(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) {
        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 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());
    }


    /**
     * 时间字符串转long类型
     * 2022-05-01 ===>>>> 20220501
     *
     * @param date
     * @return
     */
    public static Long strDateToInt(String date) {

        return Long.valueOf(date.replaceAll("-", ""));
    }

    /**
     * 时间字符串转long类型
     * 2022-05-01 00:00:00 ===>>>> 20220501
     *
     * @param date
     * @return
     */
    public static Long strDateTimsToInt(String date) {
        String[] datas = date.split(" ");
        return Long.valueOf(datas[0].replaceAll("-", ""));
    }


    /**
     * @param
     * @description: 获取当前周的开始和截至时间
     * @return: java.util.Map
     * @author: zianY
     * @time: 2022/6/1
     */
    public static Map getWeekBeginAndEnd() {
        Map<String, String> timeMap = new HashMap<>();
        String begin = parseDateToStr(YYYY_MM_DD, getBeginDayOfWeek());
        String end = parseDateToStr(YYYY_MM_DD, getEendDayOfWeek());
        timeMap.put("begin", begin + " 00:00:00");
        timeMap.put("end", end + " 23:59:59");
        return timeMap;
    }


    /**
     * @param
     * @description: 获取本周开始时间
     * @return: java.util.Date
     * @author: zianY
     * @time: 2022/6/1
     */
    public static Date getBeginDayOfWeek() {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            dayOfWeek += 7;
        }
        cal.add(Calendar.DATE, 2 - dayOfWeek);
        return cal.getTime();
    }

    /**
     * @param
     * @description: 获取本周结束时间
     * @return: java.util.Date
     * @author: zianY
     * @time: 2022/6/1
     */
    public static Date getEendDayOfWeek() {

        Calendar cal = Calendar.getInstance();
        cal.setTime(getBeginDayOfWeek());
        cal.add(Calendar.DAY_OF_WEEK, 6);
        return cal.getTime();
    }

    /**
     * 指定模式的时间格式
     */
    private static SimpleDateFormat getSDFormat(String pattern) {
        return new SimpleDateFormat(pattern);
    }

    /**
     * 指定日期按指定格式显示
     */
    public static String formatDate(Date date, String pattern) {
        return getSDFormat(pattern).format(date);
    }


    /**
     * 日期转换为时间戳
     */
    public static long timeToStamp(String timers) {
        Date d = new Date();
        long timeStemp = 0;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 日期转换为时间戳
            d = sf.parse(timers);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        timeStemp = d.getTime();
        return timeStemp;
    }

    /**
     * 时间戳转换为字符串
     *
     * @param time
     * @return
     */
    public static String timestamptoStr(Long timestamp) {
        Date date = new Date();
        date.setTime(timestamp);
        return DateFormatUtils.format(date, YYYYMMDD);
    }


    /**
     * 返回 日期-天数 的string 日期
     *
     * @param time        时间
     * @param daysBetween 天数
     * @return
     */
    public static String getSubtractTime(Date time, Integer daysBetween) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(time);
        if (daysBetween.intValue() > 0) {
            rightNow.add(Calendar.DAY_OF_YEAR, -daysBetween.intValue());
        } else {
            rightNow.add(Calendar.DAY_OF_YEAR, -1);//日期 -1
        }
        Date rightNowTime = rightNow.getTime();
        String nowTime = sdf.format(rightNowTime);
        return nowTime;
    }


    /**
     * 根据时间获取季度
     * 1即Q1（1，2，3月），以此类推
     *
     * @param date
     * @return
     */
    public static int getQuarter(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //获取当前月份
        int month = cal.get(Calendar.MONTH) + 1;
        if (month <= 3) {
            return 1;
        } else if (month <= 6) {
            return 2;
        } else if (month <= 9) {
            return 3;
        } else if (month <= 12) {
            return 4;
        }

        return 0;
    }


    public static Long getStartLongTime(String orderStartDate) {
        String date = orderStartDate + " 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long orderCreateTimeStart = null;
        try {
            orderCreateTimeStart = sdf.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return orderCreateTimeStart;
    }


    public static Integer getIntegerTime(String date) {
        String replace = date.replace("-", "");
        return Integer.valueOf(replace);
    }


    public static Long getEndLongTime(String orderEndDate) {
        String date = orderEndDate + " 23:59:59";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long orderCreateTimeEnd = null;
        try {
            orderCreateTimeEnd = sdf.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return orderCreateTimeEnd;
    }

    public static Integer getNowHour() {
        Calendar cal = Calendar.getInstance();
        Date date = new Date();
        cal.setTime(date);
        return cal.get(Calendar.HOUR_OF_DAY);
    }

    public static String getAnotherDay(String format, String date, Integer num) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date getDate = null;
        try {
            getDate = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getDate);
        calendar.add(Calendar.DAY_OF_MONTH, num);
        Date resultDate = calendar.getTime();
        return sdf.format(resultDate);
    }

    public static Long getNowEndHourTemp(String dateStr, Integer hour) {
        String date = dateStr + " " + hour + ":59:59";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long orderCreateTimeEnd = null;
        try {
            orderCreateTimeEnd = sdf.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return orderCreateTimeEnd;
    }

    /**
     * 获取当前月份第一天
     *
     * @return 返回格式：2022-01-19
     */
    public static String getFirstDayByMonth() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        return format.format(c.getTime());
    }

    /**
     * 获取 两个日期之间的所有 日期
     *
     * @param startDate yyyy-MM-dd
     * @param endDate   yyyy-MM-dd
     * @return
     */
    public static List<String> getAllDatesOfTwoTimes(String startDate, String endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<String>();
        try {
            Date dateOne = sdf.parse(startDate);
            Date dateTwo = sdf.parse(endDate);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateOne);

            dateList.add(startDate);
            while (calendar.getTime().before(dateTwo)) {
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                dateList.add(sdf.format(calendar.getTime()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateList;
    }

    public static void main(String[] args) {
        System.out.println(getAllDatesOfTwoTimes("2023-02-01", "2023-02-15"));
    }
}
