package com.base.appzxhy.ui.splash

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.UnderlineSpan
import android.util.Log
import android.view.View
import android.view.WindowManager
import androidx.core.graphics.toColorInt
import androidx.core.net.toUri
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.appzxhy.GlobalConfig.URL_PRIVACY
import com.base.appzxhy.MyApplication
import com.base.appzxhy.R
import com.base.appzxhy.SpConstObject.ifAgreePrivacy
import com.base.appzxhy.SpConstObject.isGuided
import com.base.appzxhy.base.BaseActivity
import com.base.appzxhy.base.jumpAction
import com.base.appzxhy.bean.FeatureBean.Companion.BATTERY_INFO
import com.base.appzxhy.business.helper.EventUtils
import com.base.appzxhy.business.helper.InstallHelps
import com.base.appzxhy.business.helper.NewComUtils
import com.base.appzxhy.business.helper.NewComUtils.spConfig
import com.base.appzxhy.business.service.StayJobService.Companion.startStayJobService
import com.base.appzxhy.databinding.ActivitySplashBinding
import com.base.appzxhy.ui.dialog.StoragePermissionDialog
import com.base.appzxhy.ui.guide.GuideExperienceActivity
import com.base.appzxhy.ui.guide2.GuideAc
import com.base.appzxhy.ui.main.MainActivity
import com.base.appzxhy.utils.PermissionUtils.checkStorePermission
import com.base.appzxhy.utils.PermissionUtils.requestStoragePermission
//import com.base.appzxhy.utils.UmpUtils
//import com.base.appzxhy.utils.umpCalled
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean


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

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

    override fun initView() {
        super.initView()
        showLoadingAd()
    }

    private fun setPrivacyPolicy() {

        val spannableString = SpannableString(getString(R.string.privacy_policy))
        spannableString.setSpan(
            UnderlineSpan(),
            0,
            spannableString.length,
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )
        spannableString.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                startActivity(Intent(Intent.ACTION_VIEW, URL_PRIVACY.toUri()))
            }
        }, 0, spannableString.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)

        binding.tvPrivacy.text = spannableString
        binding.tvPrivacy.movementMethod = LinkMovementMethod.getInstance()
        binding.tvPrivacy.setLinkTextColor("#F2FEF8".toColorInt())

//        val spannableString2 = SpannableString("terms of service")
//        spannableString2.setSpan(UnderlineSpan(), 0, spannableString2.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
//        spannableString2.setSpan(object : ClickableSpan() {
//            override fun onClick(widget: View) {
//                startActivity(Intent(Intent.ACTION_VIEW, URL_USE.toUri()))
//            }
//        }, 0, spannableString2.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
//
//        binding.tvTerms.text = spannableString2
//        binding.tvTerms.movementMethod = LinkMovementMethod.getInstance()
//        binding.tvTerms.setLinkTextColor("#2DD29E".toColorInt())

    }

    private fun requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val array = arrayOf(Manifest.permission.POST_NOTIFICATIONS)
            launcher.launch(array) { permissions ->
                val flag = permissions.values.all { it }
                if (flag) MyApplication.appContext.startStayJobService()
            }
        }
    }

    override fun initListener() {
        super.initListener()
        binding.tvStart.setOnClickListener {
            ifAgreePrivacy = true
            showLoadingAd()
            EventUtils.event("app_start")
            EventUtils.event("page_${javaClass.simpleName}")
            MyApplication.appContext.initApp()
        }
    }

    override fun handleBackCallBack() {

    }

    private fun showLoadingAd() {
        binding.clBottomStart.visibility = if (ifAgreePrivacy) View.GONE else View.VISIBLE
        binding.clBottomLoading.visibility = if (ifAgreePrivacy) View.VISIBLE else View.GONE
        binding.llConsent.visibility = if (ifAgreePrivacy) View.GONE else View.VISIBLE
        if (guideNext()) return
        lifecycleScope.launch {
            delay(1000)
            if (guideNext()) return@launch
            if (ifAgreePrivacy) {
                if (!isGuided) {
                    requestNotificationPermission()
                }
                val acAction = {
                    lifecycleScope.launch {
                        repeat(10) {
                            delay(300)
                            binding.progressBar.setProgress(it,true)
                        }
                        jumpNext()
                    }
                }

                if (spConfig.isNotEmpty()) {
                    acAction.invoke()
                } else {
                    if (NewComUtils.requestCfgIng.get()) {
                        Log.e(TAG, "requestCfg")
                        NewComUtils.requestCfgCallBackMap.put("adCallBack") {
                            Log.e(TAG, "requestCfgCallBack")
                            lifecycleScope.launch(Dispatchers.Main) {
                                acAction.invoke()
                            }
                        }
                    } else {
                        acAction.invoke()
                    }
                }
            } else {
                setPrivacyPolicy()
            }
        }
    }

    val jumped = AtomicBoolean(false)
    fun jumpNext() {
        if (jumped.get()) return
        jumped.set(true)

        when {
            !isGuided -> {
                isGuided = true
//                when (ConfigBean.configBean.guideMode) {
//                    0 -> {
//                        goToAc(GuideExperienceActivity::class.java)
//                    }
//
//                    1 -> {
//                        goToAc(GuideCleanActivity::class.java)
//                    }
//
//                    else -> goToAc(MainActivity::class.java)
//                }
                goToAc(GuideExperienceActivity::class.java)
                finish()
            }

            isHotLaunch -> {
                goToAc(MainActivity::class.java)
                finish()
            }

            actionId.isNotEmpty() -> {
                actionIdJump()
            }

            else -> {
                goToAc(MainActivity::class.java)
                finish()
            }
        }
        intent.extras?.clear()
    }

    fun guideNext(): Boolean {
        if (InstallHelps.installSource.isNotBlank() && InstallHelps.installSource!= "or") {
            binding.root.isVisible = false
            window?.run {
                val layoutParams = attributes
                layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT
                layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
                attributes = layoutParams
            }
            goToAc(GuideAc::class.java)
            finish()
            return true
        }
        return false
    }

    fun actionIdJump() {
        when (actionId) {
            BATTERY_INFO -> {
                jumpAction(actionId)
                finish()
            }

            else -> {

                val actionStorage = {
                    if (checkStorePermission()) {
                        jumpAction(actionId)
                        finish()
                    } else {
                        val dialog = StoragePermissionDialog(this)
                        dialog.action = {
                            requestStoragePermission(launcher) {
                                if (it) {
                                    jumpAction(actionId)
                                    finish()
                                } else {
                                    goToAc(MainActivity::class.java)
                                    finish()
                                }
                            }
                        }
                        dialog.showDialog()
                    }
                }

                actionStorage.invoke()

            }

        }
    }

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

    var isHotLaunch: Boolean = false
    var actionId = ""
    fun handleIntentExtras() {
        super.onNewIntent(intent)
        actionId = intent?.extras?.getString("actionId") ?: ""
        isHotLaunch = intent?.extras?.getBoolean("isHotLaunch") == true
    }

}