package com.base.appzxhy.ui.splash

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.base.appzxhy.SpConstObject.ifAgreePrivacy
import com.base.appzxhy.bean.config.AdConfigBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
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毫秒）

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

    fun startCountdown() {

        if (!ifAgreePrivacy) return

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

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

                if (remaining <= 0) {
                    launch(Dispatchers.Main) {
                        onTick?.invoke(totalTimeMs, totalTimeMs)
                    }
                    break
                } else {
                    launch(Dispatchers.Main) {
                        onTick?.invoke(elapsed, totalTimeMs)
                    }
                }

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

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