package com.rdiot.yx485.ui

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.drake.net.utils.scopeNetLife
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ktx.immersionBar
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseActivity
import com.rdiot.yx485.databinding.ActSplashBinding
import com.rdiot.yx485.net.refreshToken
import com.rdiot.yx485.ui.login.LoginActivity
import com.rdiot.yx485.ui.main.MainActivity
import com.rdiot.yx485.util.finishGoTo
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 启动屏
 * @author mR2hao
 * @date 2022/12/31
 */
class SplashActivity : BaseActivity<ActSplashBinding>() {
    override fun getLayoutId() = R.layout.act_splash

    companion object {
        private const val DELAY_TIME = 3000L
        private const val DEBUG_DELAY_TIME = 300L
    }

    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            hideBar(BarHide.FLAG_HIDE_BAR)
        }


        scopeNetLife {
            refreshToken().await().saveLocal()
            delayFinish(true)
        }.catch { e ->
            LogUtils.e("刷新Token失败：${e.message}")
            delayFinish(false)
        }
    }

    private fun delayFinish(isGoMain:Boolean){
        lifecycleScope.launch {
            if (BuildConfig.DEBUG) {
                delay(DEBUG_DELAY_TIME)
            } else {
                delay(DELAY_TIME)
            }
            if (isGoMain){
                finishGoTo(MainActivity::class.java)

            }else{
                finishGoTo(LoginActivity::class.java)
            }
        }
    }
}