package com.yidianling.user.ui.login

import android.content.pm.ActivityInfo
import android.graphics.Color
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import com.alibaba.android.arouter.launcher.ARouter
import com.meituan.android.walle.WalleChannelReader
import com.mobile.auth.gatewayauth.*
import com.mobile.auth.gatewayauth.model.TokenRet
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.utils.LogUtil
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool

/**
 * Created by Ykai on 2020/12/22.
 *
 * 一键登录辅助类
 * TokenResultListener内存泄漏
 * sdk内部会持有外部设置进来的TokenResultListener，在⼀键登录功能使⽤完毕之后通过
 */
object OneKeyLoginHelp {
    private const val YDL_USER_APP_KEY =
        "cl6yPRBkrpRfZpTPkTKoa1+/J+muUvPMPR2HRb0oll24XnyeLPGRDtla7p54HBd3362GfxhNJLYHaaEPHKwl16lDpvNbJ9mm+VbcYQTSX3NK+apSz2/8ul7lMWrGI/1HRyQ9G7njyI3e5BW3FBVqMh3dssocaraDJgbnQds+5ajWM7kklcSy9c8k49TegzBqmj/6ENqNLG1JNgtfTXmBOPQAs9DZVWh+bUN6SfE/tCRuUEb9zriAkP/TY1ouYvXXQU1Ivjy6S7xMJduTNqHrnuUW93D1r1/v"
    private const val YDL_EXPERT_APP_KEY =
        "i4Y/PVRAz4P/aqajQF7SOd3JUIKEsJbRurH04azLyX6N2upi292OrLHECRmtTVAqY24HFjwUjW1QjRwJA9aFbNzl3zl7L5DEDBZ4+QSU28vq34HccmAjAeUCC7qCHbN7QLVZqhVpuYUCMZ5fp2NdhANJl/741wHccdPk/Un5c4larDNuv1KEo2OZOds2J1WFiBx7giWtzli4NwMq9x+9sb0aXPZZQ9C9Kr8T/0+/ccYdotwFm7XWenNs/G3Jy1HHVqqOCDecKPbyXR+cV0jBUisSjv+SEUTfpcc3iUGH5OjZyQ6OfaLkdjATsr5K9oVP"
    const val YDL_USER_APP = 1
    const val YDL_EXPERT_APP = 2
    var mPhoneNumberAuthHelper: PhoneNumberAuthHelper? = null
    private var mAppType: Int = YDL_USER_APP
    var mIsGetTokenSuccess = true    // 获取token是否成功，默认是成功
    var mIsOpenOneKeyLogin = false   // 是否开启一键登录
    var mIsFromGuide = true
    var mAuthType = PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN              // 1：本机号码校验 2: ⼀键登录
    private var checkBoxHidden = true         // 协议勾选框是否展示
    private lateinit var mActivity: BaseActivity


    fun sdkInit(activity: BaseActivity, appType: Int, authType: Int) {
        mActivity = activity
        mAppType = appType
        mAuthType = authType
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(activity, mTokenListener)
        mPhoneNumberAuthHelper?.let {
            // APP是否处于调试状态，使⽤ getReporter.setLoggerEnable(true) 可以关闭此项检测
            it.reporter.setLoggerEnable(true)
            // 设置密钥
            if (appType == YDL_USER_APP) {
                it.setAuthSDKInfo(YDL_USER_APP_KEY)
            } else if (appType == YDL_EXPERT_APP) {
                it.setAuthSDKInfo(YDL_EXPERT_APP_KEY)
            }
        }
        // 获取渠道
        val channel = WalleChannelReader.getChannel(activity)
        checkBoxHidden = !(channel=="huawei"||channel=="vivo")

    }

    /**
     * 检查认证环境
     *
     */
    fun checkEnvAvailable(authType: Int) {
        mAuthType = authType
        if (!mIsGetTokenSuccess) {
            setAuthListener()
        }
        mPhoneNumberAuthHelper?.checkEnvAvailable(authType)    //  type 1：本机号码校验 2: ⼀键登录
    }


