package com.bonus.hn.bearing.capacity.backstage.manager.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 时间操作类
 *
 * @author cshu
 */
@SuppressWarnings("deprecation")
public class DateTimeHelper {

    /**
     * 获取当前时间的年份
     *
     * @return
     */
    public static String getNowYear() {
        return format(new Date(), "yyyy");
    }


    /**
     * 获取当前月份
     *
     * @return
     */
    public static String getNowMonths() {
        return format(new Date(), "MM");
    }
    public static String getDay() {
        return format(new Date(), "dd");
    }

    public static String getYear(Date d) {
        int year = d.getYear() + 1900;
        return year + "";
    }

    public static String getMonth(Date d) {
        int month = d.getMonth() + 1;
        return StringHelper.fillPrefixZero(month, 2);
    }

    /**
     * 格式化 时间
     *
     * @param format
     * @return
     */
    public static String format(Date d, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(d);
    }

    public static String format(String str, String format, String disFormat) {
        Date d = parse(str, format);
        return format(d, disFormat);
    }

    /**
     * 格式化 时间
     *
     * @param format
     * @return
     */
    public static String format(Date d, DateFormat format) {
        return format.format(d);
    }

    /**
     * 格式化 时间
     *
     * @param format
     * @return Date
     * @throws ParseException
     */
    public static Date parse(String dateStr, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        try {
            return df.parse(dateStr);
        } catch (ParseException e) {
            return new Date();
        }
    }

    public static Date parse(String dateStr, String format, Date d) {
        try {
            SimpleDateFormat df = new SimpleDateFormat(format);
            return df.parse(dateStr);
        } catch (Exception e) {
            return d;
        }
    }

    /**
     * 解析时间
     *
     * @return Date
     * @throws ParseException
     */
    public static Date parse(String dateStr, DateFormat format)
            throws ParseException {
        return format.parse(dateStr);
    }

    /**
     * 获取当前时间之前的第 i 个月
     * i 表示往前推多少个月
     * @return
     */
    public static String getPrevMonth(int i) {
        return minusMonth(new Date(), i);
    }

    /**
     * 获取当前时间的年月
     *
     * @return
     */
    public static String getNowMonth() {
        return format(new Date(), "yyyy-MM");
    }

    public static String getNowMonth2() {
        return format(new Date(), "yyyyMM");
    }
    /**
     * 当前时间的上一年的年月日
     *
     * @return
     */
    public static String getPrevDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();


