package com.base.pdfreaderallpdfreader.ui.splash

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.updatePadding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.base.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.ads.AdmobHelper.initAdmobAd
import com.base.pdfreaderallpdfreader.ads.admob.AdmobInterstitialUtils
import com.base.pdfreaderallpdfreader.ads.admob.AdmobOpenUtils
import com.base.pdfreaderallpdfreader.base.BaseActivity
import com.base.pdfreaderallpdfreader.bean.ConstObject.ifAgreePrivacy
import com.base.pdfreaderallpdfreader.bean.ConstObject.isFirstStart
import com.base.pdfreaderallpdfreader.databinding.ActivitySplashBinding
import com.base.pdfreaderallpdfreader.fcm.NotificationHoverUtils
import com.base.pdfreaderallpdfreader.helper.EventUtils
import com.base.pdfreaderallpdfreader.helper.MyApplication
import com.base.pdfreaderallpdfreader.helper.UmpUtils
import com.base.pdfreaderallpdfreader.helper.UmpUtils.requestUMP
import com.base.pdfreaderallpdfreader.helper.UmpUtils.umpCalled
import com.base.pdfreaderallpdfreader.helper.UmpUtils.umpCanAd
import com.base.pdfreaderallpdfreader.helper.WeatherUtils
import com.base.pdfreaderallpdfreader.ui.language.LanguageActivity
import com.base.pdfreaderallpdfreader.ui.main.MainActivity
import com.base.pdfreaderallpdfreader.utils.BarUtils
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.utils.MyAnimationUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean

@SuppressLint("CustomSplashScreen")
class SplashActivity : BaseActivity<ActivitySplashBinding>() {

    private val TAG = "SplashActivity"
    private lateinit var splashViewModel: SplashViewModel