    /**
     * 设置token监听
     *
     */
    private fun setAuthListener() {
        mPhoneNumberAuthHelper?.setAuthListener(mTokenListener)
    }

    /**
     * 打开登录界面
     *
     */
    fun toLoginActivity() {
        ARouter.getInstance().build("/user/login")
            .withBoolean("bind_phone", false)
            .withBoolean("isFromGuide", mIsFromGuide)
            .navigation()
    }


    /**
     * 本机手机号码校验
     *
     */
    fun getVerifyToken() {
        mAuthType = PhoneNumberAuthHelper.SERVICE_TYPE_AUTH
        if (!mIsGetTokenSuccess) {
            setAuthListener()
        }
        mPhoneNumberAuthHelper?.getVerifyToken(5000)  // 5000表示超时时间 单位ms
    }

    /**
     * 拉起一键登录界面
     *
     * @param isOpenDialog 是否是弹窗
     */
    fun getLoginToken(isOpenDialog: Boolean) {
        mIsFromGuide = isOpenDialog
        mAuthType = PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN
        mPhoneNumberAuthHelper?.let {
            if (!mIsGetTokenSuccess) {
                setAuthListener()
            }
            // 打开页面
            if (isOpenDialog) {
                openDialog(it)
            } else {
                openPage(it)
            }
            // 拉起一键登录页面
            it.getLoginToken(mActivity, 5000) // 5000表示超时时间 单位ms
        }
    }

