package com.yidianling.user.ui.login

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Handler
import android.provider.Settings
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.AbsoluteSizeSpan
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import android.view.animation.AnimationUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.mobile.auth.gatewayauth.AuthUIConfig
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper
import com.mobile.auth.gatewayauth.PreLoginResultListener
import com.mobile.auth.gatewayauth.TokenResultListener
import com.mobile.auth.gatewayauth.model.InitResult
import com.mobile.auth.gatewayauth.model.VendorConfig
import com.tbruyelle.rxpermissions2.RxPermissions
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareConfig
import com.umeng.socialize.bean.SHARE_MEDIA
import com.ydl.ydlcommon.base.BaseMvpActivity
import com.ydl.ydlcommon.utils.ActivityManager
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.RxKeyboardTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.router.user.UserResponse
import com.yidianling.user.BuildConfig
import com.yidianling.user.R
import com.yidianling.user.UserHelper
import com.yidianling.user.bean.AliAuthBean
import com.yidianling.user.constants.UserBIConstants
import com.yidianling.user.http.request.BindPhoneJavaParam
import com.yidianling.user.http.request.PhoneLoginAutoParam
import com.yidianling.user.http.response.ChcekPhoneResponeBean
import com.yidianling.user.route.UserIn
import com.yidianling.user.ui.CountryListActivity
import com.yidianling.user.ui.login.contract.ILoginContract
import com.yidianling.user.ui.login.presenter.LoginPresenterImpl
import kotlinx.android.synthetic.main.user_activity_register_and_login.*