    override val binding: ActivitySplashBinding by lazy {
        ActivitySplashBinding.inflate(layoutInflater)
    }
    private var actionId = ""

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.WHITE)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        splashViewModel = ViewModelProvider(this)[SplashViewModel::class.java]
        if (Build.VERSION.SDK_INT >= 33) {
            registerForActivityResult(ActivityResultContracts.RequestPermission()) {}.launch(
                Manifest.permission.POST_NOTIFICATIONS
            )
        } else {
            registerForActivityResult(ActivityResultContracts.RequestPermission()) {}.launch(
                Manifest.permission.POST_NOTIFICATIONS
            )
        }

        actionId = intent.extras?.getString("actionId") ?: ""
        LogEx.logDebug(TAG, "actionId=$actionId")
        if (actionId.isNotEmpty()) {
            NotificationHoverUtils.stopNotificationHandler()
        }
        initUI()
        startWeatherAnimation()

        val isHotLaunch = intent.extras?.getBoolean("isHotLaunch") ?: false
        ifAgreePrivacy = true
        if (ifAgreePrivacy) {
            if (isHotLaunch) {
                agreePrivacy()
            } else {
                if (!umpCalled) {//第一次请求ump
                    UmpUtils.callback = {
                        umpCalled = true
                        umpCanAd = it
                        LogEx.logDebug(TAG, "UmpUtils.callback $it")
                        (application as MyApplication).initSolarEngine(it)
                        agreePrivacy()
                        EventUtils.event("ump", "umpCanAd=$umpCanAd")
                    }
                    requestUMP(this)
                } else {
                    agreePrivacy()
                }
            }
        }
    }

    private fun agreePrivacy() {
        if (umpCanAd) {
            initAdmobAd(this)
            showAd()
            splashViewModel.startJumpJob = true
            splashViewModel.startJumpJob(this)
        } else {
            jumpNext()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initUI() {
        // 获取当前日期
        val calendar: Calendar = Calendar.getInstance()
        val month: Int = calendar.get(Calendar.MONTH)
        // 获取当月的第几天
        val dayOfMonth: Int = calendar.get(Calendar.DAY_OF_MONTH)
        //是星期几
        val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)

        val dayOfWeekName = when (dayOfWeek) {
            Calendar.SUNDAY -> R.string.sunday
            Calendar.MONDAY -> R.string.monday
            Calendar.TUESDAY -> R.string.tuesday
            Calendar.WEDNESDAY -> R.string.wednesday
            Calendar.THURSDAY -> R.string.thursday
            Calendar.FRIDAY -> R.string.friday
            Calendar.SATURDAY -> R.string.saturday
            else -> 0
        }
        binding.tvWeek.text = resources.getString(dayOfWeekName)

        val monthName = when (month) {
            0 -> "January"
            1 -> "February"
            2 -> "March"
            3 -> "April"
            4 -> "May"
            5 -> "June"
            6 -> "July"
            7 -> "August"
            8 -> "September"
            9 -> "October"
            10 -> "November"
            11 -> "December"
            else -> "Unknown"
        }
        binding.tvMonthDay.text = "$monthName $dayOfMonth"

        val text = "All PDF Reader"
        val spannableString = SpannableString(text)
        spannableString.setSpan(
            ForegroundColorSpan(Color.parseColor("#E20001")),
            4, text.length,
            Spannable.SPAN_INCLUSIVE_INCLUSIVE
        )
        binding.tvSpanner.text = spannableString
    }

    @SuppressLint("SetTextI18n")
    private fun startWeatherAnimation() = lifecycleScope.launch(Dispatchers.IO) {
        if (!WeatherUtils.hasWeatherDataToday()) {
            WeatherUtils.getWeatherData()
        }

        val weatherCityBean = WeatherUtils.getWeatherEntity()
        val weather = weatherCityBean?.list?.random()
        LogEx.logDebug(TAG, "weather=$weather")
        if (weather != null) {
            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
            }

            launch(Dispatchers.Main) {
                binding.ivWeather.setImageResource(icon)
                binding.tvWendu.text = weather.tempMin + "℃" + " / " + weather.tempMax + "℃"
                MyAnimationUtils.startAlphaAnimation(binding.ivWeather, 400, null) {
                    MyAnimationUtils.startAlphaAnimation(binding.tvWendu, 400, null) {
                    }
                }
            }
        }
    }

    private fun showAd() {
        LogEx.logDebug(TAG, "showAd")
        if (AdmobOpenUtils.haveReadAd()) {
            showReadOpenAd()
        } else {
            if (AdmobInterstitialUtils.haveReadAd()) {
                showReadOpenAd()
            } else {
                AdmobOpenUtils.loadAppOpenAd { loaded ->
                    LogEx.logDebug(TAG, "loadAppOpenAd loaded=$loaded")
                    if (loaded) {
                        showReadOpenAd()
                    } else {
                        LogEx.logDebug(TAG, "no load ad jumpNext")
                        jumpNext()
                    }
                }
            }
        }
    }

    private fun showReadOpenAd() {
        AdmobOpenUtils.showAppOpenAd(this, showBefore = {
            if (it) {
                splashViewModel.pauseJumpJob()
            }
        }, onHidden = {
            LogEx.logDebug(TAG, "ad jumpNext")
            jumpNext()
        })
    }

    private var jump: AtomicBoolean = AtomicBoolean(false)
    fun jumpNext() {

        if (jump.get()) {
            return
        }
        jump.set(true)

        binding.root.postDelayed({

            if (isFirstStart) {
                firstStartJump()
            } else {
                LogEx.logDebug(TAG, "jumpNext actionId=$actionId")

                when (actionId) {
                    else -> {
                        startActivity(Intent(this, MainActivity::class.java).apply {
                            putExtra("actionId", actionId)
                        })
                    }
                }
                this.intent.extras?.clear()
                finish()
            }

        }, 100)
    }

    private fun firstStartJump() {
        isFirstStart = false
        if (Locale.getDefault().language != Locale.ENGLISH.language) {
            startActivity(Intent(this, LanguageActivity::class.java))
        } else {
            startActivity(Intent(this, MainActivity::class.java))
        }
        finish()
    }

    override fun onPause() {
        super.onPause()
        splashViewModel.pauseJumpJob()
    }

    override fun onResume() {
        super.onResume()
        splashViewModel.startJumpJob(this)
    }

}