package com.gh.gamecenter.login.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.text.*
import android.text.style.ClickableSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.CheckBox
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.text.getSpans
import androidx.core.view.doOnAttach
import com.alibaba.android.arouter.launcher.ARouter
import com.cmic.gen.sdk.auth.GenAuthnHelper
import com.cmic.gen.sdk.auth.GenTokenListener
import com.cmic.gen.sdk.view.GenAuthThemeConfig
import com.cmic.gen.sdk.view.GenLoginClickListener
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.databinding.SetWaitDialogBinding
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.provider.IConfigProvider
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.login.HaloApp
import com.gh.gamecenter.login.R
import com.gh.gamecenter.login.databinding.LayoutQuickLoginBinding
import com.gh.gamecenter.login.user.LoginTag
import com.gh.gamecenter.login.view.LoginActivity
import com.gh.gamecenter.login.view.QuickLoginHelperActivity
import com.lightgame.utils.AppManager
import com.lightgame.utils.Utils
import org.json.JSONObject

/**
 * 一键登录辅助类
 * 1.取号请求
 * 2.授权请求
 * 3.获取token
 * 4.请求登录接口
 *
 * 一键登录SDK对接文档：http://dev.10086.cn/docInside?contentId=10000067541479
 */
@SuppressLint("StaticFieldLeak")
object QuickLoginHelper {

    private var mAuthnHelper: GenAuthnHelper? = null
    private var mTokenListener: GenTokenListener? = null
    private var mPreDialog: Dialog? = null
    private var mLoggingDialog: Dialog? = null
    private var mToken: String = ""
    private var mEntrance: String = ""
    private var mOpenAuthPageSuccess = false
    private var mPrivacyCheckBox: CheckBox? = null
    private var mOperatorText: CharSequence = ""
    private var mLoginBtn: View? = null
    private const val REQUEST_GET_PHONE_INFO_CODE = 100
    private const val REQUEST_LOGIN_AUTH_CODE = 101
    private const val ENTRANCE_DEFAULT = "一键登录"
    private const val AUTH_ACTIVITY_NAME = "com.cmic.gen.sdk.view.GenLoginAuthActivity"

    // 1.取号请求(可提前进行)
    @JvmStatic
    fun getPhoneInfo() {
        if (isPublishEnv()) {
            GenAuthnHelper.setDebugMode(false)
        } else {
            GenAuthnHelper.setDebugMode(true)
        }

        val config = ARouter.getInstance().build(RouteConsts.provider.config).navigation() as? IConfigProvider
        GenAuthnHelper.getInstance(HaloApp.getInstance().applicationContext).getPhoneInfo(
            config?.getQuickLoginAppId(),
            config?.getQuickLoginAppKey(),
            { requestCode: Int, jsonObject: JSONObject ->
                val code = jsonObject.optString("resultCode")
                // “103000”为成功
                if (code == "103000") {
                    if (requestCode == REQUEST_GET_PHONE_INFO_CODE) {
                        SPUtils.setBoolean(Constants.SP_HAS_GET_PHONE_INFO, true)
                    }
                }
            },
            REQUEST_GET_PHONE_INFO_CODE
        )
    }

    @JvmStatic
    fun startLogin(context: Context, entrance: String) {
        // 防止短时间多次调用
        if (ClickUtils.isFastDoubleClick(991)) return

        mEntrance = entrance
        mOpenAuthPageSuccess = false

        if (isPublishEnv()) {
            GenAuthnHelper.setDebugMode(false)
        } else {
            GenAuthnHelper.setDebugMode(true)
        }

        if (mAuthnHelper == null) {
            initSDK(context)
        }

        if (mTokenListener == null) {
            initTokenListener()
        }

        loginAuth(context)
    }

    private fun initSDK(context: Context) {
        mAuthnHelper = GenAuthnHelper.getInstance(HaloApp.getInstance().applicationContext)
        mAuthnHelper?.run {
            // 设置超时时间
            overTime = 3000

            authThemeConfig = getConfig(context)
            // 授权页面的回调方法
            setPageInListener { code, _ ->
                // 返回码200087代表授权页成功拉起
                if (code == "200087") {
                    if (mPreDialog != null && mPreDialog!!.isShowing) {
                        mPreDialog?.dismiss()
                    }
                    mOpenAuthPageSuccess = true
                    AppManager.getInstance().recentActiveActivity?.run {
                        DisplayUtils.setStatusBarColor(this, R.color.transparent, !DarkModeUtils.isDarkModeOn(context))
                    }
                } else { // 不成功就调起验证码登录页
                    toastCode(code)
                    startCodeLoginPage(true)
                }
            }
        }
    }

