package com.gh.gamecenter.login.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.gh.gamecenter.common.avoidcallback.AvoidOnResultManager
import com.gh.gamecenter.common.avoidcallback.Callback
import com.therouter.TheRouter
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.core.provider.IQuickLoginProvider
import com.gh.gamecenter.core.utils.CurrentActivityHolder
import com.gh.gamecenter.login.databinding.LayoutQuickLoginBinding
import com.gh.gamecenter.login.user.LoginTag
import com.therouter.router.Navigator
import com.therouter.router.action.interceptor.ActionInterceptor
import java.lang.ref.WeakReference

/**
 * 一键登录辅助类
 * 1.取号请求
 * 2.授权请求
 * 3.获取token
 * 4.请求登录接口
 *
 * 一键登录SDK对接文档：https://docs.jiguang.cn/jverification/client/android_guide
 */
@SuppressLint("StaticFieldLeak")
object QuickLoginHelper {
    private var entrance: String = ""

    const val ENTRANCE_DEFAULT = "一键登录"

    private var quickLoginProvider: IQuickLoginProvider? = null
    private fun getQuickLoginProvider(): IQuickLoginProvider? =
        quickLoginProvider
            ?: TheRouter.get(IQuickLoginProvider::class.java)
                ?.also {
                    quickLoginProvider = it
                }


    @JvmStatic
    fun init(app: Application) {
        getQuickLoginProvider()?.init(app)
    }

    @JvmStatic
    fun preLogin(context: Context) {
        getQuickLoginProvider()?.preLogin(context)
    }

    @JvmStatic
    fun startLogin(context: Context,
                   entrance: String,
                   continuablePath: String? = null,
                   callback: (() -> Unit)? = null) {
        getQuickLoginProvider()?.startLogin(context, entrance, continuablePath, callback)
    }

    fun createCustomView(context: Context, continuablePath: String?, callback: (() -> Unit)?): View {
        return LayoutQuickLoginBinding.inflate(LayoutInflater.from(context)).apply {
            closeBtn.setOnClickListener {
                finishAuthActivity()
            }
            changeLoginBtn.setOnClickListener {
                startCodeLoginPage(true, context, continuablePath, callback)
                NewFlatLogUtils.logFastLoginRelatedShow("mobile_number_verification_show")
            }
            qqBtn.setOnClickListener {
                getQuickLoginProvider()?.checkPolicyAndContinue(context) {
                    startQuickLoginHelperPage(LoginTag.qq, context = context, continuablePath = continuablePath, callback = callback)
                    NewFlatLogUtils.logFastLoginChoice("QQ")
                }
            }
            wechatBtn.setOnClickListener {
                getQuickLoginProvider()?.checkPolicyAndContinue(context) {
                    startQuickLoginHelperPage(LoginTag.wechat, context = context, continuablePath = continuablePath, callback = callback)
                    NewFlatLogUtils.logFastLoginChoice("微信")
                }
            }
            weiboBtn.setOnClickListener {
                getQuickLoginProvider()?.checkPolicyAndContinue(context) {
                    startQuickLoginHelperPage(LoginTag.weibo, context = context, continuablePath = continuablePath, callback = callback)
                    NewFlatLogUtils.logFastLoginChoice("微博")
                }
            }
        }.root
    }

    // 打开验证码登录页
    fun startCodeLoginPage(openAuthPageSuccess: Boolean, context: Context, continuablePath: String?, callback: (() -> Unit)?) {
        CurrentActivityHolder.getCurrentActivity()?.run {
            val navigator = TheRouter.build(RouteConsts.activity.loginActivity)
                .withString(EntranceConsts.KEY_ENTRANCE, if (openAuthPageSuccess) ENTRANCE_DEFAULT else entrance)
                .withBoolean(EntranceConsts.KEY_FROM_QUICK_LOGIN, openAuthPageSuccess)
                .withString(com.therouter.router.KEY_DESCRIPTION, continuablePath)

            if (callback == null) {
                navigator.navigation(this)
            } else {
                val intent = navigator.createIntent(this)

                if (this is AppCompatActivity) {
                    AvoidOnResultManager.getInstance(this).startForResult(intent, object : Callback {
                        override fun onActivityResult(resultCode: Int, data: Intent?) {
                            callback.invoke()
                        }
                    })
                } else {
                    // 不回调，正常跳转
                    context.startActivity(intent)
                }
            }
        }
    }

    // 打开快速登录辅助页
    fun startQuickLoginHelperPage(
        loginTag: LoginTag,
        loginToken: String = "",
        context: Context,
        continuablePath: String?,
        callback: (() -> Unit)?
    ) {
        CurrentActivityHolder.getCurrentActivity()?.run {
            val navigator = TheRouter.build(RouteConsts.activity.quickLoginActivity)
                .withString(EntranceConsts.KEY_ENTRANCE, entrance)
                .withSerializable(EntranceConsts.KET_TYPE, loginTag)
                .withString(com.therouter.router.KEY_DESCRIPTION, continuablePath)
                .also {
                    if (loginTag == LoginTag.oauth) {
                        it.withString(EntranceConsts.KEY_DATA, loginToken)
                    }
                }

            if (callback == null) {
                navigator.withString(com.therouter.router.KEY_DESCRIPTION, continuablePath)
            } else {
                // 避免内存泄漏
                val callbackRef = WeakReference(callback)
                navigator.withString(com.therouter.router.KEY_DESCRIPTION, RouteConsts.Action.LOGIN_SUCCESS_ACTION)
                TheRouter.addActionInterceptor(
                    RouteConsts.Action.LOGIN_SUCCESS_ACTION,
                    object : ActionInterceptor() {
                        override fun handle(context: Context, navigator: Navigator): Boolean {
                            callbackRef.get()?.invoke()
                            TheRouter.removeActionInterceptor(
                                RouteConsts.Action.LOGIN_SUCCESS_ACTION,
                                this
                            )
                            return super.handle(context, navigator)
                        }
                    }
                )
            }

            navigator.navigation(this)
        }
    }

    fun isLoginAuthPage(activity: Activity): Boolean {
        val activityName = activity.javaClass.simpleName
        return "GenLoginAuthActivity" == activityName
                || "CtLoginActivity" == activityName
                || "LoginAuthActivity" == activityName
    }

    /**
     * 由于第三方sdk的容器布局默认携带padding，这里为了能让背景图能够延伸到状态栏,需要进行两步操作
     * 1.直接将自定义布局添加到sdk容器布局下方
     * 2.将sdk的容器View背景设为透明，以显示背景图
     */
    fun addCustomViewToLoginAuthPage(activity: Activity) {
        getQuickLoginProvider()?.addCustomViewToLoginAuthPage(activity)
    }

    @JvmStatic
    fun finishAuthActivity() {
        getQuickLoginProvider()?.finishAuthActivity()
    }


    fun release() {
        getQuickLoginProvider()?.release()
    }
}