package com.ytpm.hydtw.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import androidx.fragment.app.FragmentActivity
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.splashad.api.ATSplashAd
import com.anythink.splashad.api.ATSplashAdExtraInfo
import com.anythink.splashad.api.ATSplashAdListener
import com.blankj.utilcode.util.LogUtils
import com.ytpm.hydtw.databinding.ActivitySplashBinding

class SplashActivity : FragmentActivity(), ATSplashAdListener {

    private var getTlCountDownTimer: CountDownTimer? = null
    private lateinit var binding: ActivitySplashBinding
    private var splashAd: ATSplashAd? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivitySplashBinding.inflate(layoutInflater)
        setContentView(binding.root)
//        loadAd()
        startGetTlTime()
    }

    override fun onResume() {
        super.onResume()
        binding.close.setOnClickListener {
            val intent = Intent(this@SplashActivity, LoginActivity::class.java)
            startActivity(intent)
            finish()
        }
    }

    private fun startGetTlTime() {

        if (getTlCountDownTimer != null) {
            return
        }

        getTlCountDownTimer = object : CountDownTimer(5000, 1000) {
            @SuppressLint("SetTextI18n")
            override fun onTick(millisUntilFinished: Long) {

            }

            override fun onFinish() {
                val intent = Intent(this@SplashActivity, LoginActivity::class.java)
                startActivity(intent)
                finish()
            }
        }
    }

    private fun loadAd() {
        splashAd = ATSplashAd(this, "b68400ad783355", this, 5000)
        splashAd?.loadAd()
    }

    override fun onAdLoaded(p0: Boolean) {
        LogUtils.e("=======onAdLoaded=${p0}")
        if (splashAd?.isAdReady == true) {
            splashAd?.show(this@SplashActivity, binding.splashAdFl)
        }
    }


    override fun onAdLoadTimeout() {
        LogUtils.e("=======onAdLoadTimeout")
    }

    override fun onNoAdError(p0: AdError?) {
        LogUtils.e("=======onNoAdError=${p0}")
        if (getTlCountDownTimer != null) getTlCountDownTimer?.start()
    }

    override fun onAdShow(p0: ATAdInfo?) {
        LogUtils.e("=======onAdShow=${p0.toString()}")
        if (getTlCountDownTimer != null) getTlCountDownTimer?.start()
    }

    override fun onAdClick(p0: ATAdInfo?) {
        LogUtils.e("=======onAdClick=${p0.toString()}")
    }

    override fun onAdDismiss(p0: ATAdInfo?, p1: ATSplashAdExtraInfo?) {
        LogUtils.e("=======onAdDismiss=${p0.toString()}")
    }

    override fun onDestroy() {
        super.onDestroy()
        splashAd = null
        getTlCountDownTimer?.cancel()
        getTlCountDownTimer = null
    }
}