package com.module.backstage.utils

import android.text.format.Time
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import kotlin.math.abs

object TimeUtil {
    /**
     * 获取当前时间的年月日时分秒
     * @return 字符串
     */
    fun getStrCurTime(): String {
        var time = ""
        val date = System.currentTimeMillis()
        val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val curDate = Date(date)
        time = formatter.format(curDate)
        return time
    }

    /**
     *
     * @param timeMillis
     * @return 指定的时间
     */
    fun getTime(timeMillis: Long): String {
        var time = ""
        val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val curDate = Date(timeMillis)
        time = formatter.format(curDate)
        return time
    };

    /**
     *
     * @param timeMillis
     * @return 指定的没有格式的时间
     */
    fun getNoTime(timeMillis: Long): String {
        var time = ""
        val formatter = SimpleDateFormat("yyyyMMddHHmmss")
        val curDate = Date(timeMillis)
        time = formatter.format(curDate)
        return time
    };

    /**
     *
     * 判断时间相差几天
     * @param startTime
     * @param endTime
     * @param format yyyy-MM-dd
     * @return
     */
    fun dateDiff(startTime: String?, endTime: String?, format: String?): Long {
        // 按照传入的格式生成一个simpledateformate对象
        val sd = SimpleDateFormat(format)
        val nd = (1000 * 24 * 60 * 60).toLong() // 一天的毫秒数
        val nh = (1000 * 60 * 60).toLong() // 一小时的毫秒数
        val nm = (1000 * 60).toLong() // 一分钟的毫秒数
        val ns: Long = 1000 // 一秒钟的毫秒数
        val diff: Long
        var day: Long = 0
        var hour: Long = 0
        var min: Long = 0
        var sec: Long = 0
        try {
            // 获得两个时间的毫秒时间差异
            try {
                diff = (sd.parse(endTime).time
                        - sd.parse(startTime).time)
                day = diff / nd // 计算差多少天
                hour = diff % nd / nh // 计算差多少小时
                min = diff % nd % nh / nm // 计算差多少分钟
                sec = diff % nd % nh % nm / ns // 计算差多少秒
            } catch (e: ParseException) {
                e.printStackTrace()
            }


            // 输出结果
            println(
                "时间相差：" + day + "天" + hour + "小时" + min
                        + "分钟" + sec + "秒。"
            )
            if (day >= 1) {
                return day
            } else {
                if (day == 0L) {
                    return 1
                } else {
                    return 0
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    /**
     * 判断时间大小
     * @param DATE1
     * @param DATE2
     * @return
     */
    fun compare_date(DATE1: String?, DATE2: String?): Boolean {
        val df: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        try {
            val dt1 = df.parse(DATE1)
            val dt2 = df.parse(DATE2)
            if (dt1.time > dt2.time) {
                println("dt1 在dt2前")
                return true
            } else if (dt1.time < dt2.time) {
                println("dt1在dt2后")
                return false
            } else {
                return true
            }
        } catch (exception: Exception) {
            exception.printStackTrace()
        }
        return false
    }

    /**
     * 判断相差几个月
     * @param startTime
     * @param endTime
     */
    fun mouthDiff(startTime: String?, endTime: String?): Int {
        val sdf = SimpleDateFormat("yyyy-MM")
        val str1 = "2012-12"
        val str2 = "2012-01"
        val bef = Calendar.getInstance()
        val aft = Calendar.getInstance()
        try {
            bef.time = sdf.parse(str1)
            aft.time = sdf.parse(str2)
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        val result = aft[Calendar.MONTH] - bef[Calendar.MONTH]
        val month = (aft[Calendar.YEAR] - bef[Calendar.YEAR]) * 12
        return abs((month + result).toDouble()).toInt()
    }

    /**
     * 计算2个日期之间相差的  以年、月、日为单位，各自计算结果是多少
     * 比如：2011-02-02 到  2017-03-02
     * 以年为单位相差为：6年
     * 以月为单位相差为：73个月
     * 以日为单位相差为：2220天
     * @param fromDate
     * @param toDate
     * @return
     */
    fun yearCompare(fromDate: Date?, toDate: Date?): Int {
        val from = Calendar.getInstance()
        from.time = fromDate
        val to = Calendar.getInstance()
        to.time = toDate
        //只要年月
        val fromYear = from[Calendar.YEAR]
        val fromMonth = from[Calendar.MONTH]

        val toYear = to[Calendar.YEAR]
        val toMonth = to[Calendar.MONTH]

        val year = toYear - fromYear
        val month = toYear * 12 + toMonth - (fromYear * 12 + fromMonth)
        val day = ((to.timeInMillis - from.timeInMillis) / (24 * 3600 * 1000)).toInt()
        return year
    }

    //计算两个日期相差年数
    fun yearDateDiff(startDate: String?, endDate: String?): Int {
        val calBegin = Calendar.getInstance() //获取日历实例
        val calEnd = Calendar.getInstance()
        if (stringTodate(startDate, "yyyy") == null || stringTodate(startDate, "yyyy") == null) {
            return -100
        }
        calBegin.time = stringTodate(startDate, "yyyy") //字符串按照指定格式转化为日期
        calEnd.time = stringTodate(endDate, "yyyy")
        return calEnd[Calendar.YEAR] - calBegin[Calendar.YEAR]
    }

    //字符串按照指定格式转化为日期
    fun stringTodate(dateStr: String?, formatStr: String?): Date? {
        // 如果时间为空则默认当前时间
        var date: Date? = null
        val format = SimpleDateFormat(formatStr)
        if (dateStr != null && dateStr != "") {
            var time: String? = ""
            try {
                val dateTwo = format.parse(dateStr)
                time = format.format(dateTwo)
                date = format.parse(time)
            } catch (e: ParseException) {
                e.printStackTrace()
            }
        } else {
            val timeTwo = format.format(Date())
            try {
                date = format.parse(timeTwo)
            } catch (e: ParseException) {
                e.printStackTrace()
            }
        }
        return date
    }


    /**
     * 判断当前系统时间是否在指定时间的范围内
     *
     * @param beginHour
     * 开始小时，例如22
     * @param beginMin
     * 开始小时的分钟数，例如30
     * @param endHour
     * 结束小时，例如 8
     * @param endMin
     * 结束小时的分钟数，例如0
     * @return true表示在范围内，否则false
     */
    fun isCurrentInTimeScope(beginHour: Int, beginMin: Int, endHour: Int, endMin: Int): Boolean {
        var result = false
        val aDayInMillis = (1000 * 60 * 60 * 24).toLong()
        val currentTimeMillis = System.currentTimeMillis()

        val now = Time()
        now.set(currentTimeMillis)

        val startTime = Time()
        startTime.set(currentTimeMillis)
        startTime.hour = beginHour
        startTime.minute = beginMin

        val endTime = Time()
        endTime.set(currentTimeMillis)
        endTime.hour = endHour
        endTime.minute = endMin

        if (!startTime.before(endTime)) {
// 跨天的特殊情况（比如22:00-8:00）
            startTime.set(startTime.toMillis(true) - aDayInMillis)
            result = !now.before(startTime) && !now.after(endTime) // startTime <= now <= endTime
            val startTimeInThisDay = Time()
            startTimeInThisDay.set(startTime.toMillis(true) + aDayInMillis)
            if (!now.before(startTimeInThisDay)) {
                result = true
            }
        } else {
// 普通情况(比如 8:00 - 14:00)
            result = !now.before(startTime) && !now.after(endTime) // startTime <= now <= endTime
        }
        return result
    }

//    fun getDur(time: Int): String {
//        var text = ""
//        val i = time / 60
//        val i1 = time % 60
//        text = i + UiUtil.getStringRes(R.string.minute) + i1 + UiUtil.getStringRes(R.string.second)
//        return text
//    }
}