package com.xscm.modulemain.utils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class CountdownTimer { private var job: Job? = null private val _timeLeft = MutableStateFlow(0L) val timeLeft: StateFlow = _timeLeft fun startCountdown(endTimestamp: Long, scope: CoroutineScope) { job?.cancel() job = scope.launch { while (true) { val currentTime = System.currentTimeMillis() / 1000 val remainingTime = (endTimestamp - currentTime) * 1000 // 转换为毫秒 if (remainingTime <= 0) { _timeLeft.value = 0 break } _timeLeft.value = remainingTime delay(1000) } } } fun stop() { job?.cancel() } /** * 将毫秒数格式化为 HH:MM:SS 格式的时间字符串 * @param milliseconds 毫秒数(支持 0、负数、超大数值) * @return 格式化结果,如 3670000 毫秒 → 01:01:10,125000 毫秒 → 00:02:05 */ fun formatTime(milliseconds: Long): String { // 1. 处理负数/0:转为非负,避免时间为负 val nonNegativeMs = if (milliseconds < 0) 0 else milliseconds // 2. 计算总秒数(向下取整,不足1秒按0算) val totalSeconds = (nonNegativeMs / 1000).toInt() // 3. 拆分 小时、分钟、秒 val hours = totalSeconds / 3600 // 1小时=3600秒 val remainingSecondsAfterHour = totalSeconds % 3600 // 小时剩余秒数 val minutes = remainingSecondsAfterHour / 60 // 分钟 val seconds = remainingSecondsAfterHour % 60 // 秒 // 4. 格式化:HH/MM/SS 均补0为2位(如 1小时1分5秒 → 01:01:05) return String.format("%02d:%02d:%02d", hours, minutes, seconds) } }