package com.gh.gamecenter

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.CheckBox
import android.widget.FrameLayout
import androidx.core.view.WindowCompat
import androidx.core.view.doOnAttach
import cn.com.chinatelecom.account.api.CtAuth
import cn.jiguang.verifysdk.api.*
import com.gh.gamecenter.common.base.GlobalActivityManager.getCurrentPageEntity
import com.gh.gamecenter.common.databinding.SetWaitDialogBinding
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.provider.ILoginProvider
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.quicklogin.R
import com.lightgame.utils.AppManager
import com.lightgame.utils.Utils
import com.therouter.TheRouter

@SuppressLint("StaticFieldLeak")
object LoginHelper {
    // final
    private const val TAG = "LoginHelper"
    private const val TIME_OUT_DURATION = 5000
    private const val PRE_LOGIN_CODE_SUCCESS = 7000
    private const val LOGIN_AUTH_CODE_SUCCESS = 6000
    private const val LOGIN_AUTH_CODE_FAILURE = 6001

    // field
    private var isDarkMode = false
    private var openAuthPageSuccess = false
    private var isPolicyCheck = false
    private var loginToken: String = ""
    private var rlLogin: View? = null

    // view
    private var preDialog: Dialog? = null

    //请注意，这里有可能会出现内存泄漏，需要及时清理
    @SuppressLint("StaticFieldLeak")
    private var backgroundView: View? = null
    private var cbPrivacy: CheckBox? = null

    private var loginProvider: ILoginProvider? = null
    fun getLoginProvider(): ILoginProvider? =
        loginProvider ?: (TheRouter.get(ILoginProvider::class.java))
            ?.also {
                loginProvider = it
            }

    fun init(app: Application) {
        JVerificationInterface.init(
            app, TIME_OUT_DURATION
        ) { code, msg ->
            Utils.log(TAG, "init:$code -- $msg")
            // no implement
        }
    }

    fun preLogin(context: Context) {
        JVerificationInterface.setDebugMode(EnvHelper.isDevEnv)
        if (JVerificationInterface.isInitSuccess()) {
            JVerificationInterface.preLogin(
                context, TIME_OUT_DURATION
            ) { code, a, b ->
                Utils.log(TAG, "preLogin:$code -- $a -- $b")
                if (code == PRE_LOGIN_CODE_SUCCESS) {
                }
            }
        }
    }

    fun loginAuth(context: Context, continuablePath: String?, callback: (() -> Unit)?) {
        runOnUiThread {
            val dialogContext = DialogHelper.checkDialogContext(context)
            if (dialogContext is Activity && (dialogContext.isFinishing || dialogContext.isDestroyed)) return@runOnUiThread
            preDialog = try {
                dialogContext?.let {
                    Dialog(it, com.gh.gamecenter.common.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()
                    }
                }
            } catch (e: Exception) {
                // no implement
                null
            }
        }
        isDarkMode = DarkModeUtils.isDarkModeOn(context)
        setUiConfig(context, continuablePath, callback)
        val settings = LoginSettings()
        settings.isAutoFinish = false
        settings.timeout = 5 * 1000

        var isLoginLauncher = false
        settings.authPageEventListener = object : AuthPageEventListener() {
            override fun onEvent(cmd: Int, msg: String?) {
                Utils.log(TAG, "event:$cmd -- msg:$msg")

                when (cmd) {
                    2 -> {  // 成功拉起授权页
                        if (!isLoginLauncher) {
                            SensorsBridge.trackEvent(
                                "LoginPageShow",
                                "last_page_name", getCurrentPageEntity().pageName,
                                "last_page_id", getCurrentPageEntity().pageId,
                                "last_page_business_id", getCurrentPageEntity().pageBusinessId
                            )
                        }
                        isLoginLauncher = true
                        openAuthPageSuccess = true
                        if (preDialog?.isShowing == true) {
                            preDialog?.dismiss()
                        }
                    }

                    6 -> {  // 勾选了同意隐私权限
                        isPolicyCheck = true
                    }

                    7 -> {   // 取消勾选同意隐私权限
                        isPolicyCheck = false
                    }

                    8 -> {  // 点击了一键登录按钮
                        SensorsBridge.trackEvent("Login", "login_type", "一键登录")
                    }
                }
            }
        }

        JVerificationInterface.loginAuth(
            context, settings,
        ) { code, content, operator, operatorReturn ->

            Utils.log(TAG, "loginAuth:$code -- $content -- $operator -- $operatorReturn")
            when (code) {
                LOGIN_AUTH_CODE_SUCCESS -> {
                    loginToken = content
                    getLoginProvider()?.startQuickLoginHelperPageFromQuickLogin(
                        content,
                        context,
                        continuablePath,
                        callback
                    )
                }

                LOGIN_AUTH_CODE_FAILURE -> {
                    getLoginProvider()?.startCodeLoginPageFromQuickLogin(
                        openAuthPageSuccess,
                        context,
                        continuablePath,
                        callback
                    )
                }
            }
        }
    }

