package com.base.pdfviewerscannerwhite.ui.splash

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.base.pdfviewerscannerwhite.BuildConfig
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.ads.AdmobHelper.initAdmobAd
import com.base.pdfviewerscannerwhite.ads.admob.AdmobInterstitialUtils
import com.base.pdfviewerscannerwhite.ads.admob.AdmobOpenUtils
import com.base.pdfviewerscannerwhite.bean.ConstObject.ifAgreePrivacy
import com.base.pdfviewerscannerwhite.bean.ConstObject.isFirstStart
import com.base.pdfviewerscannerwhite.databinding.ActivitySplash2Binding
import com.base.pdfviewerscannerwhite.fcm.NotificationHoverUtils
import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.helper.EventUtils
import com.base.pdfviewerscannerwhite.helper.MyApplication
import com.base.pdfviewerscannerwhite.helper.WeatherUtils
import com.base.pdfviewerscannerwhite.service.StayNotificationService.Companion.startStayNotification
import com.base.pdfviewerscannerwhite.ui.main.MainActivity
import com.base.pdfviewerscannerwhite.ui.permission.PermissionActivity
import com.base.pdfviewerscannerwhite.ui.set.SetLanguageActivity
import com.base.pdfviewerscannerwhite.utils.AnimationUtils
import com.base.pdfviewerscannerwhite.utils.BarUtils
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.UmpUtils
import com.base.pdfviewerscannerwhite.utils.UmpUtils.requestUMP
import com.base.pdfviewerscannerwhite.utils.UmpUtils.umpCalled
import com.base.pdfviewerscannerwhite.utils.UmpUtils.umpCanAd
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<ActivitySplash2Binding>(), SplashView {

    private val TAG = "SplashActivity"

    private lateinit var splashPresenter: SplashPresenter

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

    @SuppressLint("SetTextI18n")
    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)

//        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())
        if (Build.VERSION.SDK_INT >= 33) {
            registerForActivityResult(ActivityResultContracts.RequestPermission()) {}.launch(
                Manifest.permission.POST_NOTIFICATIONS
            )
        }
        splashPresenter = SplashPresenter(this)
        startStayNotification()

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


        // 获取当前日期
        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.tvXingqi.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 isHotLaunch = intent.extras?.getBoolean("isHotLaunch") ?: false
        if (BuildConfig.DEBUG) {
//            toast("isHotLaunch=$isHotLaunch")
        }
        startWeatherAnimation()

        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()
                }
            }
        }
    }


    override fun showAd() {
        LogEx.logDebug(TAG, "showAd")
        if (AdmobOpenUtils.haveReadAd()) {
            showReadOpenAd()
        } else {
            if (AdmobInterstitialUtils.haveReadAd()) {
                showReadInterAd()
            } 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) {
                splashPresenter.pauseJumpJob()
            }
        }, onHidden = {
            LogEx.logDebug(TAG, "ad jumpNext")
            jumpNext()
        })
    }

    private fun showReadInterAd() {
        splashPresenter.pauseJumpJob()
        AdmobInterstitialUtils.showInterstitialAd(this) {
            jumpNext()
        }
    }

    override fun agreePrivacy() {
        if (umpCanAd) {
            initAdmobAd(this)
            showAd()
            splashPresenter.startJumpJob = true
            splashPresenter.startJumpJob(lifecycleScope)
        } else {
            jumpNext()
        }
    }

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

    override fun onResume() {
        super.onResume()
//        val recreate = updateAppLanguage(MyApplication.splashLanguage, TAG) {
//            MyApplication.splashLanguage = it
//        }
//        if (!recreate) {
//        }
        splashPresenter.startJumpJob(lifecycleScope)
    }


    private var jump: AtomicBoolean = AtomicBoolean(false)
    override fun jumpNext() {
        if (jump.get()) {
            return
        }
        jump.set(true)

        binding.progressBar.progress = 100

        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, SetLanguageActivity::class.java))
        } else {
            startActivity(Intent(this, PermissionActivity::class.java))
        }
        finish()
    }


    @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 + "℃"
                AnimationUtils.startAlphaAnimation(binding.ivWeather, 400, null) {
                    AnimationUtils.startAlphaAnimation(binding.tvWendu, 400, null) {
                    }
                }
            }
        }
    }

}