    private fun initTokenListener() {
        // token回调
        mTokenListener = GenTokenListener { requestCode: Int, jsonObject: JSONObject ->
            val code = jsonObject.optString("resultCode")
            // “103000”为成功
            if (code == "103000") {
                if (requestCode == REQUEST_LOGIN_AUTH_CODE) {
                    // 3.获取token
                    mToken = jsonObject.optString("token")
                }
            } else if (code != "200020") { // 不成功就调起验证码登录页(200020代表授权页关闭)
                toastCode(code)
                startCodeLoginPage(true)
            }
        }
    }

    private fun loginAuth(context: Context) {
        runOnUiThread {
            val dialogContext = com.gh.gamecenter.common.utils.DialogHelper.checkDialogContext(context)
            if (dialogContext is Activity && dialogContext.isFinishing) return@runOnUiThread
            mPreDialog = dialogContext?.let {
                Dialog(it, R.style.DialogWindowTransparent).apply {
                    val binding = SetWaitDialogBinding.inflate(LayoutInflater.from(dialogContext)).apply {
                        setWaitMessage.text = "请求登录中"
                    }
                    requestWindowFeature(Window.FEATURE_NO_TITLE)
                    setContentView(binding.root)
                    setCanceledOnTouchOutside(false)
                    show()
                }
            }
        }
        // 2.授权请求
        val config = ARouter.getInstance().build(RouteConsts.provider.config).navigation() as? IConfigProvider
        mAuthnHelper?.loginAuth(
            config?.getQuickLoginAppId(),
            config?.getQuickLoginAppKey(),
            mTokenListener,
            REQUEST_LOGIN_AUTH_CODE
        )
    }

    private fun getConfig(context: Context): GenAuthThemeConfig {
        return GenAuthThemeConfig.Builder()
            .setStatusBar(Color.TRANSPARENT, !DarkModeUtils.isDarkModeOn(context)) //状态栏颜色、是否高亮
            .setAuthContentView(getCustomView(context)) //自定义布局
            // 服务条款标题栏
            .setClauseLayoutResID(R.layout.layout_quick_login_navigation, "backIv") //服务条款标题栏
            .setNavTextColor(Color.BLACK) //服务条款标题颜色
            .setNavTextSize(18) //服务条款标题字体大小
            // 手机号码
            .setNumberSize(28, true) //手机号码字体大小
            .setNumberColor(R.color.text_title.toColor(context)) //手机号码字体颜色
            .setNumFieldOffsetY(440) //号码栏Y偏移量
            // 登录按钮
            .setLogBtnImgPath("download_button_normal_style") //登录按钮背景
            .setLogBtnText("一键登录", Color.WHITE, 16, false) //登录按钮相关
            .setLogBtnOffsetY(522) //登录按钮Y偏移量
            .setLogBtn(1000, 44) //登录按钮相关宽高
            .setLogBtnMargin(40, 40) //登录按钮相对于屏幕左右边缘边距
            // 回调
            .setGenBackPressedListener {
                dismissDialog()
                release()
            } //返回键回调
            .setLogBtnClickListener(object : GenLoginClickListener {
                override fun onLoginClickStart(oauthContext: Context, jsonObj: JSONObject?) {
                    runOnUiThread {
                        val dialogContext = com.gh.gamecenter.common.utils.DialogHelper.checkDialogContext(oauthContext)
                        if (dialogContext is Activity && dialogContext.isFinishing) return@runOnUiThread
                        mLoggingDialog = Dialog(oauthContext, R.style.DialogWindowTransparent).apply {
                            val binding = SetWaitDialogBinding.inflate(LayoutInflater.from(oauthContext)).apply {
                                root.background = R.drawable.background_shape_white_radius_8.toDrawable(context)
                                setWaitMessage.setTextColor(R.color.text_title.toColor(context))
                                setWaitMessage.text = R.string.logging.toResString()
                            }
                            requestWindowFeature(Window.FEATURE_NO_TITLE)
                            setContentView(binding.root)
                            setCanceledOnTouchOutside(false)
                            show()
                        }
                        NewFlatLogUtils.logFastLoginChoice("一键登录")
                    }
                }

                override fun onLoginClickComplete(oauthContext: Context, jsonObj: JSONObject?) {
                    if (mToken.isNotBlank()) {
                        // 4.请求登录接口
                        startQuickLoginHelperPage(LoginTag.oauth)
                    }
                }
            }) //登录按钮回调
            .setGenCheckBoxListener { oauthContext: Context, _: JSONObject? ->
                showLoginPolicyDialog(oauthContext, context) {
                    mLoginBtn?.performClick()
                }
            }  //勾选回调
            // 勾选框
            .setCheckTipText("") //设置未勾选时弹出提示
            .setCheckBoxImgPath("ic_selector_selected", "ic_selector_default", 16, 16) //勾选图片
            // 服务条款、用户协议、隐私政策
            .setPrivacyState(false) //默认不勾选
            .setPrivacyAlignment(
                "阅读并同意 " + "用户协议、隐私政策、" + GenAuthThemeConfig.PLACEHOLDER,
                "用户协议", R.string.disclaimer_url.toResString(),
                "隐私政策", R.string.privacy_policy_url.toResString(),
                "", "", "", ""
            ) //隐私条款的协议文本，自定义条款，自定义条款链接(支持四份条款)
            .setPrivacyText(
                12,
                R.color.text_subtitleDesc.toColor(context),
                R.color.text_subtitle.toColor(context),
                true,
                false
            ) //条款文本设置
            .setPrivacyMargin(40, 40) //隐私条款距离手机左右边缘的边距
            .setPrivacyOffsetY(596) //隐私条款Y偏移量
            .setCheckBoxLocation(0)
            // 语言
            .setAppLanguageType(0) //0.中文简体1.中文繁体2.英文
            // 转场动画
//            .setAuthPageActIn("anim_auth_in", "anim_auth_out")
//            .setAuthPageActOut("anim_auth_in","anim_auth_out")
            // 整体布局
            .setAuthPageWindowMode(0, 0) //授权页窗口宽高比例
            .setWindowBottom(0) //授权页是否居于底部，0=居中;1=底部，设置为1Y轴的偏移 失效
            .setFitsSystemWindows(false)
//            .setThemeId(-1) //授权页弹窗主题
            .build()
    }

