package com.mints.goodmoney.ui.activitys

import android.app.Activity
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.mints.goodmoney.R
import com.mints.goodmoney.manager.YlhAdManager
import com.mints.goodmoney.ui.activitys.base.BaseActivity
import com.mints.library.net.netstatus.NetUtils
import com.qq.e.ads.splash.SplashAD
import com.qq.e.ads.splash.SplashADListener
import com.qq.e.comm.util.AdError
import com.yilan.sdk.ui.little.YLLittleVideoFragment

/**
 * 后台返回时每次都展示
 */
class SplashADActivity : BaseActivity(), SplashADListener {
    private var splashAD: SplashAD? = null
    private var container: ViewGroup? = null
    private val skipView: TextView? = null
    var canJump = false

    /**
     * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
     * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
     * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值（单位ms）
     */
    private val minSplashTimeWhenNoAD = 3000

    /**
     * 记录拉取广告的时间
     */
    private var fetchSplashADTime: Long = 0
    private val handler = Handler(Looper.getMainLooper())
    override fun getContentViewLayoutID(): Int {
        return R.layout.activity_splash_ylh
    }

    override fun initViewsAndEvents() {
        if (!NetUtils.isNetworkConnected(context)) {
            finish()
        } else {
            try {
                container = findViewById<View>(R.id.splash_container) as ViewGroup
                fetchSplashAD(this, container, skipView, YlhAdManager.YLH_AD_SPLASH_POSTID, this, 0)
            } catch (e: Exception) {
                readyGoOtherActivity()
            }
        }

        // 预加载好兔视频
        YLLittleVideoFragment.preloadVideo()
    }

    override fun isApplyKitKatTranslucency(): Boolean {
        return false
    }

    /**
     * 拉取开屏广告，开屏广告的构造方法有3种，详细说明请参考开发者文档。
     *
     * @param activity      展示广告的activity
     * @param adContainer   展示广告的大容器
     * @param skipContainer 自定义的跳过按钮：传入该view给SDK后，SDK会自动给它绑定点击跳过事件。SkipView的样式可以由开发者自由定制，其尺寸限制请参考activity_splash.xml或者接入文档中的说明。
     * @param posId         广告位ID
     * @param adListener    广告状态监听器
     * @param fetchDelay    拉取广告的超时时长：取值范围[3000, 5000]，设为0表示使用广点通SDK默认的超时时长。
     */
    private fun fetchSplashAD(activity: Activity, adContainer: ViewGroup?, skipContainer: View?,
                              posId: String, adListener: SplashADListener, fetchDelay: Int) {
        fetchSplashADTime = System.currentTimeMillis()
        splashAD = SplashAD(activity, skipContainer, posId, adListener, fetchDelay)
        splashAD!!.fetchAndShowIn(adContainer)
    }

    override fun onADPresent() {
        Log.i("AD_DEMO", "SplashADPresent")
    }

    override fun onADClicked() {
        Log.i("AD_DEMO", "SplashADClicked clickUrl: "
                + if (splashAD!!.ext != null) splashAD!!.ext["clickUrl"] else "")
    }

    /**
     * 倒计时回调，返回广告还将被展示的剩余时间。
     * 通过这个接口，开发者可以自行决定是否显示倒计时提示，或者还剩几秒的时候显示倒计时
     *
     * @param millisUntilFinished 剩余毫秒数
     */
    override fun onADTick(millisUntilFinished: Long) {
        Log.i("AD_DEMO", "SplashADTick " + millisUntilFinished + "ms")
        if (skipView != null) {
            skipView.text = String.format(SKIP_TEXT, Math.round(millisUntilFinished / 1000f))
        }
    }

    override fun onADExposure() {
        Log.i("AD_DEMO", "SplashADExposure")
    }

    override fun onADLoaded(expireTimestamp: Long) {
        Log.i("AD_DEMO", "SplashADFetch expireTimestamp: " + expireTimestamp
                + ", eCPMLevel = " + splashAD!!.ecpmLevel)
    }

    override fun onADDismissed() {
        Log.i("AD_DEMO", "SplashADDismissed")
        next()
    }

    override fun onNoAD(error: AdError) {
        val str = String.format("LoadSplashADFail, eCode=%d, errorMsg=%s", error.errorCode,
                error.errorMsg)
        Log.i("AD_DEMO", str)
        /**
         * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
         * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
         * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
         */
        val alreadyDelayMills = System.currentTimeMillis() - fetchSplashADTime //从拉广告开始到onNoAD已经消耗了多少时间
        val shouldDelayMills = if (alreadyDelayMills > minSplashTimeWhenNoAD) 0 else minSplashTimeWhenNoAD - alreadyDelayMills //为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
        // 计算出还需要延时多久
        handler.postDelayed({ readyGoOtherActivity() }, shouldDelayMills)
    }

    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当开屏广告为普链类广告时，点击会打开一个广告落地页，此时开发者还不能打开自己的App主页。当从广告落地页返回以后，
     * 才可以跳转到开发者自己的App主页；当开屏广告是App类广告时只会下载App。
     */
    private operator fun next() {
        if (canJump) {
            readyGoOtherActivity()
        } else {
            canJump = true
        }
    }

    override fun onPause() {
        super.onPause()
        canJump = false
    }

    override fun onResume() {
        super.onResume()
        if (canJump) {
            next()
        }
        canJump = true
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    /**
     * 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    private fun readyGoOtherActivity() {
        finish()
    }

    companion object {
        private const val SKIP_TEXT = "点击跳过 %d"
    }
}