package com.adealink.weparty.commonui

import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.annotation.ColorRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.isNotEmpty
import androidx.viewpager2.widget.ViewPager2
import com.adealink.frame.aab.util.getCompatColor
import com.adealink.frame.aab.util.installSplitCompat
import com.adealink.frame.apm.apmService
import com.adealink.frame.locale.language.languageManager
import com.adealink.frame.router.Router
import com.adealink.frame.router.manager.deeplinkRouterManager
import com.adealink.frame.util.istNavigationBarGestureMode
import com.adealink.frame.util.paddingBottomSystemWindowInsets
import com.adealink.weparty.BuildConfig
import com.adealink.weparty.commonui.dialog.LoadingDialog
import com.adealink.weparty.commonui.dialogfragment.BaseDialogFragment
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.util.QMUIStatusBarHelper
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.crashlytics.setCustomKeys
import com.google.firebase.ktx.Firebase
import me.jessyan.autosize.AutoSizeCompat

open class BaseActivity : AppCompatActivity() {

    private var loadingDialog: LoadingDialog? = null
    private var istNavigationBarGestureMode = false

    protected open val isEdge2EdgeEnable = true
    protected open val autoFitNavigationBar = true
    protected open val forceFitNavigationBar = false

    open val routeSubPage = true

    override fun onCreate(savedInstanceState: Bundle?) {
        onBeforeCreate()
        super.onCreate(savedInstanceState)
        apmService.startStrictMode()
        istNavigationBarGestureMode = istNavigationBarGestureMode(this)
        edge2Edge(istNavigationBarGestureMode)
        val initAfter = onAfterSuperCreate()
        if (initAfter) {
            QMUIStatusBarHelper.translucent(this)
            initViews()
            initComponents()
            observeViewModel()
            loadData()
            initOthers()
            routeSubPage(intent)
        }
        fitNavigationBarForEdge2Edge(istNavigationBarGestureMode)
    }

    open fun onBeforeCreate() {

    }

    open fun onAfterSuperCreate(): Boolean {
        return true
    }

    open fun initViews() {

    }

    open fun initComponents() {

    }

    open fun observeViewModel() {

    }

    open fun loadData() {

    }

    /**
     * 加载数据之后初始化一些不紧急的内容
     */
    open fun initOthers() {
        setFirebaseCrashlytics()
    }

    private fun setFirebaseCrashlytics() {
        ProfileModule.getMyUserInfo()?.let {
            val crashlytics = Firebase.crashlytics
            crashlytics.setUserId(it.uid)
            crashlytics.setCustomKeys {
                key("uid", it.uid)
                // TODO: firebase地区补充
//                key("region", it.region ?: "")
//                key("country", it.country ?: "")
                key("cur_activity", this@BaseActivity::class.java.simpleName)
                key("BuildType", BuildConfig.BUILD_TYPE)
                key("IS_RELEASE", BuildConfig.IS_RELEASE)
                key("gender", it.gender.toString())
            }
        }
    }


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

    open fun handleNewIntent(intent: Intent?) {

    }

    open fun routeSubPage(intent: Intent?) {
        if (routeSubPage.not()) {
            return
        }

        if (!deeplinkRouterManager.isLogin()) {
            return
        }

        val subPagePath = intent?.getStringExtra("sub_page")
        if (subPagePath.isNullOrEmpty()) {
            return
        }

        Router.getRouterInstance<BaseDialogFragment>(subPagePath)
            ?.apply {
                arguments = intent.extras
            }
            ?.show(supportFragmentManager)
    }

    fun setNavigationBarColor(@ColorRes resId: Int) {
        if (isEdge2EdgeEnable && istNavigationBarGestureMode) { // Edge to Edge的情况下不设置颜色
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.navigationBarColor = getCompatColor(resId)
            runCatching { WindowCompat.getInsetsController(window, window.decorView).isAppearanceLightNavigationBars = false }
        }
    }

    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(languageManager?.attachBaseContext(newBase))
        installSplitCompat(this)
    }

    private fun edge2Edge(istNavigationBarGestureMode: Boolean) {
        if (isEdge2EdgeEnable) {
            enableEdgeToEdge()
            // 国产机型：如小米 Android 15 enableEdgeToEdge 后底部导航栏仍会占据空间，调用以下设置使其效果保持一致
            if (istNavigationBarGestureMode && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                window.isNavigationBarContrastEnforced = false
            }
        }
    }

    private fun fitNavigationBarForEdge2Edge(istNavigationBarGestureMode: Boolean) {
        if (!forceFitNavigationBar) {
            if (!autoFitNavigationBar) {
                return
            }
            if (istNavigationBarGestureMode) {
                return
            }
        }
        (window.decorView.findViewById<View>(android.R.id.content) as? ViewGroup)
            ?.run {
                takeIf { isNotEmpty() }
                    ?.getChildAt(0)
                    ?.takeIf { !it.fitsSystemWindows }
                    ?.paddingBottomSystemWindowInsets()
            }
    }

    private fun initLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog()
        }
    }

    fun showLoading() {
        initLoadingDialog()
        loadingDialog?.show(supportFragmentManager)
    }

    fun dismissLoading() {
        loadingDialog?.dismiss()
    }

    fun isLoadingShowing(): Boolean {
        return loadingDialog?.isShowing() == true
    }

    override fun onDestroy() {
        super.onDestroy()
        dismissLoading()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        if (!containsViewPager2(window.decorView)) {
            super.onSaveInstanceState(outState)
        }
    }

    private fun containsViewPager2(view: View): Boolean {
        if (view is ViewPager2) return true
        if (view is ViewGroup) {
            for (i in 0 until view.childCount) {
                if (containsViewPager2(view.getChildAt(i))) {
                    return true
                }
            }
        }
        return false
    }

    //避免频繁执行
    private var hasAutoSize = false
    override fun getResources(): Resources {
        val resources = super.getResources()
        if (hasAutoSize) {
            return resources
        }
        try {
            AutoSizeCompat.autoConvertDensityOfGlobal(resources);//如果没有自定义需求用这个方法
            hasAutoSize = true
        } catch (e: Exception) {

        }
        return resources
    }

    /**
     * 跨模块给当前WebActivity发送NativeResume消息
     */
    open fun notifyResumeMessage(){}
}