package com.yidianling.user.ui.login

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.AbsoluteSizeSpan
import android.text.style.ClickableSpan
import android.view.View
import android.view.animation.AnimationUtils
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.meituan.android.walle.WalleChannelReader
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.ResultCode
import com.mobile.auth.gatewayauth.model.TokenRet
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareConfig
import com.umeng.socialize.bean.SHARE_MEDIA
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.base.config.ChannelConfig
import com.ydl.ydlcommon.data.PlatformDataManager
import com.ydl.ydlcommon.data.PlatformRamImpl
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.utils.JPushUtils
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.YDLCacheUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
import com.ydl.ydlcommon.view.dialog.CommonDialog
import com.yidianling.common.tools.LogUtil
import com.yidianling.common.tools.RxAppTool
import com.yidianling.common.tools.RxKeyboardTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.LoginUtils
import com.yidianling.user.R
import com.yidianling.user.StatusUtils
import com.yidianling.user.UserHelper
import com.yidianling.user.UserHelper.isLogin
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 com.yidianling.user.http.response.ChcekPhoneResponeBean
import com.yidianling.user.route.UserIn
import com.yidianling.user.safePrivate.FingerPrintCheckActivity
import com.yidianling.user.safePrivate.FingerPrintUtil
import com.yidianling.user.safePrivate.HandUnlockCheckActivity
import com.yidianling.user.ui.CountryListActivity
import com.yidianling.user.ui.login.contract.ILoginContract
import com.yidianling.user.ui.login.presenter.LoginPresenterImpl
import com.yidianling.user.widget.AgreePrivacyBottomDialog
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.user_activity_register_and_login_bottom.*
import kotlinx.android.synthetic.main.user_activity_register_and_login_new.*
import kotlinx.android.synthetic.main.user_activity_secret.*

/**
 * @author jiucheng
 * @描述:登录注册页面
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/11/28
 */