    // 获取自定义布局View
    @SuppressLint("SetTextI18n")
    private fun getCustomView(context: Context): View {
        return LayoutQuickLoginBinding.inflate(LayoutInflater.from(context)).apply {
            descTv.text = "${getOperatorType()}提供认证服务"
            closeBtn.setOnClickListener {
                finishAuthActivity()
            }
            changeLoginBtn.setOnClickListener {
                checkPolicyAndContinue(context) {
                    startCodeLoginPage(false)
                    NewFlatLogUtils.logFastLoginRelatedShow("mobile_number_verification_show")
                }
            }
            qqBtn.setOnClickListener {
                checkPolicyAndContinue(context) {
                    startQuickLoginHelperPage(LoginTag.qq)
                    NewFlatLogUtils.logFastLoginChoice("QQ")
                }
            }
            wechatBtn.setOnClickListener {
                checkPolicyAndContinue(context) {
                    startQuickLoginHelperPage(LoginTag.wechat)
                    NewFlatLogUtils.logFastLoginChoice("微信")
                }
            }
            weiboBtn.setOnClickListener {
                checkPolicyAndContinue(context) {
                    startQuickLoginHelperPage(LoginTag.weibo)
                    NewFlatLogUtils.logFastLoginChoice("微博")
                }
            }
            root.doOnAttach {
                initView(context, root)
            }
            privacyCheckboxClickView.setOnClickListener {
                mPrivacyCheckBox?.performClick()
            }
        }.root
    }

    private fun checkPolicyAndContinue(context: Context, callback: (() -> Unit)) {
        if (mPrivacyCheckBox?.isChecked == false) {
            AppManager.getInstance().recentActiveActivity?.run {
                showLoginPolicyDialog(this, context, callback)
            }
        } else {
            callback.invoke()
        }
    }

    private fun showLoginPolicyDialog(oauthContext: Context, context: Context, callback: (() -> Unit)) {
        DialogHelper.showLoginPolicyDialog(
            oauthContext,
            context,
            true,
            mOperatorText
        ) {
            mPrivacyCheckBox?.isChecked = true
            callback.invoke()
        }
        NewFlatLogUtils.logFastLoginRelatedShow("login_privacy_policy_pop_show")
    }

    private fun initView(context: Context, root: View) {
        NewFlatLogUtils.logFastLoginRelatedShow("fast_login_show")

        (root.parent as? ViewGroup)?.run {
            setBackgroundColor(R.color.background_white.toColor(context))

            val phoneNumTv = (getChildAt(1) as? ViewGroup)?.getChildAt(0) as? TextView
            phoneNumTv?.run {
                includeFontPadding = false
                text = text.toString().replace("*", "･")
            }

            mLoginBtn = getChildAt(2)
            mLoginBtn?.background = R.drawable.download_button_normal_style.toDrawable(context)

            val privacyContainer = getChildAt(3) as? ViewGroup
            privacyContainer?.run {
                mPrivacyCheckBox = (getChildAt(0) as? ViewGroup)?.getChildAt(0) as? CheckBox
                mPrivacyCheckBox?.run {
                    setOnCheckedChangeListener { buttonView, isChecked ->
                        if (isChecked) {
                            buttonView.background =
                                AppCompatResources.getDrawable(context, R.drawable.ic_selector_selected)
                        } else {
                            buttonView.background =
                                AppCompatResources.getDrawable(context, R.drawable.ic_selector_default)
                        }
                    }
                    background = AppCompatResources.getDrawable(context, R.drawable.ic_selector_default)
                }

                val privacyTv = getChildAt(1) as? TextView
                privacyTv?.run {
                    layoutParams = (layoutParams as ViewGroup.MarginLayoutParams).apply {
                        leftMargin = 4F.dip2px()
                    }
                    includeFontPadding = false
                    val index = text.indexOfLast { it == '、' } + 1
                    mOperatorText = text.substring(index, text.length)
                    val spans = (text as SpannableString).getSpans<ClickableSpan>(0, text.length)
                    text = getPrivacyContent(text.replace(" ".toRegex(), ""), spans)
                }
            }
        }

        root.bringToFront()
    }