/**
 * @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 mAlicomAuthHelper: PhoneNumberAuthHelper? = null
    private var mTokenListener: TokenResultListener? = null
    private var mAutCheckResult: InitResult? = null
    private var userPhoneNumber: String? = null
    /**
     * 是不是4G网络
     */
    private var isCan4GAuth: Boolean = false
    /**
     * 手机号校验结果
     */
    private var chcekPhoneResponeBean: ChcekPhoneResponeBean? = null
    private var isUmengLoginState: Boolean = false //true 通过第三方登录后绑定手机号码
    private var countryCode: String? = "0086"//国家或地区手机区号
    private var handler: Handler? = null
    private var isFromGuide = false//是否来自启动页

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

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

        /**
         * 注意：此方法仅限于启动页调用，其他页面不要调用此方法
         */
        fun startFromGuide(context: Context, isBindPhone: Boolean, isFromGudile: Boolean) {
            val intent = Intent(context, RegisterAndLoginActivity::class.java)
            intent.putExtra(BIND_PHONE, isBindPhone)
            intent.putExtra(IS_FROM_GUIDE, isFromGudile)
            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
    }

    override fun initDataAndEvent() {
        isUmengLoginState = intent.getBooleanExtra(BIND_PHONE, false)
        isFromGuide = intent.getBooleanExtra(IS_FROM_GUIDE, false)

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


    private fun setWindowStatusBarColor() {
        StatusBarUtils.Companion.setWindowStatusBarColor(this, R.color.platform_color_075b66)
    }

    private fun requestPermission() {
        val rxPermissions = RxPermissions(this)
        rxPermissions.requestEach(Manifest.permission.READ_PHONE_STATE)
                .subscribe { permission ->
                    when {
                        permission.granted -> {
                            // 用户已经同意该权限
                            /*
                             *   5.sdk init
                             */
                            mAutCheckResult = mAlicomAuthHelper?.checkAuthEnvEnable()
                        }
                        permission.shouldShowRequestPermissionRationale -> {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时。还会提示请求权限的对话框
                        }
                        else -> {
                            // 用户拒绝了该权限，而且选中『不再询问』
                            ToastUtil.toastLong(this, getString(R.string.platform_need_storage_permission_hint))
                            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                            val uri = Uri.fromParts("package", packageName, null)
                            intent.data = uri
                            startActivity(intent)
                            finish()
                        }
                    }
                    if (mAutCheckResult != null) {
                        isCan4GAuth = mAutCheckResult?.isCan4GAuth!!
                        if (!TextUtils.isEmpty(mAutCheckResult!!.simPhoneNumber) && TextUtils.isEmpty(userPhoneNumber)) {
                            runOnUiThread {
                                et_phone_number.setPhoneText(mAutCheckResult!!.simPhoneNumber)
                                et_phone_number.setSelection(et_phone_number.text.length)
                                iv_del.visibility = View.VISIBLE
                            }
                        }
                    }
                }
    }

    /**
     * 注册流程成功之后，进行百度埋点
     */
    override fun baiduActionBury(uid: String?, positionClick: String) {
        ActionCountUtils.baiduCount(uid, UserBIConstants.APP_REGISTER_PAGE, positionClick, "","", 25)
    }


    private fun initAuthHelper() {
        /*
         *   1.init get token callback Listener
         */
        mTokenListener = object : TokenResultListener {
            override fun onTokenSuccess(ret: String) {
                this@RegisterAndLoginActivity.runOnUiThread {
                    try {
                        val aliAuthBean = AliAuthBean()
                        aliAuthBean.accessCode = ret
                        //
                        if (isUmengLoginState) {
                            //绑定手机号码
                            umengLoginBindPhone(aliAuthBean.accessCode)
                        } else {
                            autoLogin(aliAuthBean)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        aliAuthFailed()
                    }
                    /*
                     *   setText just show the result for get token。
                     *   use ret to verfiy number。
                     */
                    mAlicomAuthHelper?.quitAuthActivity()
                }
            }

            override fun onTokenFailed(ret: String) {
                this@RegisterAndLoginActivity.runOnUiThread {
                    //验证失败跳转到验证码/密码界面
                    aliAuthFailed()
                    /*
                     *  setText just show the result for get token
                     *  do something when getToken failed, such as use sms verify code.
                     */
                    mAlicomAuthHelper?.quitAuthActivity()
                }
            }
        }

        /*
         *   2.init AlicomAuthHelper with tokenListener
         */
        mAlicomAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenListener)

        /*
         *   3.set debugMode when app is in debug mode, sdk will print log in debug mode
         */
        mAlicomAuthHelper?.setDebugMode(BuildConfig.DEBUG)

        requestPermission()
        /*
         *   8.config authorization page ui to adapte app ui theme
         */
        mAlicomAuthHelper?.setAuthUIConfig(AuthUIConfig.Builder()
                .setAppPrivacyOne("自定义协议", "https://www.aliyun.com/product/dypns")
                .setLogoImgPath("ic_launcher")
                .setPrivacyState(true)
                .setCheckboxHidden(true)
                .create())

        mAlicomAuthHelper?.preLogin(5, object : PreLoginResultListener {
            override fun onTokenSuccess(s: String) {
                Log.e("mTokenListener", "preLogin Success：$s")
            }

            override fun onTokenFailed(s: String, s1: String) {
                Log.e("mTokenListener", "preLogin Failed：$s")
            }
        })
    }

    private fun initView() {
        val str = "壹点灵用户使用协议、隐私保护政策"
        val spannableString = SpannableString(str)
        spannableString.setSpan(object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = Color.WHITE
                ds.isUnderlineText = true      //设置下划线
            }

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

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


        handler = Handler()


        setHint()

        if (isUmengLoginState) {
            tv_skip.visibility = View.VISIBLE
            tv_des.text = "首次绑定即送大礼包"
            iv_weixin.visibility = View.GONE
            iv_qq.visibility = View.GONE
            tv_reg_title.text = "手机号绑定"
            tv_protocol.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()
            tv_country_code.text = "+" + countryCode?.replace("00", "")
        }

        setCountryIcon(countryCode)


        if (isFromGuide) {
            img_reg_back.visibility = View.INVISIBLE
            img_reg_back.isEnabled = false
            tv_skip.visibility = View.VISIBLE
            tv_skip.text = "随便逛逛"
        }
        //根据来源不同为当前页面埋点
        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 =  "")
        }
    }

    private fun setHint() {
        val hintStr = SpannableString(resources.getString(R.string.user_edittext_hint))// 定义hint的值
        val ass = AbsoluteSizeSpan(16, true)// 设置字体大小 true表示单位是SP
        hintStr.setSpan(ass, 0, hintStr.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        et_phone_number.hint = SpannedString(hintStr)
    }

    /**
     * 设置点击事件
     */
    private fun setClickEvent() {
        tv_skip.setOnClickListener {
            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()
        }
        //微信登录
        iv_weixin.setOnClickListener {

            mPresenter.loginByThird(this, SHARE_MEDIA.WEIXIN)
        }
        //QQ 登录
        iv_qq.setOnClickListener {

            val config = UMShareConfig()
            config.isNeedAuthOnGetUserInfo(true)
            UMShareAPI.get(this).setShareConfig(config)
            mPresenter.loginByThird(this, SHARE_MEDIA.QQ)
        }
        ll_country.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)
        }
        //下一步
        iv_next.setOnClickListener {

            if (checkPhone()) {
                mPresenter.checkPhoneStatus(userPhoneNumber!!, countryCode!!, isUmengLoginState)
            }
        }
        //手机号输入框
        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
            }
        }
        //删除按钮
        iv_del.setOnClickListener {
            et_phone_number.setText("")
        }
    }

    /**
     * 检查手机号规范
     */
    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")) {
            view_lin.setBackgroundColor(Color.parseColor("#E8E8E8"))
            true
        } else {
            view_lin.setBackgroundColor(Color.parseColor("#FB6761"))
            ToastUtil.toastShort("手机号格式错误")
            startAnim()
            false
        }
    }

    /**
     * 三方登录成功后绑定手机号
     */
    private fun umengLoginBindPhone(accessCode: String?) {
        var param = BindPhoneJavaParam(accessCode!!, countryCode!!, userPhoneNumber!!, "", UserHelper.getUserInfo()!!.uid!!)

        mPresenter.bindPhone(param)
    }

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

    /**
     *三方登录成功
     */
    override fun thirdLoginSuccess(userInfo: UserResponse.UserInfo) {
        var bindPhone = userInfo.bind_phone
        if (bindPhone != 1) {
            countryCode = userInfo.country_code
            isUmengLoginState = true
            tv_skip.visibility = View.VISIBLE
            tv_des.text = "首次绑定即送大礼包"
            iv_weixin.visibility = View.GONE
            iv_qq.visibility = View.GONE
            tv_reg_title.text = "手机号绑定"
            tv_protocol.visibility = View.GONE
        } else {
            ActivityManager.getInstance().finishActivity(VerificationCodeActivity::class.java)
            ActivityManager.getInstance().finishActivity(InputPassWordActivity::class.java)
            ActivityManager.getInstance().finishActivity(RegisterAndLoginActivity::class.java)
            if (isFromGuide) {
                startActivity(UserIn.mainIntent(this))
            }
        }
    }

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

    /**
     * 服务端校验阿里一键认证成功，设置sdk token
     *
     * 成功的回调 :
     * @see getAuthToken
     *
     * 失败的回调 ：
     * @see aliAuthFailed
     */
    override fun getAuthToken(configDTOs: List<VendorConfig>) {
//        mAlicomAuthHelper!!.getAuthToken(5000)
    }

    /**
     * 服务端校验阿里一键认证认证失败
     *
     * 成功的回调 :
     * @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, isUmengLoginState, false)
            }
        }
    }

    /**
     * 通过阿里sdk一键认证服务登陆
     */
    private fun autoLogin(bean: AliAuthBean) {
        var param = PhoneLoginAutoParam(bean.accessCode!!, userPhoneNumber!!)
        mPresenter.autoLogin(param)
    }

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

        ActivityManager.getInstance().finishActivity(VerificationCodeActivity::class.java)
        ActivityManager.getInstance().finishActivity(InputPassWordActivity::class.java)
        ActivityManager.getInstance().finishActivity(RegisterAndLoginActivity::class.java)
    }

    /**
     *菊花框
     */
    override fun showLoading(state: Boolean) {
        if (state) {
            iv_next.visibility = View.GONE
            iv_next.isEnabled = false
            pb_Normal.visibility = View.VISIBLE
        } else {
            iv_next.visibility = View.VISIBLE
            iv_next.isEnabled = true
            pb_Normal.visibility = View.GONE
        }
    }


    /**
     * 自动登录成功
     */
    override fun autoLoginSuccess() {
        ll_success.visibility = View.VISIBLE
        handler!!.postDelayed({
            val size = ActivityManager.getActivitySize()
            if (size == 1) {
                ActivityManager.finishAll()
                startActivity(UserIn.mainIntent(this))
            } else {
                ActivityManager.getInstance().finishActivity(VerificationCodeActivity::class.java)
                ActivityManager.getInstance().finishActivity(InputPassWordActivity::class.java)
                ActivityManager.getInstance().finishActivity(RegisterAndLoginActivity::class.java)
            }
        }, 3000)
    }


    override fun onBackPressed() {
        //当前stack只有一个activity，说明被挤掉线的
        if (ActivityManager.getActivitySize() == 1) {
            ActivityManager.finishOtherActivity(this)
            startActivity(UserIn.mainIntent(this, 4))
            finish()
        } else {
            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)

            tv_country_code.text = "+" + countryCode?.replace("00", "")
        }
    }

    /**
     * 根据国家个地区号设置国旗
     */
    private fun setCountryIcon(code: String?) {
        when (code) {
            "0086" -> iv_country_icon.setImageResource(R.drawable.user_ic_china)
            "001" -> iv_country_icon.setImageResource(R.drawable.user_country_usa)
            "00886" -> iv_country_icon.setImageResource(R.drawable.user_ic_china)
            "0081" -> iv_country_icon.setImageResource(R.drawable.user_country_japan)
            "00852" -> iv_country_icon.setImageResource(R.drawable.user_country_hk)
            "0061" -> iv_country_icon.setImageResource(R.drawable.user_country_australia)
            "0064" -> iv_country_icon.setImageResource(R.drawable.user_country_nz)
            "0082" -> iv_country_icon.setImageResource(R.drawable.user_country_sk)
            "0060" -> iv_country_icon.setImageResource(R.drawable.user_country_malaysia)
            "0044" -> iv_country_icon.setImageResource(R.drawable.user_country_uk)
            else -> iv_country_icon.visibility = View.VISIBLE
        }
    }

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