@Route(path = "/user/login")
class RegisterAndLoginActivity : BaseMvpActivity<ILoginContract.View, ILoginContract.Presenter>(),
    ILoginContract.View {

    private var userPhoneNumber: String? = null

    // 是否支持号码认证
    private var isCanAuth: Boolean = false

    private var chcekPhoneResponeBean: ChcekPhoneResponeBean? = null // 手机号校验结果
    private var isBindPhone: Boolean = false // 是否绑定手机号
    private var countryCode: String? = "0086"//国家或地区手机区号
    private var handler: Handler? = null
    private var isFromGuide = false//是否来自启动页
    private var isFromOneKeyLogin = false // 是否来自一键登录界面
    private var bottomDialog: AgreePrivacyBottomDialog? = null

    companion object {
        private var BIND_PHONE = "bind_phone"//用于判断时候是绑定手机号
        private var IS_FROM_GUIDE = "isFromGuide"//是否来自启动页
        private var IS_FROM_ONE_KEY_LOGIN = "isFromOneKeyLogin"//是否来自启动页
        var REQUEST_CODE_COUNTRY = 1024
        fun start(context: Context) {
            start(context, false)
        }

        /**
         * 第三方登录，绑定手机号调用此方法启动
         */
        fun start(context: Context, isBindPhone: Boolean) {
            startFromGuide(context, isBindPhone, false)
        }

        /**
         * 打开登录注册页面
         *
         * @param isFromOneKey 是否来自一键登录界面
         * @param isFromGuide 是否来自启动页面
         */
        fun start(context: Context, isFromOneKey: Boolean, isFromGuide: Boolean) {
            val intent = Intent(context, RegisterAndLoginActivity::class.java)
            intent.putExtra(IS_FROM_ONE_KEY_LOGIN, isFromOneKey)
            intent.putExtra(IS_FROM_GUIDE, isFromGuide)
            context.startActivity(intent)
        }
        /**
         * 注意：此方法仅限于启动页调用，其他页面不要调用此方法
         */
        fun startFromGuide(context: Context, isBindPhone: Boolean, isFromGuide: Boolean) {
            val intent = Intent(context, RegisterAndLoginActivity::class.java)
            intent.putExtra(BIND_PHONE, isBindPhone)
            intent.putExtra(IS_FROM_GUIDE, isFromGuide)
            context.startActivity(intent)
        }

        fun getIntent(context: Context): Intent {
            return Intent(context, RegisterAndLoginActivity::class.java)
        }
    }

    override fun createPresenter(): ILoginContract.Presenter {
        return LoginPresenterImpl(this)
    }

    override fun layoutResId(): Int {
        return R.layout.user_activity_register_and_login_new
    }

    override fun initDataAndEvent() {
        isBindPhone = intent.getBooleanExtra(BIND_PHONE, false)
        isFromGuide = intent.getBooleanExtra(IS_FROM_GUIDE, false)
        isFromOneKeyLogin = intent.getBooleanExtra(IS_FROM_ONE_KEY_LOGIN, false)

        setWindowStatusBarColor()
        initAuthHelper()
        initView()
        setClickEvent()
    }

    private fun setWindowStatusBarColor() {
        StatusBarUtils.Companion.setWindowStatusBarColor(this, R.color.white)
        StatusBarUtils.Companion.setStatusBarLightMode(this, true)
    }
    /**
     * 注册流程成功之后，进行百度埋点
     */
    override fun baiduActionBury(uid: String?, positionClick: String) {
        ActionCountUtils.baiduCount(
            uid,
            UserBIConstants.APP_REGISTER_PAGE,
            positionClick,
            "",
            "",
            25,
            ""
        )
    }


    private fun initAuthHelper() {
        OneKeyLoginHelp.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_AUTH)
        OneKeyLoginHelp.setVerifyTokenResultListener(object :
            OneKeyLoginHelp.VerifyTokenResultListener {
            override fun onTokenSuccess(result: String) {
                val tokenRet = TokenRet.fromJson(result)
                when (tokenRet.code) {
                    ResultCode.CODE_ERROR_ENV_CHECK_SUCCESS -> {             //  终端环境支持认证
                        isCanAuth = true
                    }
                    ResultCode.CODE_SUCCESS -> {                          // 获取token成功
                        autoLogin(tokenRet.token)
                        OneKeyLoginHelp.mPhoneNumberAuthHelper?.setAuthListener(null)
                        OneKeyLoginHelp.mIsGetTokenSuccess = false
                    }
                }
            }

            override fun onTokenFailed(result: TokenRet) {
                if (isCanAuth) {
                    //验证失败跳转到验证码/密码界面
                    aliAuthFailed()
                }
            }

        })
    }

    private fun initView() {
        val name = resources.getString(R.string.user_login_name_start)
        val str = "${name}用户使用协议、隐私保护政策"
        var start = name.length
        val spannableString = SpannableString(str)
        spannableString.setSpan(object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color =
                    ContextCompat.getColor(this@RegisterAndLoginActivity, R.color.user_1da1f2trans)
                ds.isUnderlineText = true      //设置下划线
            }

            override fun onClick(widget: View) {
                if (!isBindPhone) {
                    H5Activity.start(this@RegisterAndLoginActivity, false)
                    overridePendingTransition(
                        R.anim.platform_slide_in_from_bottom,
                        R.anim.user_slide_null
                    )
                }
            }
        }, start, start+6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color =
                    ContextCompat.getColor(this@RegisterAndLoginActivity, R.color.user_1da1f2trans)
                ds.isUnderlineText = true      //设置下划线
            }

            override fun onClick(widget: View) {
                if (!isBindPhone) {
                    H5Activity.start(this@RegisterAndLoginActivity, true)
                    overridePendingTransition(
                        R.anim.platform_slide_in_from_bottom,
                        R.anim.user_slide_null
                    )
                }
            }
        }, start + 7, str.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        tv_protocol.text = spannableString
        tv_protocol.movementMethod = LinkMovementMethod.getInstance()


        handler = Handler()


        setHint()
        requestFocus()
        if (isBindPhone) {
            skip_bind.visibility = View.VISIBLE
            iv_select_protocol.visibility = View.GONE
            login_wechat.visibility = View.GONE
            login_qq.visibility = View.GONE
            tv_login_title.text = "手机号绑定"
            ll_next.text = "发送验证码"
            tv_protocol.visibility = View.GONE
            other_login_style.visibility = View.GONE
        }
        if (PlatformDataManager.getRam().getChannelName()
                .startsWith(ChannelConfig.ATK_3.name) || PlatformDataManager.getRam()
                .getChannelName().startsWith(ChannelConfig.ATK_4.name)
        ) {
            login_qq.visibility = View.GONE
        }


        if (!TextUtils.isEmpty(YDLCacheUtils.getUserPhone())) {
            et_phone_number.setText(YDLCacheUtils.getUserPhone())
            et_phone_number.setSelection(et_phone_number.text!!.length)
            iv_del.visibility = View.VISIBLE
        } else {
            iv_del.visibility = View.GONE
        }

        if (!TextUtils.isEmpty(YDLCacheUtils.getCountryPhoneCode())) {
            countryCode = YDLCacheUtils.getCountryPhoneCode()
            country_code.text = "+" + countryCode?.replace("00", "")
        }

        setCountryIcon(countryCode)
        if (et_phone_number.text.toString().isNotEmpty()) {
            ll_next.isEnabled = true
            ll_next.background = ContextCompat.getDrawable(this, R.drawable.bg_one_click_login)
        }

        if (isFromGuide) {
            img_reg_back.visibility = View.INVISIBLE
            skip_bind.visibility = View.VISIBLE
            img_reg_back.isEnabled = false
        }
        //根据来源不同为当前页面埋点
        if (isFromGuide) {
            ActionCountUtils.count(
                uid = "",
                partId = UserBIConstants.PART_ID_LOGIN_MAIN,
                position = UserBIConstants.POSITION_LOGIN_ONE_PAGE_VISIT,
                url = "无url",
                api = "无api",
                sign1 = ""
            )
        } else {
            ActionCountUtils.count(
                uid = "",
                partId = UserBIConstants.PART_ID_LOGIN_MAIN,
                position = UserBIConstants.POSITION_LOGIN_TWO_PAGE_VISIT,
                url = "无url",
                api = "无api",
                sign1 = ""
            )
        }
        et_phone_number.postDelayed(Runnable {
            RxKeyboardTool.showSoftInput(this,et_phone_number)
        },500)

    }

    private fun requestFocus() {
        et_phone_number.post {
            et_phone_number.requestFocus()
            et_phone_number.isFocusable = true
            et_phone_number.isFocusableInTouchMode = true
        }
    }

    private fun setHint() {
        val hintStr = SpannableString("输入手机号")// 定义hint的值
        val ass = AbsoluteSizeSpan(20, true)// 设置字体大小 true表示单位是SP
        hintStr.setSpan(ass, 0, hintStr.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        et_phone_number.hint = SpannedString(hintStr)
    }


    /**
     * 设置点击事件
     */
    @SuppressLint("WrongConstant")
    private fun setClickEvent() {
        skip_bind.setOnClickListener {
            ActionCountUtils.count(UserBIConstants.USER_REGISTER_PAGE_SKIP_CLICK)
            ActionCountUtils.count(
                uid = "",
                partId = UserBIConstants.PART_ID_LOGIN_MAIN,
                position = UserBIConstants.POSITION_LOOK_AROUND_CLICK,
                url = "无url",
                api = "无api",
                sign1 = ""
            )
            RxKeyboardTool.hideSoftInput(this)
            onBackPressed()
        }
        img_reg_back.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            onBackPressed()
        }
        var isAgreeProtocol = false
        //华为渠道不默认勾选隐私协议，必须全局上下文才可以获取到渠道号。其他渠道默认勾选隐私协议
        //protocol_android  1是开启默认勾选，2是关闭默认勾选，方便应用市场审核
        //新逻辑：华为和VIVO一直不默认勾选(上线后华为、VIVO也会抽查隐私协议勾选情况)

        val privacyOnOffType =
            PlatformRamImpl.getInstance().getGlobalInfo()?.info?.protocol_android ?: 2
        val channel = WalleChannelReader.getChannel(applicationContext)
        if (channel == "huawei"||channel == "vivo") {
            iv_select_protocol.setImageResource(R.drawable.user_login_protocol_unselected_new)
        } else if (privacyOnOffType == 2) {
            iv_select_protocol.setImageResource(R.drawable.user_login_protocol_unselected_new)
        } else {
            isAgreeProtocol = true
            iv_select_protocol.setImageResource(R.drawable.user_login_protocol_selected_new)
        }
        iv_select_protocol.setOnClickListener {
            if (iv_select_protocol.visibility == View.VISIBLE) {
                isAgreeProtocol = !isAgreeProtocol
                if (isAgreeProtocol) {
                    iv_select_protocol.setImageResource(R.drawable.user_login_protocol_selected_new)
                } else {
                    iv_select_protocol.setImageResource(R.drawable.user_login_protocol_unselected_new)
                }
            }
        }
        //微信登录
        login_wechat.setOnClickListener {
            if (iv_select_protocol.visibility == View.VISIBLE && !isAgreeProtocol) {
                val shake = AnimationUtils.loadAnimation(this, R.anim.user_shake_input)//加载动画资源文件 
                check_protocol.startAnimation(shake)
                ToastUtil.toastShort("请您先同意壹点灵《用户使用协议》、《隐私保护政策》，才能登录使用")
                return@setOnClickListener
            }
            mPresenter.loginByThird(this, SHARE_MEDIA.WEIXIN)
        }
        //QQ 登录
        login_qq.setOnClickListener {
            if (iv_select_protocol.visibility == View.VISIBLE && !isAgreeProtocol) {
                val shake = AnimationUtils.loadAnimation(this, R.anim.user_shake_input)//加载动画资源文件 
                check_protocol.startAnimation(shake)
                ToastUtil.toastShort("请您先同意壹点灵《用户使用协议》、《隐私保护政策》，才能登录使用")
                return@setOnClickListener
            }
            val config = UMShareConfig()
            config.isNeedAuthOnGetUserInfo(true)
            UMShareAPI.get(this).setShareConfig(config)
            mPresenter.loginByThird(this, SHARE_MEDIA.QQ)
        }
        country_code.setOnClickListener {
            val intent = Intent(this, CountryListActivity::class.java)
            intent.putExtra("userCountryCode", countryCode)
            startActivityForResult(intent, REQUEST_CODE_COUNTRY)
            overridePendingTransition(R.anim.platform_slide_in_from_bottom, R.anim.user_slide_null)
        }

        //下一步
        ll_next.setOnClickListener {
            if (iv_select_protocol.visibility == View.VISIBLE && !isAgreeProtocol && !et_phone_number.text.isNullOrEmpty()) {
                if (null == bottomDialog) {
                    bottomDialog = AgreePrivacyBottomDialog(
                        this,
                        object : AgreePrivacyBottomDialog.OnAgreeBottomListener {
                            override fun onCancel() {

                            }

                            override fun onSure() {
                                isAgreeProtocol = true
                                iv_select_protocol.setImageResource(R.drawable.user_login_protocol_selected_new)
                                if (checkPhone()) {
                                    mPresenter.checkPhoneStatus(
                                        userPhoneNumber!!,
                                        countryCode!!,
                                        isBindPhone
                                    )
                                }
                            }
                        })
                    bottomDialog?.show()
                } else {
                    bottomDialog?.show()
                }
                return@setOnClickListener
            }
            if (checkPhone()) {
                mPresenter.checkPhoneStatus(userPhoneNumber!!, countryCode!!, isBindPhone)
            }

        }
        //手机号输入框

        et_phone_number.setListener {
            if (TextUtils.isEmpty(it)) {
                setHint()
                iv_del.visibility = View.INVISIBLE
                iv_del.isEnabled = false
            } else {
                iv_del.visibility = View.VISIBLE
                iv_del.isEnabled = true
            }
            updateLoginButtonStatus()
        }
        //删除按钮
        iv_del.setOnClickListener {
            et_phone_number.setText("")
        }
    }

    /**
     * 根据手机号码区域、和输入框内容，更新下一步登录按钮状态
     * */
    private fun updateLoginButtonStatus() {
        if (country_code.text.equals("+86")) {
            //国内号段
            if (et_phone_number.text.toString().length == 13) {
                //13位才能点击登录(手机号中间有两个空格)
                ll_next.isEnabled = true
                ll_next.background = ContextCompat.getDrawable(this, R.drawable.bg_one_click_login)
            } else {
                ll_next.isEnabled = false
                ll_next.background =
                    ContextCompat.getDrawable(this, R.drawable.login_password_unable_bg_24dp)
            }
        } else {
            //国外号段
            if (et_phone_number.text.toString().isNotEmpty()) {
                //有值就可点击登录
                ll_next.isEnabled = true
                ll_next.background = ContextCompat.getDrawable(this, R.drawable.bg_one_click_login)
            } else {
                ll_next.isEnabled = false
                ll_next.background =
                    ContextCompat.getDrawable(this, R.drawable.login_password_unable_bg_24dp)
            }
        }
    }

    /**
     * 检查手机号规范
     */
    private fun checkPhone(): Boolean {
        val editPhone = et_phone_number.textContent
        if (TextUtils.isEmpty(editPhone)) {
            ToastUtil.toastShort("请输入手机号")
            return false
        }
        LogUtil.e("本地userPhoneNumber赋值操作2：$editPhone")
        userPhoneNumber = editPhone
        //手机号码验证 国外手机号码不做限制
        if (!TextUtils.equals("0086", countryCode)) {
            return !TextUtils.isEmpty(editPhone)
        }
        return if (editPhone.length == 11 && editPhone.startsWith("1") && checkRegex(
                editPhone.toString().trim()
            )
        ) {
            view_lin.setBackgroundColor(Color.parseColor("#E8E8E8"))
            true
        } else {
            view_lin.setBackgroundColor(Color.parseColor("#FB6761"))
            ToastUtil.toastShort("不是正确的手机号")
            startAnim()
            false
        }
    }

    private fun checkRegex(phone: String): Boolean {
        val regex = "^1+[23456789]+\\d{9}"
        return phone.matches(regex.toRegex())
    }

    /**
     * 动画
     */
    private fun startAnim() {
        val shake = AnimationUtils.loadAnimation(this, R.anim.user_shake_input)//加载动画资源文件 
        et_phone_number.startAnimation(shake)
    }

    /**
     *三方登录成功
     */
    @SuppressLint("CheckResult")
    override fun thirdLoginSuccess(
        userInfo: UserResponseBean.UserInfo,
        thirdLoginPlatform: String
    ) {

        val userInfo = UserHelper.getUserInfo()?.userInfo
        val map = HashMap<String, String>()
        map["login_type"] = thirdLoginPlatform
        map["openid"] = userInfo?.open_id_qqapp ?: ""
        map["unionid"] = userInfo?.union_id ?: ""
        LoginApiRequestUtil.isNeedForceBindPhone(map)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it.code == "200") {
                    if (it.data) {
                        BindPhoneActivity.startActivity(this, it.data, isFromGuide)
                        finish()
                    } else {
                        when {
                            isFromGuide -> {
                                LoginUtils.loginSuccessOperate(this)
                            }
                            isFromOneKeyLogin -> {
                                if (OneKeyLoginHelp.mIsFromGuide) {
                                    LoginUtils.loginSuccessOperate(this)
                                } else {
                                    OneKeyLoginHelp.quitLoginPage()
                                    finish()
                                }
                            }
                            else -> {
                                finish()
                            }
                        }
                    }
                }
            }, {
                ToastUtil.toastShort(it.message)
            })
    }

    /**
     * 校验手机号(是否是用户版号码、是否有设置密码、是否被绑定)成功
     */
    override fun checkPhoneStatusSuccess(bean: ChcekPhoneResponeBean?, phone: String) {
        //校验手机号的结果需要在本地保存，后续一键认证登录失败后跳转密码登录需要用到校验结果
        if (bean != null) {
            chcekPhoneResponeBean =
                ChcekPhoneResponeBean(bean.hasPwd, bean.isDoctor, bean.isRegistered)
        }
        if (isBindPhone) {
            aliAuthFailed()
        } else {
            if (isCanAuth) {
                OneKeyLoginHelp.getVerifyToken()
            } else {
                aliAuthFailed()
            }
        }
    }


    /**
     * 服务端校验阿里一键认证认证失败
     *
     * 成功的回调 :
     * @see getAuthToken
     *
     * 失败的回调 ：
     * @see aliAuthFailed
     */
    override fun aliAuthFailed() {
        RxKeyboardTool.hideSoftInput(this)
        runOnUiThread {
            showLoading(false)
        }

        if (chcekPhoneResponeBean != null && chcekPhoneResponeBean?.hasPwd == 1) {//用户码有设置密码：跳转到密登录
            InputPassWordActivity.start(
                this,
                userPhoneNumber!!,
                countryCode!!,
                InputPassWordActivity.STATUS_INPUT_PWD
            )
        } else {//否则跳转验证码页面
            if (!TextUtils.isEmpty(userPhoneNumber) && !TextUtils.isEmpty(countryCode)) {
                VerificationCodeActivity.start(
                    this,
                    userPhoneNumber!!,
                    countryCode!!,
                    VerificationCodeActivity.STATUS_LOGIN_BY_CODE,
                    isBindPhone,
                    false
                )
            }
        }
    }

    /**
     * 通过阿里sdk一键认证服务登陆
     */
    private fun autoLogin(token: String) {
        val param = PhoneLoginAutoParam(
            token, JPushUtils.getRegistrationID(), 2, 1, userPhoneNumber!!,
            RxAppTool.getAppVersionName(BaseApp.Companion.getApp())
        )
        mPresenter.autoLogin(param)
    }

    /**
     * 手机号绑定成功
     */
    override fun bindSuccess() {
        UserHelper.getUserInfo()!!.userInfo!!.bind_phone = 1
        UserHelper.getUserInfo()!!.userInfo!!.phone = userPhoneNumber

        finishPrePage()
    }


    /**
     *菊花框
     */
    override fun showLoading(state: Boolean) {
        if (state) {
            showProgressDialog()
        } else {
            dismissProgressDialog()
        }
    }


    /**
     * 自动登录成功
     */
    override fun autoLoginSuccess() {
        ll_success.visibility = View.GONE
        ToastUtil.toastShort("登录成功")
        handler!!.postDelayed({
            when {
                isFromGuide -> {
                    LoginUtils.loginSuccessOperate(this)
                }
                isFromOneKeyLogin -> {
                    if (OneKeyLoginHelp.mIsFromGuide) {
                        LoginUtils.loginSuccessOperate(this)
                    } else {
                        OneKeyLoginHelp.quitLoginPage()
                        finish()
                    }
                }
                else -> {
                    finish()
                }
            }
        }, 1000)
    }

    private fun finishPrePage() {
        ActivityManager.getInstance().finishActivity(VerificationCodeActivity::class.java)
        ActivityManager.getInstance().finishActivity(InputPassWordActivity::class.java)
        ActivityManager.getInstance().finishActivity(RegisterAndLoginActivity::class.java)

        //关闭手势解锁页面与指纹解锁页面
        ActivityManager.getInstance().finishActivity(FingerPrintCheckActivity::class.java)
        ActivityManager.getInstance().finishActivity(HandUnlockCheckActivity::class.java)
        FingerPrintUtil.instance().setCurrentUnLockTime(System.currentTimeMillis())
    }


    override fun onBackPressed() {
        if (isFromGuide) {
            LoginUtils.setLoginCallBack(null)
            ActivityManager.finishOtherActivity(this)
            if (StatusUtils.isFirstStartApp) {
                UserIn.mainIntent(this, 0)
            } else {
                UserIn.mainIntent(this, 4)
            }
            finish()
        } else if (isFromOneKeyLogin) {        // 来自一键登录界面
            // 如果已经登录
            if (isLogin()) {
                OneKeyLoginHelp.quitLoginPage()
                if (OneKeyLoginHelp.mIsFromGuide) {
                    ActivityManager.finishOtherActivity(this)
                    UserIn.mainIntent(this, 4)
                    finish()
                } else {
                    super.onBackPressed()
                }
            } else {
                if (!OneKeyLoginHelp.mIsFromGuide) {
                    finish()
                }else{
                    OneKeyLoginHelp.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN)
                }
                super.onBackPressed()
            }
        } else {
            LoginUtils.setLoginCallBack(null)
            super.onBackPressed()
        }
    }

    override fun showProgressView() {
        showProgressDialog()
    }

    override fun dismissProgressView() {
        dismissProgressDialog()
    }

    override fun showHasBindedDialog() {
        CommonDialog.create(this)
            .setMessage("该手机号已被注册，无法绑定，\n您可以使用它直接登录。")
            .setRightClick("确定") {
            }
            .show()
    }

    override fun showNormalDialog() {
        CommonDialog.create(this)
            .setMessage("专家账号，请下载壹点灵专家版app喔")
            .setRightClick("确定") {

            }
            .show()
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == 45 && requestCode == REQUEST_CODE_COUNTRY) {
            countryCode = data!!.getStringExtra("code")
            setCountryIcon(countryCode)

            country_code.text = "+" + countryCode?.replace("00", "")
            updateLoginButtonStatus()

        }
    }

    /**
     * 根据国家个地区号设置国旗
     */
    private fun setCountryIcon(code: String?) {
        country_code.text = "+" + countryCode?.replace("00", "")
        val splitCode = countryCode?.replace("00", "")
    }

    override fun onDestroy() {
        super.onDestroy()
        if (handler != null) {
            handler = null
        }
    }
}