    private fun getPrivacyContent(content: CharSequence, spans: Array<out ClickableSpan>): SpannableStringBuilder? {
        return SpannableStringBuilder(content).apply {
            val hypertextList = arrayListOf(
                mOperatorText.toString(),
                "《用户协议》",
                "《隐私政策》",
            )
            val positionListPairList = arrayListOf<Pair<Int, Int>>()

            for (hypertext in hypertextList) {
                val index = indexOf(hypertext, 0)
                if (index != -1) {
                    positionListPairList.add(Pair(index, index + hypertext.length))
                }
            }

            for ((index, hypertextPositionPair) in positionListPairList.withIndex()) {
                setSpan(object : ClickableSpan() {
                    override fun updateDrawState(ds: TextPaint) {
                        super.updateDrawState(ds)
                        spans[index].updateDrawState(ds)
                        ds.isUnderlineText = true
                    }

                    override fun onClick(widget: View) {
                        spans[index].onClick(widget)
                    }
                }, hypertextPositionPair.first, hypertextPositionPair.second, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
        }
    }

    // 获取运营商名称
    private fun getOperatorType(): String {
        mAuthnHelper?.run {
            val jsonObject = getNetworkType(HaloApp.getInstance().applicationContext)
            tryWithDefaultCatch {
                return when (jsonObject.optString("operatortype").toInt()) {
                    1 -> "中国移动"
                    2 -> "中国联通"
                    3 -> "中国电信"
                    else -> ""
                }
            }
        }
        return ""
    }

    // 打开验证码登录页
    private fun startCodeLoginPage(isFinishAuth: Boolean) {
        if (mPreDialog != null && mPreDialog!!.isShowing) {
            tryWithDefaultCatch {
                mPreDialog?.dismiss()
            }
        }

        if (isFinishAuth) {
            finishAuthActivity()
        }

        AppManager.getInstance().recentActiveActivity?.run {
            startActivity(
                LoginActivity.getIntent(
                    this,
                    if (mOpenAuthPageSuccess) ENTRANCE_DEFAULT else mEntrance,
                    mOpenAuthPageSuccess
                )
            )
        }
    }

    // 打开快速登录辅助页
    private fun startQuickLoginHelperPage(loginTag: LoginTag) {
        AppManager.getInstance().recentActiveActivity?.run {
            val intent = Intent(this, QuickLoginHelperActivity::class.java).apply {
                putExtra(EntranceConsts.KEY_ENTRANCE, mEntrance)
                putExtra(EntranceConsts.KET_TYPE, loginTag)
                if (loginTag == LoginTag.oauth) {
                    putExtra(EntranceConsts.KEY_DATA, mToken)
                }
            }
            startActivity(intent)
        }
    }

    @JvmStatic
    fun finishAuthActivity() {
        dismissDialog()
        mAuthnHelper?.quitAuthActivity()
        // 调用quitAuthActivity()方法有概率会关不掉授权页，所以使用在调用quitAuthActivity()方法后，判断当前Activity是否还是AuthActivity，如果是则finish
        AppManager.getInstance().recentActiveActivity?.run {
            if (localClassName == AUTH_ACTIVITY_NAME) {
                finish()
            }
        }
        release()
    }

    private fun toastCode(code: String) {
        debugOnly {
            Utils.log("QuickLoginHelper -> code = $code")
        }

//        if (code == "200023" || code == "200028") {
//            toast("验证码登录")
//        } else {
//            toast(code)
//        }
    }

    private fun dismissDialog() {
        if (mPreDialog != null && mPreDialog!!.isShowing) {
            mPreDialog?.dismiss()
        }
        if (mLoggingDialog != null && mLoggingDialog!!.isShowing) {
            mLoggingDialog?.dismiss()
        }
    }

    private fun release() {
        mAuthnHelper = null
        mTokenListener = null
        mPreDialog = null
        mLoggingDialog = null
        mPrivacyCheckBox = null
        mLoginBtn = null
    }
}