package com.gingersoft.gsa.cloud.base.utils.time;

import android.text.TextUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import timber.log.Timber;

/**
 * @ClassName: TimeUtils
 * @Description: TODO(时间工具类)
 */
public class TimeUtils {
    public static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//, Locale.CHINESE
    public static final SimpleDateFormat DATE_FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");
    public static final SimpleDateFormat DATE_FORMAT_DATE1 = new SimpleDateFormat("HH:mm");
    public static final SimpleDateFormat DEFAULT_DATE_MDHM = new SimpleDateFormat("MM-dd HH:mm");//, Locale.CHINESE
    public static final SimpleDateFormat DEFAULT_DATE_MD = new SimpleDateFormat("MM-dd");
    public static final SimpleDateFormat DEFAULT_DATE_Y = new SimpleDateFormat("yyyy-");
    public static final SimpleDateFormat DATE_Y = new SimpleDateFormat("yyyy");

    /**
     * 獲得今年第一天的日期
     * cal.set(Calendar.DAY_OF_YEAR, cal.getActualMinimum(Calendar.DAY_OF_YEAR));
     * 獲得今年最後一天的日期
     * cal.set(Calendar.DAY_OF_YEAR, cal.getActualMaximum(Calendar.DAY_OF_YEAR));
     *
     */

    /**
     * 时间日期格式化到年月日时分秒.
     */
    public static String dateFormatYMDHMS = "yyyy-MM-dd HH:mm:ss";
    public static String dateFormatYMDHMS_f = "yyyyMMddHHmmss";
    public static String dateFormatMDHM = "MM-dd HH:mm";
    public static String dateFormat = "yyyy-MM-dd HH:mm";
    /**
     * 时间日期格式化到年月日.
     */
    public static String dateFormatYMD = "yyyy-MM-dd";
    /**
     * 时分秒.
     */
    public static String dateFormatHMS = "HH:mm:ss";

    /**
     * 时分.
     */
    public static String dateFormatHM = "HH:mm";

    /**
     * 上午/下午时分
     */
    public static String dateFormatAHM = "aHH:mm";

    public static SimpleDateFormat dateFormatYMDE = new SimpleDateFormat("yyyy/MM/dd E");//, Locale.TRADITIONAL_CHINESE
    public static String dateFormatYMD2 = "yyyy/MM/dd";

    private TimeUtils() {
        throw new AssertionError();
    }

    public static String getFormatTime(String time, SimpleDateFormat simpleDateFormat) {
        return simpleDateFormat.format(new Date(time));
    }