    /**
     * 设置界面UI,并打开页面
     *
     */
    private fun openPage(phoneNumberAuthHelper: PhoneNumberAuthHelper) {
        // 每次打开页面前先清空所有的自定义控件，再重新设置
        phoneNumberAuthHelper.removeAuthRegisterXmlConfig()
        phoneNumberAuthHelper.removeAuthRegisterViewConfig()

        //自定义认证商显示控件
        val tvAuth = TextView(mActivity)
        val tvAuthParams = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
        )
        tvAuthParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE)
        tvAuthParams.setMargins(0, RxImageTool.dp2px(250f), 0, 0)
        when (phoneNumberAuthHelper.currentCarrierName) {
            "CUCC" -> {
                tvAuth.text = "中国联通提供认证服务"
            }
            "CMCC" -> {
                tvAuth.text = "中国移动提供认证服务"
            }
            "CTCC" -> {
                tvAuth.text = "中国电信提供认证服务"
            }
        }
        tvAuth.setTextColor(Color.parseColor("#999999"))
        tvAuth.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)
        tvAuth.gravity = Gravity.CENTER
        tvAuth.layoutParams = tvAuthParams
        //一键登录添加自定义控件
        phoneNumberAuthHelper.addAuthRegistViewConfig(
            "tv_auth", AuthRegisterViewConfig.Builder()
                .setView(tvAuth)
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .build()
        )

        //自定义验证码登录按钮
        val otherLogin = TextView(mActivity)
        val layoutParams = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RxImageTool.dp2px(50f)
        )
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE)
        layoutParams.setMargins(
            RxImageTool.dp2px(40f),
            0,
            RxImageTool.dp2px(40f),
            RxImageTool.dp2px(68f)
        )
        otherLogin.text = "其他方式登录"
        otherLogin.setTextColor(Color.parseColor("#666666"))
        otherLogin.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
        otherLogin.gravity = Gravity.CENTER
        otherLogin.layoutParams = layoutParams
        phoneNumberAuthHelper.addAuthRegistViewConfig(
            "other_login", AuthRegisterViewConfig.Builder()
                .setView(otherLogin)
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .setCustomInterface {
                    phoneNumberAuthHelper.quitLoginPage()
                    toLoginActivity()
                }
                .build()
        )
        var loginLogo = "ic_ydl_login_logo"
        var loginHeight = 40
        var loginWidth = 118
        var appPrivacyOneTip = "壹点灵用户使用协议"
        var appPrivacyOne = "https://h5.ydl.com/SDUserProtol"
        var appPrivacyTwo = "https://m.ydl.com/Protol/yinsi"
        if (mAppType == YDL_EXPERT_APP) {
            loginLogo = "ic_expert_login_logo"
            loginHeight = 60
            loginWidth = 60
            appPrivacyOneTip = "壹点灵专家使用协议"
        }
        phoneNumberAuthHelper.setAuthUIConfig(
            AuthUIConfig.Builder()
                .setStatusBarColor(Color.TRANSPARENT)
                .setWebViewStatusBarColor(Color.TRANSPARENT)
                .setStatusBarUIFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
                .setNavHidden(true) //  设置一键登录页面标题栏隐藏
                .setWebNavTextColor(Color.parseColor("#242424")) //  设置协议页面标题字体颜色
                .setWebNavColor(Color.WHITE)
                .setLightColor(true) //设置状态栏文字颜色,true为黑色
                .setWebNavReturnImgPath("common_ic_back") //  设置协议页返回按钮
                .setLogoImgPath(loginLogo) //  设置登录logo
                .setLogoScaleType(ImageView.ScaleType.FIT_CENTER)
                .setLogoHeight(loginHeight) //  设置登录logo高度
                .setLogoWidth(loginWidth) //  设置登录logo宽度
                .setLogoOffsetY(35) //  设置登录logo距离顶部距离
                .setSloganHidden(true) //  设置slogan是否隐藏
                .setNumberColor(Color.parseColor("#242424"))
                .setNumberSize(24)
                .setNumFieldOffsetY(215)
                .setLogBtnBackgroundPath("bg_one_click_login") //  设置登录按钮背景图片
                .setLogBtnTextColor(Color.parseColor("#ffffff")) //  设置登录按钮文字颜色
                .setLogBtnTextSize(15)
                .setLogBtnMarginLeftAndRight(40) //  设置登录按钮距离左右距离
                .setLogBtnHeight(78)
                .setSwitchAccText("切换号码")
                .setSwitchAccTextSize(15)
                .setSwitchAccTextColor(Color.parseColor("#1DA1F2"))
                .setAppPrivacyOne(appPrivacyOneTip, appPrivacyOne)
                .setAppPrivacyTwo("隐私协议", appPrivacyTwo)
                .setAppPrivacyColor(Color.parseColor("#999999"), Color.parseColor("#1da1f2"))
                .setCheckboxHidden(checkBoxHidden) //  设置是否同意协议的checkbox隐藏
                .setPrivacyBefore("登录即代表您同意")
                .setScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) //  设置竖屏
                .setAuthPageActIn("in_activity", "out_activity")
                .setAuthPageActOut("in_activity", "out_activity")
                .create()
        )
    }

    /**
     * 设置弹窗UI,并打开弹窗
     *
     */
    private fun openDialog(phoneNumberAuthHelper: PhoneNumberAuthHelper) {
        // 每次打开页面前先清空所有的自定义控件，再重新设置
        phoneNumberAuthHelper.removeAuthRegisterXmlConfig()
        phoneNumberAuthHelper.removeAuthRegisterViewConfig()

        val dialogHeight = RxImageTool.px2dp((RxDeviceTool.getScreenHeight(mActivity) * 0.45f))
        phoneNumberAuthHelper.setAuthUIConfig(
            AuthUIConfig.Builder()
                .setStatusBarColor(Color.TRANSPARENT)
                .setWebViewStatusBarColor(Color.TRANSPARENT)
                .setStatusBarUIFlag(View.SYSTEM_UI_FLAG_LOW_PROFILE)
                .setNavText("登录解锁更多功能")
                .setNavTextColor(Color.parseColor("#242424"))
                .setWebNavTextColor(Color.parseColor("#242424")) //  设置协议页面标题字体颜色
                .setNavReturnImgPath("one_key_login_dialog_close")
                .setWebNavColor(Color.WHITE)
                .setLightColor(true) //设置状态栏文字颜色,true为黑色
                .setWebNavReturnImgPath("common_ic_back") //  设置协议页返回按钮
                .setSloganHidden(true) //  设置slogan是否隐藏
                .setNumberColor(Color.parseColor("#242424"))
                .setNumberSize(24)
                .setNumFieldOffsetY(60)
                .setLogBtnBackgroundPath("bg_one_click_login") //  设置登录按钮背景图片
                .setLogBtnTextColor(Color.parseColor("#ffffff")) //  设置登录按钮颜色
                .setLogBtnTextSize(16)
                .setLogBtnMarginLeftAndRight(35) //  设置登录按钮距离左右距离
                .setLogBtnHeight(78)
                .setLogBtnOffsetY(90)
                .setSwitchAccText("其它方式登录")
                .setSwitchAccTextSize(15)
                .setSwitchAccTextColor(Color.parseColor("#666666"))
                .setSwitchOffsetY(168)
                .setAppPrivacyOne("壹点灵用户使用协议", "https://h5.ydl.com/SDUserProtol")
                .setAppPrivacyTwo("隐私协议", "https://m.ydl.com/Protol/yinsi")
                .setAppPrivacyColor(Color.parseColor("#999999"), Color.parseColor("#1da1f2"))
                .setCheckboxHidden(checkBoxHidden) //  设置是否同意协议的checkbox隐藏
                .setPrivacyBefore("登录即代表您同意")
                .setDialogHeight(dialogHeight)
                .setDialogBottom(true)
                .setScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) //  设置竖屏
                .create()
        )
    }


    // 一键登录token监听器
    private var mTokenListener: TokenResultListener = object : TokenResultListener {
        override fun onTokenSuccess(s: String) {
            if (mAuthType == PhoneNumberAuthHelper.SERVICE_TYPE_AUTH) { // 本机号码校验
                verifyTokenResultListener.onTokenSuccess(s)
            } else {
                val tokenRet = TokenRet.fromJson(s)
                when (tokenRet.code) {
                    ResultCode.CODE_START_AUTHPAGE_SUCCESS -> {           // 唤起一键登录页面成功
                        LogUtil.e("唤起授权页成功：$s")
                    }
                    ResultCode.CODE_SUCCESS -> {                          // 获取token成功
                        val token = tokenRet.token
                        mPhoneNumberAuthHelper?.setAuthListener(null)
                        mIsGetTokenSuccess = false
                    }
                }
            }



        }

        override fun onTokenFailed(s: String) {
            LogUtil.e(s)
            mIsGetTokenSuccess = false
            val tokenRet = TokenRet.fromJson(s)
            if (mAuthType == PhoneNumberAuthHelper.SERVICE_TYPE_AUTH) {   // 本机号码校验
                verifyTokenResultListener.onTokenFailed(tokenRet)
            } else {
                // 一键登录
                when (tokenRet.code) {
                    ResultCode.CODE_ERROR_USER_CANCEL -> {                // 用户主动取消一键登录

                    }
                    else -> {                                             // 其它失败原因
                        // 跳转到原生登录界面
                        toLoginActivity()
                    }
                }
            }
            mPhoneNumberAuthHelper?.setAuthListener(null)
        }
    }

    // 号码验证监听
    private lateinit var verifyTokenResultListener: VerifyTokenResultListener

    interface VerifyTokenResultListener {
        fun onTokenSuccess(result: String)

        fun onTokenFailed(result: TokenRet)
    }

    fun setVerifyTokenResultListener(listener: VerifyTokenResultListener) {
        verifyTokenResultListener = listener
    }

}
