package com.duben.microtribe.ui.activitys

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import com.duben.microtribe.R
import com.duben.microtribe.ad.AdManager
import com.duben.microtribe.ad.splash.SplashManager
import com.duben.microtribe.common.Constant
import com.duben.microtribe.common.Constant.PRIVACY_URL
import com.duben.microtribe.common.Constant.REGISTER_URL
import com.duben.microtribe.manager.LocalVedioManager
import com.duben.microtribe.manager.TrackManager
import com.duben.microtribe.manager.UserManager
import com.duben.microtribe.ui.activitys.base.BaseActivity
import com.duben.microtribe.ui.widgets.CycleProgress
import com.duben.microtribe.ui.widgets.DialogListener
import com.duben.microtribe.ui.widgets.PowerDialog
import com.duben.microtribe.ui.widgets.PowerDialog2
import com.duben.microtribe.ui.widgets.countdowntimer.CountDownTimerSupport
import com.duben.microtribe.ui.widgets.countdowntimer.OnCountDownTimerListener
import com.duben.microtribe.utils.AppPreferencesManager
import com.duben.microtribe.utils.AppPreferencesManager.get
import com.duben.microtribe.utils.LogUtil
import java.util.*

/**
 * 描述：启动页
 * 作者：孟崔广
 * 时间：2022/12/4 18:06
 */
class SplashActivity : BaseActivity() {

    var powerDialog: PowerDialog? = null
    var powerDialog2: PowerDialog2? = null
    private var mProgressBar: CycleProgress? = null
    private val AD_TIME_OUT = 3000
    var timer: CountDownTimerSupport? = null
    private var isAdSuc = false

    override fun getContentViewLayoutID(): Int {
        return R.layout.activity_splash
    }

    override fun initViewsAndEvents() {
        if (!isTaskRoot) {
            //点击Home键后再点击App图标，会回到原来的界面。今天重新打包后，但是在Debug模式下，一切正常，
            // 但是把打完包的apk（Release）安装在其他手机上时，回到桌面后点击图标会重新打开启动页
            finish()
            return
        }
        mProgressBar = findViewById(R.id.progressBar)

        showPowerDialog()
    }

    override fun finish() {
        // 兼容可能崩溃的问题
        if (powerDialog != null && powerDialog!!.isShowing) {
            powerDialog!!.dismiss()
            powerDialog = null
        }
        if (powerDialog2 != null && powerDialog2!!.isShowing) {
            powerDialog2!!.dismiss()
            powerDialog2 = null
        }
        super.finish()
    }

    private fun initData() {
//        if(!TextUtils.isEmpty(UserManager.getInstance().userID)){
//            TrackManager.getInstance().firstShowVedio()
//        }

        val firstSplash = get().getBoolean(Constant.FIRST_SPLASH, true)
        if (!firstSplash) {
            SplashManager.preLoadAd(this@SplashActivity)
        }
        mProgressBar!!.startOneAnim()
        try {
            startTimer()
        } catch (e: Exception) {
            goToMainActivity()
        }
    }

