package com.gh.gamecenter.login.view

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.gamecenter.common.constant.Constants
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.core.provider.ILogUtilsProvider
import com.gh.gamecenter.core.utils.SPUtils
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 org.json.JSONObject

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

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

    override fun getLayoutId() = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mUserViewModel.loginObsUserinfo.observe(this, this)
        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 = ARouter.getInstance().build(RouteConsts.provider.logUtils).navigation() as? ILogUtilsProvider
        logUtils?.login("logging", loginTag.name, mEntrance)
        if (loginTag != LoginTag.oauth) {
            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) {
        toast(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 =
                    ARouter.getInstance().build(RouteConsts.provider.logUtils).navigation() as? ILogUtilsProvider
                logUtils?.login("success", loginType, mEntrance)

                if (loginType == LoginTag.oauth.name) {
                    SPUtils.setBoolean(Constants.SP_HAS_GET_PHONE_INFO, false)
                    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)
                ) {
                    ARouter.getInstance().build(RouteConsts.activity.bindPhoneActivity)
                        .withBoolean(EntranceConsts.KEY_FROM_LOGIN, true)
                        .withBoolean(EntranceConsts.KEY_CHANGE_PHONE, false)
                        .navigation()
                }
            }

            // 防止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("失败")
        }
    }
}