package com.yidianling.user.ui.login

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.text.TextUtils
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.fm.openinstall.OpenInstall
import com.fm.openinstall.listener.AppInstallAdapter
import com.fm.openinstall.model.AppData
import com.meituan.android.walle.WalleChannelReader
import com.mobile.auth.gatewayauth.*
import com.mobile.auth.gatewayauth.model.TokenRet
import com.tbruyelle.rxpermissions2.RxPermissions
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.utils.JPushUtils
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper
import com.ydl.ydlcommon.utils.log.LogHelper
import com.yidianling.common.tools.RxAppTool
import com.yidianling.common.tools.RxDeviceTool
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.LoginUtils
import com.yidianling.user.StatusUtils
import com.yidianling.user.UserHelper
import com.yidianling.user.api.bean.UserResponseBean
import com.yidianling.user.constants.UserBIConstants
import com.yidianling.user.http.LoginApiRequestUtil
import com.yidianling.user.http.request.PhoneLoginAutoParam
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.math.BigDecimal

/**
 * 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_XINLIZIXUN_APP_KEY =
        "j/bknWkezaeinV5fNddqzgY3iFPi9qlghUURCZdwLK6/zkxgwHyaAIxMVPnmQc0dSJ3LDYUvRYsSPZTXfjAdm92R1qmADFCK/NSENPENw5hLo/NCdvuySRYOnbbX5ZidyfeD/N5813mLomStMCPTv8GEYwUOdW1fnd8LBMNyi1K0Y2yWUKzGzYyVuMpWSpu38ULA6YXuATGkV/h3ric6SPqD2yS5SvjLHOye4Im5eeGdUgjRqzGnBM9F//okRlKJnuEHnBQ/HEU1Vt6sUgBhWHszGn1vzdSw"
    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
    const val YDL_XINLIZIXUN_APP = 3
    var mPhoneNumberAuthHelper: PhoneNumberAuthHelper? = null
    private var mAppType: Int = YDL_USER_APP
    var mIsFromGuide = true   // 是否来自启动页
    private var mOpenPageIsSuccess = false // 一键登录界面是否打开成功
    var mIsGetTokenSuccess = true    // 获取token是否成功，默认是成功
    var mIsOpenOneKeyLogin = true   // 是否开启一键登录
    var mAuthType = PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN              // 1：本机号码校验 2: ⼀键登录
    private var checkBoxHidden = true         // 协议勾选框是否展示m-user
    var mPrivacyBeforeText = "登录即代表您同意" // 隐私协议文案
    private lateinit var mActivity: BaseActivity
    var openInstallKey = ""

    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)
            } else if (appType == YDL_XINLIZIXUN_APP) {
                it.setAuthSDKInfo(YDL_XINLIZIXUN_APP_KEY)
            }

            // 控件点击事件
            it.setUIClickListener { code, context, json ->
                if (code == "700002") { // 表示一键登录按钮点击事件
                    ActionCountUtils.countUid(
                        UserBIConstants.PART_ID_LOGIN_MAIN,
                        UserBIConstants.ACTION_TYPE_ONE_KEY_CLICK
                    )
                }
            }
        }
        // 获取渠道
        val channel = WalleChannelReader.getChannel(activity.applicationContext)
        checkBoxHidden = !(channel == "huawei" || channel == "vivo")
        LogUtil.e("checkBoxHidde:$checkBoxHidden")
        if (!checkBoxHidden) {
            mPrivacyBeforeText = "同意"
        }
        if (appType == YDL_USER_APP) {
            getOpenInstallKey()
        }
    }

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


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

    /**
     * 打开登录界面
     *
     */
    private fun toLoginActivity() {
        if (mOpenPageIsSuccess) {
            RegisterAndLoginActivity.start(mActivity, isFromOneKey = true, isFromGuide = false)
        } else {
            RegisterAndLoginActivity.start(mActivity, false, mIsFromGuide)
        }
    }

    /**
     * 根据是否开启一键登录开关，跳转对应的登录页面
     * 请使用新的方法 [startLogin]
     */
    @Deprecated("mActivity有销毁的可能")
    fun toLoginActivity(isOpenDialog: Boolean) {
        if (mIsOpenOneKeyLogin) {
            getLoginToken(isOpenDialog)
        } else {
            // 一键登录页面打开成功
            if (mOpenPageIsSuccess) {
                RegisterAndLoginActivity.start(mActivity)
            } else {
                RegisterAndLoginActivity.start(mActivity, isFromOneKey = false, isFromGuide = true)
            }
        }
    }

    /**
     * 退出一键登录界面
     */
    fun quitLoginPage() {
        mPhoneNumberAuthHelper?.quitLoginPage()
    }


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

    /**
     * 拉起一键登录界面
     *
     * @param isOpenDialog 是否是弹窗
     *
     * 注：不建议直接调用，mActivity有销毁风险，请调用[startLogin]或者[startLoginByStatus]
     */
    fun getLoginToken(isOpenDialog: Boolean) {
        mOpenPageIsSuccess = false
        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(255f), 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 switchLogin = TextView(mActivity)
        val switchLoginLayoutParams = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
        )
        switchLoginLayoutParams.setMargins(
            RxImageTool.dp2px(40f),
            RxImageTool.dp2px(370f),
            RxImageTool.dp2px(40f),
            RxImageTool.dp2px(68f)
        )
        switchLogin.text = "切换号码"
        switchLogin.setTextColor(Color.parseColor("#999999"))
        switchLogin.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
        switchLogin.gravity = Gravity.CENTER
        switchLogin.layoutParams = switchLoginLayoutParams
        phoneNumberAuthHelper.addAuthRegistViewConfig(
            "switch_login", AuthRegisterViewConfig.Builder()
                .setView(switchLogin)
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_BODY)
                .setCustomInterface {
                    toLoginActivity()
                }
                .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("#999999"))
        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 {
                    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)
                .setStatusBarUIFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
                .setNavHidden(true) //  设置一键登录页面标题栏隐藏
                .setWebViewStatusBarColor(Color.WHITE)
                .setWebNavColor(Color.WHITE)
                .setWebNavTextColor(Color.parseColor("#242424")) //  设置协议页面标题字体颜色
                .setWebNavReturnImgPath("one_key_login_dialog_close") //  设置协议页返回按钮
                .setLightColor(true) //设置状态栏文字颜色,true为黑色
                .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(220)
                .setLogBtnBackgroundPath("bg_one_click_login") //  设置登录按钮背景图片
                .setLogBtnTextColor(Color.parseColor("#ffffff")) //  设置登录按钮文字颜色
                .setLogBtnTextSize(17)
                .setLogBtnHeight(78)
                .setLogBtnOffsetY(290)
                .setSwitchAccHidden(true)
                .setAppPrivacyOne(appPrivacyOneTip, appPrivacyOne)
                .setAppPrivacyTwo("隐私协议", appPrivacyTwo)
                .setAppPrivacyColor(Color.parseColor("#bfbfbf"), Color.parseColor("#991da1f2"))
                .setCheckboxHidden(checkBoxHidden) //  设置是否同意协议的checkbox隐藏
                .setCheckBoxHeight(16)
                .setCheckBoxWidth(16)
                .setCheckedImgPath("user_login_protocol_selected_new")
                .setUncheckedImgPath("user_login_protocol_unselected_new")
                .setPrivacyBefore(mPrivacyBeforeText)
                .setPrivacyMargin(35)
                .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)
                .setStatusBarUIFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
                .setNavText("登录解锁更多功能")
                .setNavTextColor(Color.parseColor("#999999"))
                .setNavReturnImgPath("one_key_login_dialog_close")
                .setWebViewStatusBarColor(Color.TRANSPARENT)
                .setWebNavTextColor(Color.parseColor("#242424")) //  设置协议页面标题字体颜色
                .setWebNavColor(Color.WHITE)
                .setWebNavReturnImgPath("one_key_login_dialog_close") //  设置协议页返回按钮
                .setLightColor(true) //设置状态栏文字颜色,true为黑色
                .setSloganHidden(true) //  设置slogan是否隐藏
                .setNumberColor(Color.parseColor("#242424"))
                .setNumberSize(24)
                .setNumFieldOffsetY(40)
                .setLogBtnBackgroundPath("bg_one_click_login") //  设置登录按钮背景图片
                .setLogBtnTextColor(Color.parseColor("#ffffff")) //  设置登录按钮颜色
                .setLogBtnTextSize(17)
                .setLogBtnHeight(78)
                .setLogBtnOffsetY(80)
                .setSwitchAccText("其它方式登录")
                .setSwitchAccTextSize(15)
                .setSwitchAccTextColor(Color.parseColor("#999999"))
                .setSwitchOffsetY_B(80)
                .setAppPrivacyOne("壹点灵用户使用协议", "https://h5.ydl.com/SDUserProtol")
                .setAppPrivacyTwo("隐私协议", "https://m.ydl.com/Protol/yinsi")
                .setAppPrivacyColor(Color.parseColor("#bfbfbf"), Color.parseColor("#991da1f2"))
                .setCheckboxHidden(checkBoxHidden) //  设置是否同意协议的checkbox隐藏
                .setCheckBoxHeight(16)
                .setCheckBoxWidth(16)
                .setCheckedImgPath("user_login_protocol_selected_new")
                .setUncheckedImgPath("user_login_protocol_unselected_new")
                .setPrivacyBefore(mPrivacyBeforeText)
                .setPrivacyMargin(35)
                .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")
                        mOpenPageIsSuccess = true
                        if (mIsFromGuide) {
                            mActivity.finish()
                        }
                    }
                    ResultCode.CODE_SUCCESS -> {                          // 获取token成功
                        val param = PhoneLoginAutoParam(
                            tokenRet.token,
                            JPushUtils.getRegistrationID(),
                            2,
                            2,
                            "",
                            RxAppTool.getAppVersionName(BaseApp.Companion.getApp())
                        )
                        LoginApiRequestUtil.autoLogin(param)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe({
                                if (it.code == 200) {
                                    AliYunRichLogsHelper.getInstance()
                                        .sendRichLog(AliYunLogConfig.LOGIN, "一键登录成功")
                                    ToastUtil.toastShort("登录成功")
                                    saveUserData(it.data)
                                    if (it.data.firstLogin == 1) {//第一次登录：是注册
                                        StatusUtils.isFirstLogin = true
                                        //   埋点
                                        ActionCountUtils.baiduCount(
                                            it.data.uid,
                                            UserBIConstants.APP_REGISTER_PAGE,
                                            UserBIConstants.POSITION_ALIYUN_REGISTER_CLICK,
                                            "",
                                            "",
                                            25,
                                            openInstallKey
                                        )
                                        if (OneKeyLoginHelp.openInstallKey.isNotEmpty() && StatusUtils.isUseOpenInstall) {
                                            // 用户注册成功后调用
                                            OpenInstall.reportRegister()
                                        }
                                    } else {
                                        ActionCountUtils.countUid(
                                            UserBIConstants.POSITION_LOGIN_SUCCESS_CLICK,
                                            it.data.uid!!,
                                            UserBIConstants.ACTION_TYPE_ONE_KEY_CLICK
                                        )
                                    }
                                    mPhoneNumberAuthHelper?.let { helper ->
                                        helper.hideLoginLoading()
                                        helper.quitLoginPage()
                                        helper.setAuthListener(null)
                                    }
                                    mIsGetTokenSuccess = false
                                    if (mIsFromGuide) {
                                        LoginUtils.loginSuccessOperate(mActivity)
                                    }
                                } else {
                                    AliYunRichLogsHelper.getInstance().sendRichLog(
                                        AliYunLogConfig.LOGIN,
                                        "一键登录失败   msg:${it.msg}"
                                    )
                                    ToastUtil.toastShort(it.msg)
                                    mPhoneNumberAuthHelper?.hideLoginLoading()
                                }
                            }, {
                                AliYunRichLogsHelper.getInstance().sendRichLog(
                                    AliYunLogConfig.LOGIN,
                                    "一键登录Error   msg:${it.message}"
                                )
                                ToastUtil.toastShort(it.message)
                                mPhoneNumberAuthHelper?.hideLoginLoading()
                            })
                    }
                }
            }


        }

        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 -> {                // 用户主动取消一键登录
                        // 如果是从引导页首次打开
//                        if (mIsFromGuide){
//                            ActivityManager.finishOtherActivity(mActivity)
//                            UserIn.mainIntent(mActivity, 4)
//                        }
                    }
                    else -> {                                             // 其它失败原因
                        mPhoneNumberAuthHelper?.hideLoginLoading()
                        // 跳转到原生登录界面
                        mActivity.runOnUiThread {
                            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
    }


    /**
     * 保存登录信息
     */
    private fun saveUserData(userResponse: UserResponseBean) {
        if (!TextUtils.isEmpty(userResponse.userInfo!!.phone)) {
            YDLCacheUtils.saveUserPhone(userResponse.userInfo!!.phone)
            YDLCacheUtils.saveCountryPhoneCode(userResponse.userInfo!!.country_code)
        }
        if (userResponse.uid!!.contains(".")) {
            val bd = BigDecimal(userResponse.uid)
            var uid = bd.toPlainString()
            if (uid.endsWith(".0")) {
                uid = uid.replace(".0", "")
            }
            userResponse.userInfo!!.uid = uid
            userResponse.uid = uid
        }
        LoginUtils.saveData(userResponse)
        LogHelper.getInstance().writeLogSync("登录成功")
        LoginUtils.onLogin(userResponse)
    }

    /**
     * CPA(CPS)推广渠道统计
     * 获取安装携带的参数
     * 注：1、不要在 init 之后，紧接着调用 getInstall，防止网络等问题导致 getInstall 超时，从而获取数据失败
     */
    private fun getOpenInstallKey() {
        OpenInstall.getInstall(object : AppInstallAdapter() {
            override fun onInstall(appData: AppData) {
                // 获取渠道数据  转换值同步IOS  "AppData{channel='" + this.channel + '\'' + ", data='" + this.data + '\'' + '}'
                openInstallKey =
                    appData.toString().replace("AppData", "").replace("channel", "channelCode")
            }
        })
    }

    /**
     * @param isOpenDialog true： 使用弹窗展示一键登录
     *                     false： 使用全页面展示一键登录
     *                     @return true:登录。false:未登录
     * */
    fun startLoginByStatus(context: Context, isOpenDialog: Boolean): Boolean {
        if (!UserHelper.isLogin()) {
            if (this::mActivity.isInitialized) {
                //如果mActivity有初始化，代表项目使用了一键登录
                startLogin(context as Activity, isOpenDialog)
            } else {
                //如果mActivity未初始化，使用正常登录
                RegisterAndLoginActivity.start(context)
            }
        }
        return UserHelper.isLogin()
    }

    /**
     * @param isOpenDialog true 使用弹窗
     * */
    @SuppressLint("CheckResult")
    fun startLogin(context: Activity, isOpenDialog: Boolean) {
        try {
            RxPermissions(context)
                .request(Manifest.permission.READ_PHONE_STATE)
                .subscribe { hasPermission: Boolean? ->
                    if (hasPermission == true && mIsOpenOneKeyLogin) {
                        getLoginToken(isOpenDialog)
                    } else {
                        // 一键登录页面打开成功
                        if (mOpenPageIsSuccess) {
                            RegisterAndLoginActivity.start(context)
                        } else {
                            RegisterAndLoginActivity.start(
                                context,
                                isFromOneKey = false,
                                isFromGuide = true
                            )
                        }
                    }
                }
        } catch (e: Exception) {
            RegisterAndLoginActivity.start(context)
            e.printStackTrace()
        }

    }
}
