package com.duben.microtribe.ui.activitys

import android.app.Dialog
import android.media.AudioManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextPaint
import android.text.TextUtils
import android.text.style.ClickableSpan
import android.view.KeyEvent
import android.view.View
import androidx.core.content.ContextCompat
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.duben.library.utils.nodoubleclick.AntiShake
import com.duben.microtribe.R
import com.duben.microtribe.common.Constant
import com.duben.microtribe.manager.ActivityPageManager
import com.duben.microtribe.manager.UserManager
import com.duben.microtribe.mvp.presenters.LoginPresenter
import com.duben.microtribe.mvp.views.LoginView
import com.duben.microtribe.ui.activitys.base.BaseActivity
import com.duben.microtribe.ui.widgets.CustomDialogAsApple
import com.duben.microtribe.ui.widgets.DialogListener
import com.duben.microtribe.utils.BackInputUtil
import com.duben.microtribe.utils.LogUtil
import com.duben.microtribe.utils.SpanUtils
import com.duben.microtribe.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_mobile_login.*
import kotlinx.android.synthetic.main.header_layout.*


/**
 * 描述：手机号登录
 * 作者：孟崔广
 * 时间：2020/12/2 14:21
 */
class MobileLoginActivity : BaseActivity(), LoginView, View.OnClickListener {

    companion object {
        val TYPE = "type"
    }

    private var enterType = ""//【vip】表示挽留用户

    private val loginPresenter by lazy { LoginPresenter() }

    private var mobile: String? = null
    private var isCheckAgree = false

    override fun getBundleExtras(extras: Bundle?) {
        super.getBundleExtras(extras)
        extras?.let {
            enterType = it.getString(TYPE, "")
        }
    }

    override fun initViewsAndEvents() {
        loginPresenter.attachView(this)
        initView()
        initListener()
    }

    override fun getContentViewLayoutID() = R.layout.activity_mobile_login

    override fun toggleOverridePendingTransition() = true

    override fun getOverridePendingTransitionMode() = TransitionMode.BOTTOM

    override fun isApplyKitKatTranslucency() = false

