package com.adealink.weparty

import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.WindowManager
import androidx.fragment.app.FragmentContainerView
import com.adealink.frame.aab.util.getCompatColor
import com.adealink.frame.log.Log
import com.adealink.frame.router.Router
import com.adealink.frame.router.annotation.BindExtra
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.frame.router.manager.deeplinkRouterManager
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.module.account.Account
import com.adealink.weparty.module.account.AccountModule
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.ui.MainStartUpFragment
import com.adealink.weparty.ui.main.MainFragment
import com.adealink.weparty.update.updateManager
import com.adealink.weparty.util.QMUIStatusBarHelper
import com.adealink.weparty.util.goLocalLinkPage

@RouterUri(path = [AppModule.Main.PATH], desc = "首页")
class MainActivity : BaseActivity() {

    companion object {
        private const val TAG = "MainActivity"
    }

    enum class DispatchFrom {
        ON_CREATE,
        ON_NEW_INTENT
    }

    @BindExtra(AppModule.Main.EXTRA_MAIN_TAB)
    var mainTabKey: String? = ""

    @BindExtra(AppModule.Main.EXTRA_MAIN_SUB_TAB)
    var subTabKey: String? = ""

    private var dispatchRouter = false
    override val routeSubPage: Boolean
        get() = !dispatchRouter

    override fun onBeforeCreate() {
        super.onBeforeCreate()
        Log.d(TAG, "onCreate")
        Router.bind(this)
    }

    override fun onAfterSuperCreate(): Boolean {
        if (!isTaskRoot) {
            finish()
            return false
        }

        return true
    }

    override fun initViews() {
        super.initViews()

        //还原启动图背景，清除全屏模式
        window.setBackgroundDrawable(ColorDrawable(getCompatColor(R.color.white)))
        window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)

        QMUIStatusBarHelper.setStatusBarLightMode(this)
        setContentView(FragmentContainerView(this).apply {
            id = R.id.fl_content
        })
        dispatch(intent, DispatchFrom.ON_CREATE)
    }

    override fun initOthers() {
        super.initOthers()
//        reportAppOpenIfNeed(false)
//        serveReportManager.reportFirebaseAppInstanceId()
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume")
        updateManager.checkUpdate(this)
    }

    override fun handleNewIntent(intent: Intent?) {
        super.handleNewIntent(intent)
        setIntent(intent)
        intent?.extras?.let {
            mainTabKey = it.getString(AppModule.Main.EXTRA_MAIN_TAB)
            subTabKey = it.getString(AppModule.Main.EXTRA_MAIN_SUB_TAB)
        }
        dispatch(intent, DispatchFrom.ON_NEW_INTENT)
    }

    private fun dispatch(intent: Intent?, from: DispatchFrom) {
        when {
            needGoLoginActivity() -> {
                Log.d(TAG, "needGoLoginActivity")
                Router.build(this, Account.Login.PATH)
                    .putExtras(intent?.extras ?: Bundle())
                    .start()
                finish()
                return
            }

            needGoRegisterActivity() -> {
                Log.d(TAG, "needGoRegisterActivity")
                Router.build(this, Account.Register.PATH)
                    .putExtras(intent?.extras ?: Bundle())
                    .start()
                finish()
                return
            }
        }
        inflateMainFragment(from)
        intent ?: return
//        val pushDeeplink = intent.getStringExtra(KEY_PUSH_DEEPLINK)
//        if (!pushDeeplink.isNullOrEmpty()) {
//            Log.d(TAG, "dispatchPath, pushDeeplink:$pushDeeplink")
//            PushStatEvent(PushStatEvent.Action.CLICK).apply {
//                type to (intent.extras?.getString(KEY_PUSH_MESSAGE_TYPE) ?: "1")
//                pushId to (intent.extras?.getString(KEY_PUSH_ID) ?: "1")
//                source to "new_fcm_push"
//                deeplink to pushDeeplink
//            }.send()
//            goLocalLinkPage(this, pushDeeplink)
//            return
//        }

        val dispatchPath = intent.getStringExtra(deeplinkRouterManager.getDispatchPathKey())
        if (!dispatchPath.isNullOrEmpty()) {
            Log.d(TAG, "dispatchPath, path:$dispatchPath")
            if (dispatchPath.startsWith(Router.getDeepLink(AppModule.Main.PATH))) {
                return
            }

            dispatchRouter = true
            Router.build(this, dispatchPath).putExtras(intent).start()
            return
        }

        val splashBannerUrl = intent.getStringExtra(AppModule.Main.EXTRA_SPLASH_JUMP_URL)
        if (!splashBannerUrl.isNullOrEmpty()) {
            Log.d(TAG, "dispatchPath, splashBannerUrl:$splashBannerUrl")
            goLocalLinkPage(this, splashBannerUrl)
            return
        }
    }

    private fun needGoLoginActivity(): Boolean {
        return !AccountModule.isLogin()
    }

    private fun needGoRegisterActivity(): Boolean {
        return AccountModule.isLogin() && ProfileModule.getMyUserInfo()?.isComplete() != true
    }

    private fun inflateMainFragment(from: DispatchFrom) {
        var mainFragment =
            supportFragmentManager.findFragmentByTag(MainFragment.TAG) as? MainFragment
        if (mainFragment?.isAdded == true && from == DispatchFrom.ON_CREATE) {
            return
        }

        mainFragment = mainFragment ?: MainFragment.newInstance(
            mainTabKey, subTabKey
        )
        supportFragmentManager.beginTransaction()
            .replace(R.id.fl_content, mainFragment, MainFragment.TAG)
            .commitAllowingStateLoss()

        MainStartUpFragment.inject(this)
    }
}