package com.adealink.weparty.util

import android.annotation.SuppressLint
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.util.ONE_HOUR
import com.adealink.frame.util.ONE_MINUTE
import com.adealink.frame.util.ONE_SECOND
import com.adealink.weparty.R
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import kotlin.math.abs


@SuppressLint("SimpleDateFormat")
fun formatTimeTo(timestamp: Long, format: String, locale: Locale = Locale.ENGLISH): String {
    return SimpleDateFormat(format, locale).format(Date(timestamp))
}

/**
 * 倒计时格式化方法，使用 frame 库常量
 * @param millis 毫秒数
 * @return 格式化的倒计时字符串，如 "02h : 30m : 45s"
 */
fun formatCountdownTime(millis: Long): String {
    val hours = millis / ONE_HOUR
    val leftMS = millis % ONE_HOUR
    val minutes = leftMS / ONE_MINUTE
    val seconds = (leftMS % ONE_MINUTE) / ONE_SECOND

    fun formatTime(time: Long) = if (time < 10) "0$time" else "$time"

    return "${formatTime(hours)}h : ${formatTime(minutes)}m : ${formatTime(seconds)}s"
}

fun isSameDay(timestamp1: Long, timestamp2: Long): Boolean {
    return (timestamp1 / 86400_000) == (timestamp2 / 86400_000)
}

//快速计算是否同一年(不适用精准场景)
fun isSameYearApprox(timestamp1: Long, timestamp2: Long): Boolean {
    // 按平均一年365.2425天计算
    //31,556,952,000 =365.2425 * 24 * 60 * 60 * 1000
    return timestamp1 / 31_556_952_000 == timestamp2 / 31_556_952_000
}


// 精确判断（考虑闰年）
fun isSameYearExact(timestamp1: Long, timestamp2: Long): Boolean {
    val cal1 = Calendar.getInstance().apply { timeInMillis = timestamp1 }
    val cal2 = Calendar.getInstance().apply { timeInMillis = timestamp2 }
    return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
}


private const val JUST_NOW = 900_000 //15x60x1000 //15分钟内
private const val JUST_ONE_DAY = 86400_000 //24x60x60x1000 //24小时

/**
 * IM列表时间格式化
 *
 * ≤15min，现在
 * ＞15min且小于24h，并且是今天内，显示实际的时分，如10:21, (格式:HH:mm)
 * ＞15min且小于24h，并且不是今天内，显示日期，如28/11 (格式:dd/MM)
 * ≥24h，显示日期，28/11 (格式:dd/MM)
 * 跨年，显示日月年，28/11/2025 (格式:dd/MM/yyyy)
 */
fun Long.formatTimeStr(): String {
    val now = Date()
    val ts = Date(this)
    val tsOffset = abs(now.time - ts.time)
    return if (tsOffset <= JUST_NOW) {
        //≤15min，现在
        getCompatString(R.string.common_just_now)
    } else if (tsOffset <= JUST_ONE_DAY && isSameDay(now.time, ts.time)) {
        //＞15min且小于24h，并且是今天内，显示实际的时分，如10:21, (格式:HH:mm)
        formatTimeTo(this, "HH:mm")
    } else if (tsOffset <= JUST_ONE_DAY) {
        //＞15min且小于24h，并且不是今天内，显示日期，如28/11 (格式:dd/MM)
        formatTimeTo(this, "dd/MM")
    } else if (isSameYearApprox(now.time, ts.time)) {
        //≥24h，显示日期，28/11 (格式:dd/MM)
        formatTimeTo(this, "dd/MM")
    } else {
        //跨年，显示日月年，28/11/2025 (格式:dd/MM/yyyy)
        formatTimeTo(this, "dd/MM/yyyy")
    }
}

/**
 * IM会话时间格式化
 * 时间格式规则：
 * 今天：today
 * 昨天：Yesterday
 * 同一年：28/11
 * 跨年：MM-DD-YYYY  28/11/2025
 */
fun Long.sessionTimeStr(): String {
    val now = Date()
    val ts = Date(this)
    val tsOffset = abs(now.time - ts.time)
    return if (tsOffset <= JUST_ONE_DAY && isSameDay(now.time, ts.time)) {
        //小于24h，并且是今天内，显示实际的时分，如10:21, (格式:HH:mm)
        formatTimeTo(this, "HH:mm")
    } else if (tsOffset <= JUST_ONE_DAY) {
        //小于24h，并且不是今天内，显示日期，如28/11 (格式:dd/MM)
        formatTimeTo(this, "dd/MM")
    } else if (isSameYearApprox(now.time, ts.time)) {
        //≥24h，显示日期，28/11 (格式:dd/MM)
        formatTimeTo(this, "dd/MM")
    } else {
        //跨年，显示日月年，28/11/2025 (格式:dd/MM/yyyy)
        formatTimeTo(this, "dd/MM/yyyy")
    }
}

/**
 * 获取IM会话时间
 * @param lastTime 上一条消息的时间
 * @return null 不展示
 */
fun getSessionTimeStr(thisTime: Long, lastTime: Long?): String? {
    if (lastTime == null) {
        return thisTime.sessionTimeStr()
    }
    val nowTs = Date().time
    val nowOffset = abs(nowTs - thisTime)
    return if (nowOffset <= JUST_ONE_DAY && isSameDay(nowTs, thisTime)) {
        //小于24h，并且是今天内，显示实际的时分，如10:21, (格式:HH:mm)
        if (isSameDay(lastTime, thisTime)) {
            null
        } else {
            formatTimeTo(thisTime, "HH:mm")
        }
    } else if (nowOffset <= JUST_ONE_DAY) {
        //小于24h，并且不是今天内，显示日期，如28/11 (格式:dd/MM)
        if (isSameDay(lastTime, thisTime)) {
            null
        } else {
            formatTimeTo(thisTime, "dd/MM")
        }
    } else if (isSameYearApprox(nowTs, thisTime)) {
        //≥24h，显示日期，28/11 (格式:dd/MM)
        if (isSameDay(lastTime, thisTime)) {
            null
        } else {
            formatTimeTo(thisTime, "dd/MM")
        }
    } else {
        //跨年，显示日月年，28/11/2025 (格式:dd/MM/yyyy)
        if (isSameDay(lastTime, thisTime)) {
            null
        } else {
            formatTimeTo(thisTime, "dd/MM/yyyy")
        }
    }
}