package com.koko.drouter.base

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import androidx.activity.SystemBarStyle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewbinding.ViewBinding
import com.didi.drouter.api.DRouter
import com.koko.drouter.app.AppService
import com.koko.drouter.event.EventService
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.random.Random

abstract class BaseActivity<VB : ViewBinding>(
    bindingInflater: (LayoutInflater) -> VB
) : AppCompatActivity() {

    open val TAG = javaClass.simpleName
    private val tagNo = Random.nextInt(500)
    val binding by lazy(LazyThreadSafetyMode.NONE) {
        bindingInflater(layoutInflater)
    }

    lateinit var launcher: ActivityLauncher
    private var currentLocale: Locale? = null

    private val eventService by lazy {
        DRouter.build(EventService::class.java).getService()
    }

    private var onCreateI = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        useDefaultImmersive()
        eventService.eventActivity(this)
        onCreateI++
//        LogEx.logDebug(TAG, "lifecycle $tagNo onCreate ${javaClass.simpleName} $onCreateI")
        launcher = ActivityLauncher(this)
        setContentView(binding.root)

        eventActivity()
//        currentLocale = Locale(appLanguageSp, appLanguageCountrySp)
        initView()
        initListener()
        initData()
    }

    open fun initData() {}

    open fun useDefaultImmersive() {
        enableEdgeToEdge(SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT))
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun eventActivity() {
        val eventService = DRouter.build(EventService::class.java).getService()
        eventService.eventActivity(this)
    }


    protected open fun initView() {}

    protected open fun initListener() {}


    fun finishToMainTop() {
        val appService = DRouter.build(AppService::class.java).getService()
        appService.finishToMainTop(this)
    }

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

//    override fun attachBaseContext(newBase: Context?) {
//        super.attachBaseContext(MultiLanguages.attach(newBase))
//    }


//    fun changeLanguage(currentActivity: Activity, bundle: Bundle = Bundle()): Boolean {
//        val spLanguage = Locale(appLanguageSp, appLanguageCountrySp)
//        val flag = currentLocale != spLanguage
//        val restart = MultiLanguages.setAppLanguage(this, spLanguage)
//        LogEx.logDebug(
//            TAG, "changeLanguage " +
//                    "flag=$flag  restart=$restart currentLocale=$currentLocale spLanguage=$spLanguage"
//        )
//        if (restart) {
//            currentLocale = Locale(appLanguageSp, appLanguageCountrySp)
//        }
//
//        if (flag || restart) {
//            // 1.使用 recreate 来重启 Activity，效果差，有闪屏的缺陷
////             recreate();
//
//            // 2.使用常规 startActivity 来重启 Activity，有从左向右的切换动画
//            // 稍微比 recreate 的效果好一点，但是这种并不是最佳的效果
//            // startActivity(new Intent(this, LanguageActivity.class));
//            // finish();
//
//            // 3.我们可以充分运用 Activity 跳转动画，在跳转的时候设置一个渐变的效果，相比前面的两种带来的体验是最佳的
//            //需要设置启动模式，避免AndroidManifest.xml设置singleTop启动模式导致重复启动不生效
//            //这种方式如果设置了singleTop或者singleTask的，再次回到该activity无法改变于语言，因为还在堆栈里没有重新创建
//            needRecreate()
//            if (needRecreate()) {
//                LogEx.logDebug(TAG, "changeLanguage recreate")
//                recreate()
//            } else {
//                startActivity(Intent(this, currentActivity::class.java).apply {
//                    putExtras(bundle)
//                })
//                overridePendingTransition(R.anim.activity_alpha_in, R.anim.activity_alpha_out)
//                finish()
//            }
//            return true
//        }
//        return false
//    }


    /**
     * 判断是否需要重新创建对SingleTop启动模式的有效
     */
    fun needRecreate(): Boolean {
        return TAG.contains("MainActivity")
    }


    /**
     * 避免在onResume--onPause周期内,多次调用
     * 在onStop中重置标志
     */
    private val onResumeCalled = AtomicBoolean(false)
    private var onResumeOneShootI = 0
    open fun onResumeOneShoot() {
        onResumeOneShootI++
//        LogEx.logDebug(TAG, "lifecycle $tagNo onResumeOneShoot ${javaClass.simpleName} $onResumeOneShootI")
    }

    private var onResumeI = 0
    override fun onResume() {
        super.onResume()
        onResumeI++
//        LogEx.logDebug(TAG, "lifecycle $tagNo onResume ${javaClass.simpleName} $onResumeI")

        if (!onResumeCalled.get()) {
            onResumeCalled.set(true)
            onResumeOneShoot()
        }
    }

    private var onStartI = 0
    override fun onStart() {
        super.onStart()
        onStartI++
//        LogEx.logDebug(TAG, "lifecycle $tagNo onStart ${javaClass.simpleName} $onStartI")
    }

    private var onStopI = 0
    override fun onStop() {
        super.onStop()
        onStopI++
//        LogEx.logDebug(TAG, "lifecycle $tagNo onStop ${javaClass.simpleName} $onStopI")
        onResumeCalled.set(false)
    }

    private var onPauseI = 0
    override fun onPause() {
        super.onPause()
        onPauseI++
//        LogEx.logDebug(TAG, "lifecycle $tagNo onPause ${javaClass.simpleName} $onPauseI")
    }

}