package com.kaixed.kchat.utils

import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * @Author: kaixed
 * @Date: 2024/11/11 14:25
 */
object TextUtil {

    fun getTimestampString(timestamp: Long): String {
        val currentTime = System.currentTimeMillis()
        val difference = currentTime - timestamp

        // 判断是否超过一年
        if (difference >= 365L * 24 * 60 * 60 * 1000) {
            return formatTimestamp(timestamp, "yyyy年MM月dd日")
        }

        // 判断是否是昨天
        if (isYesterday(timestamp)) {
            return "昨天${formatTimestamp(timestamp, "HH:mm")}"
        }

        // 判断是否超过两天
        if (difference >= 2L * 24 * 60 * 60 * 1000) {
            return formatTimestamp(timestamp, "MM月dd日")
        }

        // 否则返回时分
        return formatTimestamp(timestamp, "HH:mm")
    }

    // 判断是否为昨天
    private fun isYesterday(timestamp: Long): Boolean {
        val calendar = Calendar.getInstance()
        val currentDay = calendar.get(Calendar.DAY_OF_YEAR)
        val currentYear = calendar.get(Calendar.YEAR)

        calendar.time = Date(timestamp)
        val timestampDay = calendar.get(Calendar.DAY_OF_YEAR)
        val timestampYear = calendar.get(Calendar.YEAR)

        return currentYear == timestampYear && currentDay - timestampDay == 1
    }

    private fun formatTimestamp(timestamp: Long, pattern: String = "yyyy-MM-dd HH:mm:ss"): String {
        val dateFormat = SimpleDateFormat(pattern, Locale.getDefault())
        val date = Date(timestamp)
        return dateFormat.format(date)
    }
}
