package com.boman.common.core.utils;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

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 YYYYMM = "yyyyMM";

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

    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 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 formatDate(String dateStr) {
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        try {
            return format.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String formatString(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        return format.format(date);
    }

    /**
     * 根据时间+多少天
     *
     * @param date
     * @param i
     * @return
     */
    public static Date addDayOfDate(Date date, int i) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, i);
        Date newDate = c.getTime();
        return newDate;
    }

    /**
     * 根据时间-日期
     *
     * @param i
     * @return
     */
    public static String minusDayOfDate(int i) {
        LocalDateTime today = LocalDateTime.now();
        LocalDateTime localDateTime = today.minusDays(i);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(formatter);
    }

    /**
     * 根据时间+10分钟
     *
     * @return
     */
    public static String plusSeconds(String dateTime, int seconds) {
        LocalDateTime parse = parse(dateTime, "yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = parse.plusMinutes(seconds);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(formatter);
    }

    /**
     * String转LocalDateTime
     *
     * @param str
     * @param format
     * @return
     */
    public static LocalDateTime parse(String str, String format) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(str, df);
    }

    /**
     * 当天的开始时间
     */
    public static Date getTodayStart() {
        String time = getDate() + " 00:00:00";
        return strToDate(time, YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 当天的开始时间
     */
    public static String getTodayStartStr() {
        return getDate() + " 00:00:00";
    }

    public static String setHmsZero(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.setTime(date);
        return dateTime(calendar.getTime());
    }


    /**
     * 当天的开始时间
     */
    public static String getTodayEndStr() {
        return getDate() + " 23:59:59";
    }

    public static Date addDay(Date date, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);
        return calendar.getTime();
    }


    /**
     * 指定日期的的开始时间
     */
    public static Date getDayStartFromTime(String time) {
        return strToDate(time + " 00:00:00", YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 指定日期的的结束时间
     */
    public static Date getDayEndFromTime(String time) {
        return strToDate(time + " 23:59:59", YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 当天的结束时间
     */
    public static Date getTodayEnd() {
        String time = getDate() + " 23:59:59";
        return strToDate(time, YYYY_MM_DD_HH_MM_SS);
    }

    public static Date strToDate(String strDate, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        ParsePosition pos = new ParsePosition(0);
        return formatter.parse(strDate, pos);
    }

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

    public static String getYear() {
        return dateTimeNow(YYYY);
    }

    public static long calcMinutes(Date before, Date after) {
        long beforeTime = before.getTime(), afterTime = after.getTime();
        return (afterTime - beforeTime) / 1000 / 60;
    }

    public static long calcDays(Date before, Date after) {
        long beforeTime = before.getTime(), afterTime = after.getTime();
        return (afterTime - beforeTime) / 1000 / 60 / 60 / 24;
    }


    public static String getMonth() {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH) + 1;
        return month < 10 ? "0" + month : month + "";
    }

    public static String getFirstDayOfYearStr() {
        return getYear() + "-01-01 00:00:00";
    }

    public static String getFirstDayOfMonthStr() {
        return getYear() + "-01 00:00:00";
    }

    public static Date getFirstDayOfMonth() {
        String str = getFirstDayOfMonthStr();
        return dateTime(YYYY_MM_DD_HH_MM_SS, str);
    }

    public static String getLastDayOfMonthStr() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, 1);
        calendar.roll(Calendar.DATE, -1);
        return dateTime(calendar.getTime()) + " 23:59:59";
    }

    public static String getLastDayOfMonthStr(String yyyy) {
        String re = getLastDayOfMonthStr();
        re = re.substring(4);
        return yyyy + re;
    }


    public static Date getLastDayOfMonth() {
        String str = getLastDayOfMonthStr();
        return dateTime(YYYY_MM_DD_HH_MM_SS, str);
    }


    public static String getLastDayOfYearStr() {
        return getYyyy_Mm() + "-12-31 23:59:59";
    }

    public static int dayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    public static final String getYyyyMm() {
        return dateTimeNow(YYYYMM);
    }

    public static final String getYyyy_Mm() {
        return dateTimeNow(YYYY_MM);
    }


    public static final String getYyyyMmDd() {
        return dateTimeNow(YYYYMMDD);
    }

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

    public static final String getTime1(final Date date) {

        return dateTime1(date);
    }

    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 dateTime1(final Date date) {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS, 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");
    }

    /**
     * 时间转月-日
     *
     * @param date
     * @return
     */
    public static final String dateToMMdd(Date date) {
        return DateFormatUtils.format(date, "MM-dd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    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 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 + "分钟";
    }

    /**
     * 获取两个日期之间所有日期
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
        long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate) + 1;
        return IntStream.iterate(0, i -> i + 1).limit(numOfDaysBetween).mapToObj(startDate::plusDays).collect(Collectors.toList());
    }

    /**
     * 时间戳转换日期
     *
     * @param stamp
     * @return
     */
    public static String stampToTime(String stamp) {
        return new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(stamp)));
    }

    /**
     * 功能描述: 获取当前月份的第一天到当天
     *
     * @return java.lang.String
     */
    public static List<String> getMonthDays() {
        List<String> result = new ArrayList<>(31);
        Calendar cd = Calendar.getInstance();
        int year = cd.get(Calendar.YEAR);
        int month = cd.get(Calendar.MONTH);
        int day;

        String today = getDate();
        int[] monDays = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        if (((year) % 4 == 0 && (year) % 100 != 0) || (year) % 400 == 0) {
            day = monDays[month]++;
        } else {
            day = monDays[month];
        }

        for (int i = 1; i <= day; i++) {
            String m;
            if (month < 10) {
                m = "0" + (month + 1) + "";
            } else {
                m = month + 1 + "";
            }

            String d;
            if (i < 10) {
                d = "0" + i + "";
            } else {
                d = i + "";
            }

            String time = year + "-" + m + "-" + d;
            if (today.equals(time)) {
                result.add(time);
                break;
            }

            result.add(time);
        }

        return result;
    }

    public static int getWeekMonthYear(int type) {
        Calendar calendar = Calendar.getInstance();
        Date today = new Date();
        calendar.setTime(today);
        int typeNo = calendar.get(type);
        if (type == Calendar.WEEK_OF_MONTH) {
            if (typeNo == 1) {
                typeNo = 7;
            } else {
                typeNo = typeNo - 1;
            }
        }

        return typeNo;
    }


    /**
     * 获取某年某月每一天日期
     *
     * @return
     */
    public static List<String> getMonthEveryDays(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        List<String> arr = new ArrayList<>();
        try {
            Date parse = simpleDateFormat.parse(date);
            Calendar c = Calendar.getInstance();
            c.setTime(parse);
            int year = c.get(Calendar.YEAR);
            int monthInt = c.get(Calendar.MONTH) + 1;
            int num = getDaysByYearMonth(year, monthInt);
            for (int i = 1; i <= num; i++) {
                String day = String.valueOf(i);
                if (i < 10) {
                    day = "0" + i;
                }
                String month = String.valueOf(monthInt);
                if (monthInt < 10) {
                    month = "0" + monthInt;
                }
                arr.add(year + "-" + month + "-" + day);
            }
            return arr;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据年 月 获取对应的月份 天数
     */
    public static int getDaysByYearMonth(int year, int month) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    public static List<Date> getWeek(Date startTimeDate) {
        if (null == startTimeDate) return Collections.emptyList();
        List<Date> weeks = new ArrayList<>(7);
        weeks.add(addDay(startTimeDate, -6));
        weeks.add(addDay(startTimeDate, -5));
        weeks.add(addDay(startTimeDate, -4));
        weeks.add(addDay(startTimeDate, -3));
        weeks.add(addDay(startTimeDate, -2));
        weeks.add(addDay(startTimeDate, -1));
        weeks.add(startTimeDate);
        return weeks;
    }

    /**
     * 根据日期计算年龄
     *
     * @param birthDay
     * @return
     * @throws Exception
     */
    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }


    public static String checkDate(String str) {
        String format1 = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date(str);
            format1 = format.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return format1;
    }
}
