package com.halo.assistant.fragment.user

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.view.View
import androidx.fragment.app.viewModels
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.ClickUtils
import com.gh.gamecenter.databinding.FragmentVerifyPhoneBinding

class VerifyPhoneFragment : ToolbarFragment() {

    private val mViewModel: VerifyPhoneViewModel by viewModels()
    private val mBinding by lazy { FragmentVerifyPhoneBinding.inflate(layoutInflater) }

    override fun handleMessage(msg: Message) {
        if (msg.what == 0) { // 验证码倒计时
            var arg1 = msg.arg1
            arg1--
            if (arg1 >= 0) {
                val message = Message()
                message.what = 0
                message.arg1 = arg1
                mBaseHandler.sendMessageDelayed(message, 1000)
                mBinding.captchaTv.text = arg1.toString() + "s"
            } else {
                mBinding.captchaTv.run {
                    text = "重新获取"
                    setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()))
                    isEnabled = true
                }
            }
        }
    }

    override fun getLayoutId() = 0

    override fun getInflatedLayout() = mBinding.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        arrayListOf(
            mBinding.captchaTv,
            mBinding.verifyBtn
        ).forEach {
            it.setOnClickListener(this)
        }

        setTextChangedListener()
        setObserver()

        SensorsBridge.trackMobileNumberVerificationPageShow()
    }

    private fun setObserver() {
        mViewModel.nextLiveData.observeNonNull(viewLifecycleOwner) {
            mBinding.captchaEt.showKeyBoard()
            toast("验证码短信已发送，请注意查收")
            // 启动验证码倒计时
            val message = Message()
            message.what = 0
            message.arg1 = 60 // 倒数时间

            mBaseHandler.sendMessage(message)
            mBinding.captchaTv.setTextColor(com.gh.gamecenter.common.R.color.hint.toColor(requireContext()))
            mBinding.captchaTv.isEnabled = false
        }
        mViewModel.finishLiveData.observeNonNull(viewLifecycleOwner) {
            requireActivity().setResult(
                Activity.RESULT_OK,
                Intent().putExtra(VERIFY_SUCCESS, true)
            )
            requireActivity().finish()
        }
    }

    private fun setTextChangedListener() {
        // 手机号EditText监听
        mBinding.phoneEt.setTextChangedListener { s, _, _, _ ->
            // 输入手机号码加空格
            val stringBuilder = StringBuilder()
            handlePhoneStringBuilder(s, stringBuilder)
            if (stringBuilder.toString() != s.toString()) {
                mBinding.phoneEt.setText(stringBuilder.toString())
                mBinding.phoneEt.setSelection(mBinding.phoneEt.text.toString().length)
            }

            val checkPhone = s.trim { it <= ' ' }.replace(" ".toRegex(), "")
            if (checkPhone.length < 11) {
                mBinding.captchaTv.isEnabled = false
                mBinding.captchaTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(requireContext()))
            } else {
                mBinding.captchaTv.isEnabled = true
                mBinding.captchaTv.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(requireContext()))
            }
        }

        // 验证码EditText监听
        mBinding.captchaEt.setTextChangedListener { s, _, _, _ ->
            if (s.length > 5) {
                mBinding.verifyBtn.isEnabled = true
                mBinding.verifyBtn.alpha = 1f
            } else {
                mBinding.verifyBtn.isEnabled = false
                mBinding.verifyBtn.alpha = 0.4f
            }
        }
    }

    private fun handlePhoneStringBuilder(s: CharSequence, stringBuilder: StringBuilder) {
        for (i in s.indices) {
            if (i != 3 && i != 8 && s[i] == ' ') {
                continue
            } else {
                stringBuilder.append(s[i])
                if ((stringBuilder.length == 4 || stringBuilder.length == 9)
                    && stringBuilder[stringBuilder.length - 1] != ' '
                ) {
                    stringBuilder.insert(stringBuilder.length - 1, ' ')
                }
            }
        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        // 防止快速点击
        if (ClickUtils.isFastDoubleClick()) return

        mBinding.run {
            when (v) {
                captchaTv -> {
                    val phoneNum = mBinding.phoneEt.text.toString().trim { it <= ' ' }.replace(" ".toRegex(), "")
                    if (phoneNum.length == 11) {
                        mViewModel.verifyPhoneOne(phoneNum, requireContext())
                    }
                }
                verifyBtn -> {
                    val phoneNum: String =
                        mBinding.phoneEt.text.toString().trim { it <= ' ' }.replace(" ".toRegex(), "")
                    when {
                        phoneNum.isBlank() -> toast("手机号不允许为空")
                        phoneNum.length < 11 -> toast("手机号错误请重新输入")
                        captchaEt.text.isBlank() -> toast("验证码不允许为空")
                        else -> mViewModel.verifyPhoneTwo(
                            phoneNum,
                            mBinding.captchaEt.text.toString().trim(),
                            requireContext()
                        )
                    }
                }
            }
        }
    }

    companion object {
        const val VERIFY_SUCCESS = "verify_success" // 验证成功
    }
}