package com.rgt.superr.ui.splash

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.rgt.superr.SpConstObject.ifAgreePrivacy
import com.rgt.superr.bean.config.AdConfigBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.random.Random

class SplashViewModel : ViewModel() {

    private var countdownJob: Job? = null
    private var startTime: Long = 0
    val totalTimeMs = AdConfigBean.adsConfigBean.openAdLoading * 1000L // 倒计时总时长
    private val checkIntervalMs = 100L // 检查间隔（100毫秒）
    private var countdownOver: Boolean = false

    var jumpNext: (() -> Unit)? = null
    var onTick: ((sLong: Long, total: Long, percent: Float) -> Unit)? = null

    fun startCountdown() {

        if (!ifAgreePrivacy) return

        if (countdownOver) return

        countdownJob?.cancel()
        startTime = System.currentTimeMillis()
        countdownJob = viewModelScope.launch(Dispatchers.IO) {

            while (isActive) {
                val elapsed = System.currentTimeMillis() - startTime
                val remaining = totalTimeMs - elapsed

                if (remaining <= 0) {
                    async(Dispatchers.Main) {
                        onTick?.invoke(totalTimeMs, totalTimeMs, 100f)
                    }
                    break
                } else {
                    async(Dispatchers.Main) {
                        val percent = elapsed * 100f / totalTimeMs
                        onTick?.invoke(elapsed, totalTimeMs, percent)
                    }.await()
                }

                delay(Random.nextLong(checkIntervalMs, checkIntervalMs + 100L))
            }
            launch(Dispatchers.Main) {
                jumpNext?.invoke()
                jumpNext = null
            }
        }
    }

    /**
     * 停止倒计时（可选，便于资源释放）
     */
    fun stopCountdown() {
        countdownJob?.cancel()
        countdownJob = null
    }

    /**
     * 永久结束倒计时
     */
    fun overCountDown() {
        countdownOver = true
        stopCountdown()
    }
}