    private fun dismissDialog() {
        if (preDialog?.isShowing == true) {
            preDialog?.dismiss()
        }
    }

    private fun setUiConfig(context: Context, continuablePath: String?, callback: (() -> Unit)?) {
        backgroundView = getLoginProvider()?.createQuickLoginBackgroundView(context)
        val beanArrayList: MutableList<PrivacyBean> = ArrayList()
        beanArrayList.add(PrivacyBean("用户协议", com.gh.gamecenter.common.R.string.disclaimer_url.toResString(), ", "))
        beanArrayList.add(
            PrivacyBean(
                "隐私政策",
                com.gh.gamecenter.common.R.string.privacy_policy_url.toResString(),
                ", "
            )
        )

        val btnLoginWidth =
            (context.resources.displayMetrics.widthPixels / context.resources.displayMetrics.density - 80).toInt()

        val uiConfig = JVerifyUIConfig.Builder()
            // 状态栏
            .setStatusBarTransparent(true)
            .setVirtualButtonHidden(true)
            // 导航栏
            .setNavHidden(true)
            // logo
            .setLogoHidden(true)
            // 号码栏
            .setNumberSize(28) //手机号码字体大小
            .setNumberTextBold(true)
            .setNumberColor(com.gh.gamecenter.common.R.color.text_primary.toColor(context)) //手机号码字体颜色
            .setNumberFieldOffsetBottomY(298) //号码栏Y偏移量
            // slogan
            .setSloganTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(context))
            .setSloganTextSize(12)
            .setSloganOffsetY(-1)
            .setSloganBottomOffsetY(278)
            // 登录按钮
            .setLogBtnImgPath("download_button_normal_style") //登录按钮背景
            .setLogBtnText("一键登录") //登录按钮相关
            .setLogBtnTextColor(Color.WHITE)
            .setLogBtnTextSize(16)
            .setLogBtnTextBold(false)
            .setLogBtnWidth(btnLoginWidth)
            .setLogBtnHeight(44)
            .setLogBtnOffsetY(-1)
            .setLogBtnBottomOffsetY(202)
            .setPrivacyCheckDialogLogBtnImgPath("download_button_normal_style")
            .setCheckedImgPath("ic_selector_selected")
            .setUncheckedImgPath("ic_selector_default")
            .setPrivacyCheckboxSize(16)
            .setPrivacyTextSize(12)
            // 服务条款、用户协议、隐私政策
            .setPrivacyState(false) //默认不勾选
            .setPrivacyUnderlineText(true)
            .setPrivacyOffsetY(140)
            .setAppPrivacyColor(
                com.gh.gamecenter.common.R.color.text_tertiary.toColor(context),
                com.gh.gamecenter.common.R.color.text_tertiary.toColor(context)
            )
            .setPrivacyNameAndUrlBeanList(
                beanArrayList
            )
            .setDimAmount(1.0f)
            .setLoginActionListener { authContext, _, _, _ ->
                showPrivacyCheckDialog(authContext, context, getOperatorPrivacyText(context)) {
                    rlLogin?.performClick()
                }
            }
            .setPrivacyUnderlineText(true)
            .setPrivacyWithBookTitleMark(true)
            .setAppPrivacyColor(
                com.gh.gamecenter.common.R.color.text_tertiary.toColor(context),
                com.gh.gamecenter.common.R.color.text_secondary.toColor(context)
            )
            .setPrivacyMarginL(40) //隐私条款距离手机左右边缘的边距
            .setPrivacyMarginR(40)
            // 添加自定义布局
            .addBottomView(getCustomView(context, continuablePath, callback)) { _, _ -> }
            .setStatusBarDarkMode(false)
            .build()
        JVerificationInterface.setCustomUIWithConfig(uiConfig)
    }

    private fun getCustomView(context: Context, continuablePath: String?, callback: (() -> Unit)?): View? {
        return getLoginProvider()?.createCustomView(context, continuablePath, callback)
            ?.also { root ->
                root.doOnAttach {
                    initView(it)
                }
            }
    }

    private fun initView(root: View) {
        val parent = root.parent as? ViewGroup
        val containerView = parent?.getChildAt(2) as? ViewGroup
        if (containerView != null) {
            rlLogin = (containerView.getChildAt(1) as? ViewGroup)?.getChildAt(2)
            cbPrivacy =
                ((containerView.getChildAt(2) as? ViewGroup)
                    ?.getChildAt(0) as? ViewGroup)
                    ?.getChildAt(0) as? CheckBox
        }
    }

    private fun showPrivacyCheckDialog(
        authContext: Context,
        context: Context,
        privacyText: String,
        callback: () -> Unit
    ) {
        loginProvider?.showLoginPolicyDialog(authContext, context, true, privacyText) {
            cbPrivacy?.isChecked = true
            callback()
        }
    }

    private fun getOperatorPrivacyText(context: Context): String {
        return try {
            when (CtAuth.getInstance().operatorType) {
                "CT" -> context.getString(R.string.operator_privacy_text_ct)
                "CU" -> context.getString(R.string.operator_privacy_text_cu)
                "CM" -> context.getString(R.string.operator_privacy_text_cm)
                else -> ""
            }
        } catch (_: Exception) {
            ""
        }
    }

    fun checkPolicyAndContinue(context: Context, callback: () -> Unit) {
        if (isPolicyCheck) {
            callback()
        } else {
            AppManager.getInstance().recentActiveActivity?.run {
                showPrivacyCheckDialog(this, context, getOperatorPrivacyText(context)) {
                    callback()
                }
            }
        }
    }

    fun addCustomViewToLoginAuthPage(activity: Activity) {
        val decorView = activity.window.decorView
        WindowCompat.getInsetsController(activity.window, decorView)?.isAppearanceLightStatusBars = !isDarkMode
        val contentView = decorView.findViewById<FrameLayout>(android.R.id.content)
        contentView?.post {
            // backgroundView为什么要在QuickLoginHelper中初始化呢？
            // 因为当前activity为第三方sdk提供，不支持深色模式，所以需要使用光环activity的Context初始化View以适配深色模式
            val backgroundView = backgroundView
            val childCount = contentView.childCount
            if (childCount == 1 && backgroundView != null) {
                // 1. 容器View设为透明
                val firstView = contentView.getChildAt(0)
                firstView?.setBackgroundColor(Color.TRANSPARENT)
                // 2.在最底部添加背景View
                contentView.addView(backgroundView, 0)
            }

        }
    }

    fun finishAuthActivity() {
        dismissDialog()
        JVerificationInterface.dismissLoginAuthActivity()
    }

    fun release() {
        backgroundView = null
        preDialog = null
        isPolicyCheck = false
        loginToken = ""
        openAuthPageSuccess = false
    }


}