    fun startTimer() {
        if (timer != null) { //防止计时器重复
            timer!!.stop()
            timer = null
        }
        timer = CountDownTimerSupport(AD_TIME_OUT.toLong(), 1000)
        timer!!.setOnCountDownTimerListener(object : OnCountDownTimerListener {
            override fun onTick(millisUntilFinished: Long) {
                // 第一次安装时，延迟加载开屏广告，因为广告sdk还未初始化完成
                val firstSplash = get().getBoolean(Constant.FIRST_SPLASH, true)
                if (firstSplash && millisUntilFinished == (AD_TIME_OUT - 2000).toLong()) {
                    SplashManager.preLoadAd(this@SplashActivity)
                    get().put(Constant.FIRST_SPLASH, false)
                }

                if (!isFinishing) {
                    if (isAdSuc) return

                    if (SplashManager.isSuccessStatus()) {
                        LogUtil.d("SplashNewActivity-->", "SplashNewActivity--> ad show")
                        isAdSuc = true
                        if (mProgressBar != null) {
                            mProgressBar!!.setCompleteNoAnim()
                        }
                        // 跳转广告
                        readyGoThenKill(SplashAdActivity::class.java)
                    }
                }
            }

            override fun onFinish() {
                if (isAdSuc) return

                if (!isFinishing) {
                    if (mProgressBar != null) {
                        mProgressBar!!.setCompleteNoAnim()
                    }
                    goToMainActivity()
                }
            }
        })
        timer!!.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer!!.stop()
            timer = null
        }
    }

    override fun isApplyKitKatTranslucency(): Boolean {
        return false
    }

    /**
     * 跳转到主页面
     */
    private fun goToMainActivity() {
        readyGoThenKill(MainActivity::class.java)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(
            keyCode,
            event
        )
    }

    private fun showPowerDialog() {
        if (get().getBoolean(Constant.LOAN_PERMISSION_FLAG, true)) {
            powerDialog()
        } else {
            initData()
        }
    }

    /**
     * 权限弹窗
     */
    private fun powerDialog() {
        val bundle = Bundle()
        powerDialog = PowerDialog(this, object : DialogListener() {
            @SuppressLint("NonConstantResourceId")
            override fun onClick(v: View) {
                when (v.id) {
                    R.id.tv_dialogper_agreement -> {
                        bundle.putString(WebActivity.WEB_TITLE, getString(R.string.register_name))
                        bundle.putString(WebActivity.WEB_URL, REGISTER_URL)
                        readyGo(WebActivity::class.java, bundle)
                    }
                    R.id.tv_dialogper_policy -> {
                        bundle.putString(WebActivity.WEB_TITLE, getString(R.string.privacy_name))
                        bundle.putString(WebActivity.WEB_URL, PRIVACY_URL)
                        readyGo(WebActivity::class.java, bundle)
                    }
                    R.id.btn_dialogper_back -> {
                        if (powerDialog != null && powerDialog!!.isShowing) {
                            powerDialog!!.dismiss()
                        }
                        powerDialog2()
                    }
                    R.id.btn_dialogper_next -> {
                        if (powerDialog != null && powerDialog!!.isShowing) {
                            powerDialog!!.dismiss()
                        }
                        get().put(Constant.LOAN_PERMISSION_FLAG, false)
                        baseApplication.thirdConfig()
                        TrackManager.getInstance().visitorlogin()
                        initData()
                    }
                }
            }
        })
        powerDialog!!.show()
    }

    /**
     * 权限弹窗
     */
    private fun powerDialog2() {
        val bundle = Bundle()
        powerDialog2 = PowerDialog2(this, object : DialogListener() {
            @SuppressLint("NonConstantResourceId")
            override fun onClick(v: View) {
                when (v.id) {
                    R.id.tv_dialogper_agreement -> {
                        bundle.putString(WebActivity.WEB_TITLE, getString(R.string.register_name))
                        bundle.putString(WebActivity.WEB_URL, REGISTER_URL)
                        readyGo(WebActivity::class.java, bundle)
                    }
                    R.id.tv_dialogper_policy -> {
                        bundle.putString(WebActivity.WEB_TITLE, getString(R.string.privacy_name))
                        bundle.putString(WebActivity.WEB_URL, PRIVACY_URL)
                        readyGo(WebActivity::class.java, bundle)
                    }
                    R.id.btn_dialogper_back -> {
                        if (powerDialog2 != null && powerDialog2!!.isShowing) {
                            powerDialog2!!.dismiss()
                        }
                        baseApplication.exitApp()
                    }
                    R.id.btn_dialogper_next -> {
                        if (powerDialog2 != null && powerDialog2!!.isShowing) {
                            powerDialog2!!.dismiss()
                        }
                        get().put(Constant.LOAN_PERMISSION_FLAG, false)
                        baseApplication.thirdConfig()
                        TrackManager.getInstance().visitorlogin()
                        initData()
                    }
                }
            }
        })
        powerDialog2!!.show()
    }
}