    public static String getYesterdayTime(SimpleDateFormat simpleDateFormat) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -1);//往上推一天
        return simpleDateFormat.format(calendar.getTime());
    }

    public static String getTime(Date date) {//可根据需要自行截取数据显示
        return DATE_FORMAT_DATE.format(date);
    }

    /**
     * long time to string
     *
     * @param timeInMillis
     * @param dateFormat
     * @return
     */
    public static String getTime(long timeInMillis, SimpleDateFormat dateFormat) {
        return dateFormat.format(new Date(timeInMillis));
    }

    /**
     * long time to string, format is {@link #DEFAULT_DATE_FORMAT}
     *
     * @param timeInMillis
     * @return
     */
    public static String getCurrentTime(long timeInMillis) {
        return getTime(timeInMillis, DEFAULT_DATE_FORMAT);
    }

    /**
     * get current time in milliseconds
     *
     * @return
     */
    public static long getCurrentTimeInLong() {
        return System.currentTimeMillis();
    }

    /**
     * get current time in milliseconds
     *
     * @return
     */
    public static String getCurrentTimeInString(SimpleDateFormat dateFormat) {
        return getTime(getCurrentTimeInLong(), dateFormat);
    }


    /**
     * @param distance 差距： 昨天天傳負一，今天傳零，明天傳一
     * @param type     類型： 1、天 Calendar.DATE  2、年Calendar.YEAR 3、月Calendar.MONTH
     * @param sf       {@link #DEFAULT_DATE_MD}
     * @return
     */
    public static String getDistanceDate(int distance, int type, SimpleDateFormat sf) {
        Date beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        date.set(type, date.get(type) + distance);
        Date endDate = null;
        try {
            endDate = sf.parse(sf.format(date.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sf.format(endDate);
    }

    /**
     * 获取前n天日期、后n天日期
     *
     * @param distanceDay 前几天 如获取前7天日期则传-7即可；如果后7天则传7
     * @return
     */
    public static String getOldDate(int distanceDay) {
        return getDistanceDate(distanceDay, Calendar.DATE, DATE_FORMAT_DATE);
    }

    /**
     * 获取前n年日期、后n年日期
     *
     * @param distanceYear 前几年 如获取前7年日期则传-7即可；如果后7年则传7
     * @return
     */
    public static String getYear(int distanceYear) {
        return getDistanceDate(distanceYear, Calendar.YEAR, DATE_FORMAT_DATE);
    }

    /**
     * 获取前n月日期、后n月日期
     *
     * @param distanceMonth 前几月 如获取前7月日期则传-7即可；如果后7月则传7
     * @return
     */
    public static String getDistanceMonth(int distanceMonth) {
        return getDistanceDate(distanceMonth, Calendar.YEAR, DATE_FORMAT_DATE);
    }

    /**
     * 把日期型字符串转换为数字型字符串
     *
     * @param time
     * @return
     */
    public static String tranTime(String time) {
        if (time != null) {
            String year;
            String month;
            String day;
            String hour;
            String minute;
            String second;
            year = time.substring(0, 4);
            month = time.substring(5, 7);
            day = time.substring(8, 10);
            hour = time.substring(11, 13);
            minute = time.substring(14, 16);
            second = time.substring(17, 19);
            String newTime = String.format("%s%s%s%s%s%s", year, month, day,
                    hour, minute, second);
            return newTime;
        } else
            return time;
    }

    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    public static Date StrToDate(String str) {
        Date date = null;
        try {
            date = DEFAULT_DATE_FORMAT.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 把日期转为字符串
     *
     * @param date
     * @return
     * @Title: ConverToString
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public static String ConverToString(Date date) {
        return DATE_FORMAT_DATE1.format(date);
    }

    /**
     * 日期转换成秒数
     */
    public static long getSecondsFromDate(String expireDate) {
        if (expireDate == null || expireDate.trim().equals(""))
            return 0;
        Date date = null;
        try {
            date = DEFAULT_DATE_FORMAT.parse(expireDate);
            return (long) (date.getTime() / 1000);
        } catch (ParseException e) {
            e.printStackTrace();
            return 0L;
        }
    }
//
//    /**
//     * 时间戳格式转换
//     */
//    static String dayNames[] = {app.getString(R.string.sunday), app.getString(R.string.monday),
//            app.getString(R.string.tuesday), app.getString(R.string.wednesday), app.getString(R.string.thursday),
//            app.getString(R.string.friday), app.getString(R.string.saturday)};
//
//    public static String getNewChatTime(long timesamp) {
//        String result = "";
//        Calendar todayCalendar = Calendar.getInstance();
//        Calendar otherCalendar = Calendar.getInstance();
//        otherCalendar.setTimeInMillis(timesamp);
//        String timeFormat = "M" + app.getString(R.string.month) + "d" + app.getString(R.string.day) + " " + "HH:mm";
//        String yearTimeFormat = "yyyy" + app.getString(R.string.year) + "M" + app.getString(R.string.month) + "d" + app.getString(R.string.day) + " " + "HH:mm";
//        String am_pm = "";
//        int hour = otherCalendar.get(Calendar.HOUR_OF_DAY);
//        if (hour >= 0 && hour < 6) {
//            am_pm = app.getString(R.string.early_morning);
//        } else if (hour >= 6 && hour < 12) {
//            am_pm = app.getString(R.string.morning);
//        } else if (hour == 12) {
//            am_pm = app.getString(R.string.noon);
//        } else if (hour > 12 && hour < 18) {
//            am_pm = app.getString(R.string.afternoon);
//        } else if (hour >= 18) {
//            am_pm = app.getString(R.string.at_night);
//        }
//        timeFormat = "M" + app.getString(R.string.month) + "d" + app.getString(R.string.day) + " " + am_pm + "HH:mm";
//        yearTimeFormat = "yyyy" + app.getString(R.string.year) + "M" + app.getString(R.string.month) + "d" + app.getString(R.string.day) + " " + am_pm + "HH:mm";
//
//        boolean yearTemp = todayCalendar.get(Calendar.YEAR) == otherCalendar.get(Calendar.YEAR);
//        if (yearTemp) {
//            int todayMonth = todayCalendar.get(Calendar.MONTH);
//            int otherMonth = otherCalendar.get(Calendar.MONTH);
//            if (todayMonth == otherMonth) {//表示是同一个月
//                int temp = todayCalendar.get(Calendar.DATE) - otherCalendar.get(Calendar.DATE);
//                switch (temp) {
//                    case 0:
//                        result = am_pm + " " + getHourAndMin(timesamp);
//                        break;
//                    case 1:
//                        result = app.getString(R.string.yesterday) + " " + am_pm + " " + getHourAndMin(timesamp);
//                        break;
//                    case 2:
//                    case 3:
//                    case 4:
//                    case 5:
//                    case 6:
//                        int dayOfMonth = otherCalendar.get(Calendar.WEEK_OF_MONTH);
//                        int todayOfMonth = todayCalendar.get(Calendar.WEEK_OF_MONTH);
//                        if (dayOfMonth == todayOfMonth) {//表示是同一周
////							int dayOfWeek=otherCalendar.get(Calendar.DAY_OF_WEEK);
////							if(dayOfWeek!=1){//判断当前是不是星期日     如想显示为：周日 12:09 可去掉此判断
//                            result = dayNames[otherCalendar.get(Calendar.DAY_OF_WEEK) - 1] + " " + am_pm + " " + getHourAndMin(timesamp);
////							}else{
////								result = getTime(timesamp,timeFormat);
////							}
//                        } else {
//                            result = getTime(timesamp, timeFormat);
//                        }
//                        break;
//                    default:
//                        result = getTime(timesamp, timeFormat);
//                        break;
//                }
//            } else {
//                result = getTime(timesamp, timeFormat);
//            }
//        } else {
//            result = getYearTime(timesamp, yearTimeFormat);
//        }
//        return result;
//    }

    /**
     * 当天的显示时间格式
     *
     * @param time
     * @return
     */
    public static String getHourAndMin(long time) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        return format.format(new Date(time));
    }

    /**
     * 不同一周的显示时间格式
     *
     * @param time
     * @param timeFormat
     * @return
     */
    public static String getTime(long time, String timeFormat) {
        SimpleDateFormat format = new SimpleDateFormat(timeFormat);
        return format.format(new Date(time));
    }

    /**
     * 不同年的显示时间格式
     *
     * @param time
     * @param yearTimeFormat
     * @return
     */
    public static String getYearTime(long time, String yearTimeFormat) {
        SimpleDateFormat format = new SimpleDateFormat(yearTimeFormat);
        return format.format(new Date(time));
    }

    /**
     * 描述：获取milliseconds表示的日期时间的字符串.
     *
     * @param format 格式化字符串，如："yyyy-MM-dd HH:mm:ss"
     * @return String 日期时间字符串
     */
    public static String getStringByFormat(long milliseconds, String format) {
        String thisDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            thisDateTime = mSimpleDateFormat.format(milliseconds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return thisDateTime;
    }

    /**
     * 描述：获取表示当前日期时间的字符串.
     *
     * @param format 格式化字符串，如："yyyy-MM-dd HH:mm:ss"
     * @return String String类型的当前日期时间
     */
    public static String getCurrentDate(String format) {
        String curDateTime = null;
        try {
            SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
            Calendar c = new GregorianCalendar();
            curDateTime = mSimpleDateFormat.format(c.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curDateTime;
    }

    /**
     * 区分白天还是夜晚
     *
     * @param time
     * @return
     */
    public static boolean getDuringOrNight(String time) {

        String before = formatDate(time, "yyyy-MM-dd HH:mm:ss", "HH");
        int k = Integer.parseInt(before);

        if ((k >= 0 && k < 6) || (k >= 18 && k < 24)) {
            return true;
        } else {
            return false;
        }
    }

    /***
     * from yyyy-MM-dd HH:mm:ss to MM-dd HH:mm
     * @param before 之前的时间
     * @param beforeformat 之前的时间格式
     * @param afterformat  之后的时间格式
     * @return
     */
    public static String formatDate(String before, String beforeformat, String afterformat) {
        String after;
        try {
            Date date = new SimpleDateFormat(beforeformat, Locale.getDefault())
                    .parse(before);
            after = new SimpleDateFormat(afterformat, Locale.getDefault()).format(date);
        } catch (ParseException e) {
            return before;
        }
        return after;
    }

    public static Date parseServerTime(String serverTime, String format) {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINESE);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
            date = sdf.parse(serverTime);
        } catch (Exception e) {
            Timber.e(e, "");
        }
        return date;
    }

    /**
     *
     * @param time
     * @param dateFormat
     * @return
     */
    public static String parseTimeRepeat(String time, SimpleDateFormat dateFormat) {
        Date date = null;
        if(TextUtils.isEmpty(time)){
            return "";
        }
        try {
            date = new Date(time);
        } catch (IllegalArgumentException e) {
//            e.printStackTrace();
            try {
                date = dateFormat.parse(time);
            } catch (ParseException ex) {
//                ex.printStackTrace();
            }
        }
        if (date != null) {
            return dateFormat.format(date);
        }
        return time;
    }
}
