package com.base.browserwhite.ui.activity.splash

import CloseNotificationReceiver
import android.Manifest
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.view.KeyEvent
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.browserwhite.R
import com.base.browserwhite.ads.AdmobMaxHelper
import com.base.browserwhite.bean.ConstObject.ifAgreePrivacy
import com.base.browserwhite.databinding.ActivitySplash2Binding
import com.base.browserwhite.help.EventUtils
import com.base.browserwhite.help.WeatherUtils
import com.base.browserwhite.service.StayNotificationService.Companion.startStayNotification
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.utils.AnimationUtils
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.LogEx
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@SuppressLint("CustomSplashScreen")
class Splash2Activity : BaseActivity<ActivitySplash2Binding>(),
    PrivacyManager.onUserPrivacyAggreementListener, TaskManager.ProgressListener {
    private val TAG = "Splash2Activity"
    private fun initStatusBar() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        if (Build.VERSION.SDK_INT >= 33) {
            registerForActivityResult(ActivityResultContracts.RequestPermission()) {}.launch(
                Manifest.permission.POST_NOTIFICATIONS
            )
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            EventUtils.event("back")
        }
        return super.onKeyDown(keyCode, event)
    }


    override val binding: ActivitySplash2Binding by lazy {
        ActivitySplash2Binding.inflate(layoutInflater)
    }

    private var mTaskManager: TaskManager? = null
    var jumpType = 0

    @SuppressLint("SetTextI18n")
    override fun initView() {
        initStatusBar()
        if (isDestroyed) {
            return
        }

        jumpType = intent.getIntExtra("actionId", 0)
        closeNotification()
        mTaskManager = TaskManager(binding, this)
        if (ifAgreePrivacy) {
            startAnimation(true) {
                onAgreePrivacy()
            }
        } else {

            startAnimation(false) {
                PrivacyManager(binding, this, this)
            }
        }


    }

    fun startPbAnimation(callback: () -> Unit) {
        AnimationUtils.startAlphaAnimation(binding.pb, 400, null) {
            callback.invoke()
        }
    }

    @SuppressLint("SetTextI18n", "Recycle")
    fun startAnimation(isAgree: Boolean, callback: () -> Unit) {
        lifecycleScope.launch(Dispatchers.IO) {

            if (!WeatherUtils.hasWeatherDataToday()) {
                WeatherUtils.getWeatherData()
            }

            val weatherCityBean = WeatherUtils.getWeatherEntity()
            val weather = weatherCityBean?.list?.random()
            if (weather != null) {

                launch(Dispatchers.Main) {

                    LogEx.logDebug(TAG, "weather 开始 ${weather.fxDate}")
                    binding.tvDate.text = weather.fxDate
                    binding.tvTemperature.text =
                        weather.tempMin + "℃" + " / " + weather.tempMax + "℃"

                    val icon = when (weather.iconDay) {
                        "Sunny day" -> R.mipmap.d_qing
                        "Cloudy day" -> R.mipmap.d_yin
                        "Rainy day" -> R.mipmap.d_dayu
                        "Snowy day" -> R.mipmap.d_xiaxue
                        "Greasy day" -> R.mipmap.d_wumaishachengbao
                        "Unknown" -> R.mipmap.d_qing
                        else -> R.mipmap.d_qing
                    }
                    binding.ivWeather.setImageResource(icon)
                    AnimationUtils.startAlphaAnimation(binding.ivWeather, 400, null) {
                        AnimationUtils.startAlphaAnimation(binding.tvDate, 400, null) {
                            AnimationUtils.startAlphaAnimation(binding.tvTemperature, 400, null) {
                                if (isAgree) {
                                    AnimationUtils.startAlphaAnimation(binding.pb, 400, null) {
                                        callback.invoke()
                                    }
                                } else {
                                    AnimationUtils.startAlphaAnimation(binding.idTvStart, 400, {
                                        val set1 = AnimatorSet()
                                        // 创建缩放动画的ObjectAnimator
                                        val scaleUpAnimator1 = ObjectAnimator.ofFloat(binding.idTvStart, "scaleX", 1f, 0.95f, 1.05f)
                                        val scaleUpAnimator2 = ObjectAnimator.ofFloat(binding.idTvStart, "scaleY", 1f, 0.95f, 1.05f)
                                        scaleUpAnimator1.duration = 400 // 动画持续500毫秒
                                        scaleUpAnimator1.repeatCount = 1 // 重复次数
                                        scaleUpAnimator1.repeatMode = ValueAnimator.REVERSE // 反向重复，实现缩小效果
                                        scaleUpAnimator2.duration = 400 // 动画持续500毫秒
                                        scaleUpAnimator2.repeatCount = 1 // 重复次数
                                        set1.playTogether(scaleUpAnimator1, scaleUpAnimator2)
                                        set1.start()
                                    }) {
                                        callback.invoke()
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                if (isAgree) {
                    AnimationUtils.startAlphaAnimation(binding.pb, 400, null) {
                        callback.invoke()
                    }
                } else {
                    AnimationUtils.startAlphaAnimation(binding.idTvStart, 400, {
                        val set1 = AnimatorSet()
                        // 创建缩放动画的ObjectAnimator
                        val scaleUpAnimator1 = ObjectAnimator.ofFloat(binding.idTvStart, "scaleX", 1f, 0.95f, 1.05f)
                        val scaleUpAnimator2 = ObjectAnimator.ofFloat(binding.idTvStart, "scaleY", 1f, 0.95f, 1.05f)
                        scaleUpAnimator1.duration = 400 // 动画持续500毫秒
                        scaleUpAnimator1.repeatCount = 1 // 重复次数
                        scaleUpAnimator1.repeatMode = ValueAnimator.REVERSE // 反向重复，实现缩小效果
                        scaleUpAnimator2.duration = 400 // 动画持续500毫秒
                        scaleUpAnimator2.repeatCount = 1 // 重复次数
                        set1.playTogether(scaleUpAnimator1, scaleUpAnimator2)
                        set1.start()
                    }) {
                        callback.invoke()
                    }
                }
            }


        }.start()
    }


    private fun closeNotification() {
        sendBroadcast(Intent(this, CloseNotificationReceiver::class.java).apply {
            this.action = CloseNotificationReceiver.Action
            this.putExtra(CloseNotificationReceiver.NotificationId, jumpType)
        })
    }

    override fun onAgreePrivacy(isStart: Boolean) {
        EventUtils.event("app_start")
        if (jumpType == 0) {
            startStayNotification()
        }
        AdmobMaxHelper.preloadAd(this)
        binding.idTvStart.isVisible = false
        binding.llStart.visibility = View.GONE
        binding.llProgress.visibility = View.VISIBLE
        if (isStart) {
            startPbAnimation {
                mTaskManager?.startProgress()
                loadAd()
            }
        } else {
            mTaskManager?.startProgress()
            loadAd()
        }


    }


    override fun onProgressMax() {
        Handler().postDelayed({
            StartUtils.jumpNextPage(this)
        }, 500)
    }

    private fun loadAd() {
        AdmobMaxHelper.admobMaxShowOpenAd(this, {
            mTaskManager?.pauseProgress()
        }, {
            mTaskManager?.pauseProgress()
            runOnUiThread {
                mTaskManager?.maxProgress()
            }

        })
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
    }

    private var isPause = false

    override fun onStart() {
        super.onStart()
        isPause = false
    }

    override fun onPause() {
        super.onPause()
        isPause = true
        EventUtils.event("onPause")
    }

    override fun onResume() {
        super.onResume()
        isPause = false
        EventUtils.event("onResume")
    }

    override fun onStop() {
        super.onStop()
        isPause = true
    }


}