        c.setTime(new Date());
        c.add(Calendar.YEAR, -1);
        Date y = c.getTime();
        String year = format.format(y);
        return year;

    }

    /**
     * 获取当前时间的年月日
     *
     * @return
     */
    public static String getNowDate() {
        return format(new Date(), "yyyy-MM-dd");
    }

    /**
     * 获取当前时间的年月日、时分秒
     *
     * @return
     */
    public static String getNowDateToSecond() {
        return format(new Date(), "yyyyMMddHHmmss");
    }

    /**
     * 获取当前为本年的第几周
     */
    public static String getNowWeek() {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        int week = ca.get(Calendar.WEEK_OF_YEAR);
        return format(new Date(), "yyyy") + "-" + week;
    }

    public static String getNowDayHMS() {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        return time;
    }

    /**
     * @return
     */
    public static String minusMonth(Date date, int c) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.MONTH, -c);
            return format(cal.getTime(), df);
        } catch (Exception e) {
            return format(date, df);
        }
    }

    /**
     * @param month
     * @return
     */
    public static String minusMonth(String month, int c) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
            Date date = parse(month, df);

            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.MONTH, -c);

            return format(cal.getTime(), df);
        } catch (Exception e) {
            return month;
        }
    }

    /**
     * @return
     */
    public static Date minus(Date d, int type, int c) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            cal.add(type, -c);
            return cal.getTime();
        } catch (Exception e) {
            return new Date();
        }
    }

    /**
     * 得到前一个月
     *
     * @param month
     * @return
     */
    public static String prevMonth(String month) {
        return minusMonth(month, 1);
    }

    /**
     * 得到前一个月
     *
     * @param month
     * @return
     */
    public static String prevMonth(String month, int c) {
        return minusMonth(month, c);
    }

    public static float duration(String startTime, String stopTime) {
        Date sd = DateTimeHelper.parse(startTime, "yyyy-MM-dd HH:mm");
        long sl = sd.getTime();

        Date ed = DateTimeHelper.parse(stopTime, "yyyy-MM-dd HH:mm");
        long el = ed.getTime();

        float l = el - sl;
        if (l <= 0) {
            l = 0;
        }
        l = l / (1000 * 60);
        return l;
    }

    public static String getStartYearMonthBySeason(String year, int season) {
        switch (season) {
            case 1:
                return getYearMonth(year, "01");
            case 2:
                return getYearMonth(year, "04");
            case 3:
                return getYearMonth(year, "07");
            case 4:
                return getYearMonth(year, "10");
            default:
                return getYearMonth(year, "01");
        }
    }

    private static String getYearMonth(String year, String month) {
        return year + "-" + month;
    }

    public static String getEndYearMonthBySeason(String year, int season) {
        switch (season) {
            case 1:
                return getYearMonth(year, "03");
            case 2:
                return getYearMonth(year, "06");
            case 3:
                return getYearMonth(year, "09");
            case 4:
                return getYearMonth(year, "12");
            default:
                return getYearMonth(year, "03");
        }
    }

    /**
     * 获取当年初始时间
     *
     * @return
     */
    public static String getYearStart() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.DATE, 1);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        return format.format(calendar.getTime());
    }

    /**
     * 获取当前日期周一
     *
     * @return
     */
    public static String getMonday() {
        Calendar cal = Calendar.getInstance(Locale.CHINA);
//      如果当前时间是星期天，则向上移动一天，再取本周的星期一，老外用周日到周六为一周，向前移动一天，则是中国人的本周  
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            cal.add(Calendar.DATE, -1);
        }
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        return sdf1.format(cal.getTime());

    }

    /**
     * 获取当前时间的年月
     *
     * @return
     */
    public static String getYmDate() {
        return format(new Date(), "yyyy-MM");
    }


    /**
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String time) throws ParseException {
        String stap;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取时间的时间戳
        long ts = date.getTime() / 1000;
        stap = String.valueOf(ts);
        return stap;
    }

    /**
     * 将时间戳转换为时间
     */
    public static String stampToDate(String stap) {
        String time;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(stap);
        Date date = new Date(lt * 1000);
        time = simpleDateFormat.format(date);
        return time;
    }

    /**
     * 传入两个时间参数，返回需要的值
     * @param stime
     * @param etime
     * @return
     */
    public static List<String> findDates(String stime, String etime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Date dBegin = sdf.parse(stime);
        Date dEnd = sdf.parse(etime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        return allDate;
    }
    public static List<String> getAllMonth(String stime, String etime){
        YearMonth startYearMonth = YearMonth.parse(stime, DateTimeFormatter.ofPattern("yyyy-MM"));
        YearMonth endYearMonth = YearMonth.parse(etime, DateTimeFormatter.ofPattern("yyyy-MM"));

        List<String> allMonths = new ArrayList<>();

        YearMonth currentYearMonth = startYearMonth;
        while (currentYearMonth.isBefore(endYearMonth) || currentYearMonth.equals(endYearMonth)) {
            String monthString = currentYearMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            allMonths.add(monthString);
            currentYearMonth = currentYearMonth.plusMonths(1);
        }
        return allMonths;
    }
    public static List<String> findDates1(String stime, String etime)
            throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(stime);
        Date dEnd = sdf.parse(etime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        return allDate;
    }

    public static List<String> method(List<String> list) {
        // 新集合
        List<String> newList = new ArrayList<>(list.size());
        list.forEach(i -> {
            if (!newList.contains(i)) { // 如果新集合中不存在则插入
                newList.add(i);
            }
        });
        return newList;
    }

    public static String obtainedFifteenDaysAgo(int amount){
        Date date = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + amount);
        return new SimpleDateFormat("yyyy-MM-dd").format(now.getTime());
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(getNowMonth());
        System.out.println(getPrevMonth(11));
        System.out.println(method(findDates(getPrevMonth(11),getNowMonth())).size());
        System.out.println();
    }

    /**
     * 比较两个时间之间的间隔是否大于两小时   前面时间小   后面时间大
     * @param time
     * @param nowDayHMS
     * @return
     * @throws ParseException
     */
    public static boolean compareTimeOverTwoHours(String time, String nowDayHMS) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date1 = sdf.parse(time);
        Date date2 = sdf.parse(nowDayHMS);

        Instant instant1 = date1.toInstant();
        Instant instant2 = date2.toInstant();

        Duration duration = Duration.between(instant1, instant2);

        if (Math.abs(duration.toHours()) >= 2) {
           return true;
        } else {
            return false;
        }
    }
}