    override fun onDestroy() {
        super.onDestroy()
        loginPresenter.detachView()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                if (TextUtils.equals(enterType, "vip")) {
                    bindDialog()
                } else {
                    finish()
                }
            }
        }
        return true
    }

    override fun finish() {
        super.finish()
        //关闭窗体动画显示
        overridePendingTransition(0, R.anim.push_bottom_out)
    }

    override fun onClick(v: View?) {
        if (AntiShake.check(v?.id)) return

        when (v?.id) {
            R.id.iv_left_icon -> {
                if (TextUtils.equals(enterType, "vip")) {
                    bindDialog()
                } else {
                    finish()
                }
            }
            R.id.tvLoginSendcode -> {
                var mobile = etLoginMobile.text.toString().trim()
                if (mobile.length < 13) {
                    showToast("请输入手机号")
                    return
                }

                sendCodeThread()

                mobile = mobile.replace(" ".toRegex(), "")
                loginPresenter.sendMobileCode(mobile)
            }
            R.id.tvLoginNext -> {
                var mobile = etLoginMobile.text.toString().trim()
                if (mobile.length < 13) {
                    showToast("请输入手机号")
                    return
                }

                val code = etLoginCode.text.toString().trim()
                if (code.length < 4) {
                    showToast("请输入验证码")
                    return
                }

                if (!isCheckAgree) {
                    ToastUtil.showLong(this, "请勾选同意后再进行登录")
                    llMobileloginCheck.postDelayed({
                        YoYo.with(Techniques.Shake).duration(500).repeat(2)
                            .playOn(llMobileloginCheck)
                    }, 200)
                    return
                }

//                mobile = mobile.replace(" ".toRegex(), "")
//
//                // 登录
//                loginPresenter.login(mobile, code)
                mobile = mobile.replace(" ".toRegex(), "")
                loginPresenter.login(mobile, code)
            }
        }
    }

    override fun loginSuc() {
        if (isFinishing) return

        // false-登录  true-绑定手机号
        showToast("绑定成功")

        hideLoading()

        Handler(Looper.getMainLooper()).postDelayed({
            readyGoThenKill(MainActivity::class.java)
        }, 1000)
    }

    override fun sendCodeSuc() {
        if (!isFinishing) {
            sendCodeThread()
        }
    }

    override fun mergeAccount(mobile: String, wxOpenId: String, key: String) {

    }

    private fun initView() {
        tv_title.text = "绑定手机号"
        tvLoginNext.text = "确认绑定"
        iv_left_icon.visibility = View.VISIBLE
        iv_left_icon.setImageResource(R.mipmap.ic_arrow_back)

        BackInputUtil.phoneNumAddSpace(etLoginMobile)
        mobile = UserManager.getInstance().mobile
        if (!TextUtils.isEmpty(mobile)) {
            etLoginMobile.setText(mobile)
            etLoginMobile.setSelection(mobile!!.length + 2)
        }

        SpanUtils.with(tvMobileAgreement)
            .append("已阅读并同意")
            .append("《用户注册协议》").setClickSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    val bundle = Bundle()
                    bundle.putString(WebActivity.WEB_TITLE, getString(R.string.register_name))
                    bundle.putString(WebActivity.WEB_URL, Constant.REGISTER_URL)
                    readyGo(WebActivity::class.java, bundle)
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(mContext, R.color.tv_message_recente_money)
                    ds.isUnderlineText = false
                }
            })
            .append("、")
            .append("《用户隐私协议》").setClickSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    val bundle = Bundle()
                    bundle.putString(WebActivity.WEB_TITLE, getString(R.string.privacy_name))
                    bundle.putString(WebActivity.WEB_URL, Constant.PRIVACY_URL)
                    readyGo(WebActivity::class.java, bundle)
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(mContext, R.color.tv_message_recente_money)
                    ds.isUnderlineText = false
                }
            })
            .append("与您的利益切身相关。请您注册前务必仔细阅读!")
            .create()
    }

    private fun initListener() {
        iv_left_icon.setOnClickListener(this)
        tvLoginSendcode.setOnClickListener(this)
        tvLoginNext.setOnClickListener(this)

        mobileloginCheck.setOnCheckedChangeListener { buttonView, isChecked ->
            this.isCheckAgree = isChecked
        }
    }

    var num = 0
    var run: Runnable? = null

    fun sendCodeThread() {
        num = 60
        tvLoginSendcode?.let {
            it.isEnabled = false
            it.text = "（$num）重新获取"

            run = object : Runnable {
                override fun run() {
                    num--
                    LogUtil.d("login", "login num:$num")
                    if (num == 0) {
                        it.text = "重新获取"
                        it.isEnabled = true
                    } else {
                        it.text = "（$num）重新获取"
                        it.postDelayed(this, 1000)
                    }
                }
            }
            it.postDelayed(run, 1000)
        }
    }

    private fun bindDialog() {
        val cdaa = CustomDialogAsApple(context, object : DialogListener() {
            override fun onClick(dialog: Dialog?, v: View?) {
                dialog?.dismiss()
                when (v?.id) {
                    R.id.dialog_btn_left -> {
                        readyGo(MainActivity::class.java)
                        val activity =
                            ActivityPageManager.getInstance().getActivity(MainActivity::class.java)
                        if (activity != null && activity is MainActivity) {
                            activity.clickTab4Layout()
                        }
                    }
                    R.id.dialog_btn_right -> {

                    }
                }
            }
        })
        cdaa.setTitle("温馨提示")
        cdaa.setContent("为了保障您的账号安全，我们需要您绑定手机号，帮助您更好的使用我们的产品")
        cdaa.setLeft("关闭")
        cdaa.setRight("去绑定")
        cdaa.setLeftColor(R.color.gray)
        cdaa.setRightColor(R.color.main_mints)
        cdaa.show()
    }
}