package com.gh.gamecenter.login.view

import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.core.view.WindowCompat
import androidx.lifecycle.Observer
import com.therouter.TheRouter
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.retrofit.ApiResponse
import com.gh.gamecenter.common.utils.DarkModeUtils
import com.gh.gamecenter.core.provider.ILogUtilsProvider
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.login.HaloApp
import com.gh.gamecenter.login.R
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.login.user.LoginTag
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserViewModel
import com.gh.gamecenter.login.utils.LoginHelper
import com.gh.gamecenter.login.utils.NewFlatLogUtils
import com.gh.gamecenter.login.utils.QuickLoginHelper
import com.therouter.router.Route
import org.json.JSONObject


/**
 * 快速登录辅助页，此页面为透明页面，用于执行各快速登录流程
 */
@Route(path = RouteConsts.activity.quickLoginActivity)
class QuickLoginHelperActivity : BaseActivity(), LoginHelper.LoginCallback, Observer<ApiResponse<UserInfoEntity>> {

    private var mLoginTag: LoginTag? = null
    private var mRouteSource = ""
    private var mLoginDialog: WaitingDialogFragment? = null
    private val mUserViewModel: UserViewModel by viewModels { UserViewModel.Factory(HaloApp.getInstance()) }

    private var isSmsCodePageStarted = false

    override fun getLayoutId() = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
        DisplayUtils.transparentStatusBar(this)
        WindowCompat.getInsetsController(window, window.decorView)?.isAppearanceLightStatusBars =
            !DarkModeUtils.isDarkModeOn(this)
        mUserViewModel.loginObsUserinfo.observe(this, this)
        mRouteSource = intent.extras?.getString(com.therouter.router.KEY_DESCRIPTION, "") ?: ""

        handleLoginType()
    }

    private fun handleLoginType() {
        mLoginTag = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
            intent?.getSerializableExtra(EntranceConsts.KET_TYPE) as? LoginTag
        } else {
            intent?.getSerializableExtra(EntranceConsts.KET_TYPE, LoginTag::class.java)
        }
        when (mLoginTag ?: finish()) {
            LoginTag.qq -> LoginHelper.loginWithQQ(this, this)
            LoginTag.wechat -> LoginHelper.loginWithWechat(this)
            LoginTag.weibo -> LoginHelper.loginWithWeibo(this, this)
            LoginTag.oauth -> {
                val token = intent.getStringExtra(EntranceConsts.KEY_DATA) ?: finish()
                login(JSONObject(mapOf("token" to token)), LoginTag.oauth)
            }
        }
    }

    private fun login(content: JSONObject, loginTag: LoginTag) {
        val logUtils = TheRouter.get(ILogUtilsProvider::class.java)
        logUtils?.login("logging", loginTag.name, mEntrance)

        mLoginDialog = WaitingDialogFragment.newInstance(getString(R.string.logging))
        mLoginDialog?.show(supportFragmentManager, null)

        mUserViewModel.login(content, loginTag)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            // QQ Login callback
            com.tencent.connect.common.Constants.REQUEST_LOGIN -> LoginHelper.onQQLoginCallback(
                requestCode,
                resultCode,
                data
            )
            // WeiBo Login callback
            32973 -> LoginHelper.onWeiboLoginCallback(this, requestCode, resultCode, data)
        }
    }

    override fun onLoginSuccess(loginType: LoginTag, jsonContent: JSONObject) {
        login(jsonContent, loginType)
    }

    override fun onLoginFailure(loginType: LoginTag, error: String) {
        ToastUtils.showToast(error)
        finish()
    }

    override fun onChanged(response: ApiResponse<UserInfoEntity>?) {
        if (response != null && mLoginDialog != null) {
            mLoginDialog?.dismissAllowingStateLoss()
            mLoginDialog = null
        }

        if (response?.data != null) {
            val loginTokenEntity = UserManager.getInstance().loginTokenEntity
            if (loginTokenEntity != null) {

                val loginType = loginTokenEntity.loginType
                val logUtils = TheRouter.get(ILogUtilsProvider::class.java)
                logUtils?.login("success", loginType, mEntrance)

                if (loginType == LoginTag.oauth.name) {
                    NewFlatLogUtils.logFastLoginResult("成功")
                }

                // 第三方登录方式登录后跳转绑定手机页面（https://gitlab.ghzs.com/pm/halo-app-issues/-/issues/1206）
                val isThirdPartyLogin =
                    LoginTag.qq.name == loginType || LoginTag.wechat.name == loginType || LoginTag.weibo.name == loginType || LoginTag.douyin.name == loginType
                if (isThirdPartyLogin
                    && TextUtils.isEmpty(response.data.loginMobile)
                ) {
                    TheRouter.build(RouteConsts.activity.bindPhoneActivity)
                        .withBoolean(EntranceConsts.KEY_FROM_LOGIN, true)
                        .withBoolean(EntranceConsts.KEY_CHANGE_PHONE, false)
                        .withString(com.therouter.router.KEY_DESCRIPTION, mRouteSource)
                        .navigation(this)
                } else {
                    if (!TextUtils.isEmpty(mRouteSource)) {
                        if (mRouteSource == RouteConsts.Action.LOGIN_SUCCESS_ACTION) {
                            TheRouter.build(RouteConsts.Action.LOGIN_SUCCESS_ACTION).action()
                        } else {
                            TheRouter.build(mRouteSource).navigation(this)
                        }
                    }
                }
            }

            // 防止UserManager数据丢失后重复登录
            if (TextUtils.isEmpty(UserManager.getInstance().token)) {
                mUserViewModel.retryCheckLogin()
            }

            finish()
            if (UserManager.getInstance().isLoggedIn) {
                QuickLoginHelper.finishAuthActivity()

            }
        } else if ((response?.httpException != null || response?.throwable != null) && mLoginTag == LoginTag.oauth) {
            NewFlatLogUtils.logFastLoginResult("失败")
            // 一键登录失败，关闭当前页，关闭授权页，切换到短信验证码登录
            if (!isSmsCodePageStarted) {
                isSmsCodePageStarted = true
                finish()
                QuickLoginHelper.finishAuthActivity()

                startActivity(LoginActivity.getIntent(this, QuickLoginHelper.ENTRANCE_DEFAULT, true))
            }
        }
    }
}