package com.hongyegroup.cpt_auths.ui

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import com.guadou.cs_cptservices.base.activity.YYBaseVDBActivity
import com.guadou.cs_router.YYRouterService
import com.guadou.cs_router.app.IAppComponentServer
import com.guadou.lib_baselib.base.vm.EmptyViewModel
import com.guadou.lib_baselib.bean.DataBindingConfig
import com.guadou.lib_baselib.ext.toast
import com.guadou.lib_baselib.utils.CheckUtil
import com.guadou.lib_baselib.utils.CommUtils
import com.guadou.lib_baselib.utils.KeyboardUtils
import com.hongyegroup.cpt_auths.BR
import com.hongyegroup.cpt_auths.R
import com.hongyegroup.cpt_auths.databinding.ActivityPensonalForgotPsdVerityBinding

/**
 * 用户忘记密码 2-短信验证码
 */
class PensonalForgotPsdVerityActivity : YYBaseVDBActivity<EmptyViewModel, ActivityPensonalForgotPsdVerityBinding>(), View.OnKeyListener {

    private var mSMSService: IAppComponentServer? = null
    private var mMobilePhone: String? = null
    private val clickProxy by lazy { ClickProxy() }

    companion object {
        fun startInstance(phone: String?) {
            val context = CommUtils.getContext()
            val intent = Intent(context, PensonalForgotPsdVerityActivity::class.java)
            intent.putExtra("phone", phone)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.activity_pensonal_forgot_psd_verity)
            .addBindingParams(BR.click, clickProxy)
    }

    override fun getDataFromIntent(intent: Intent) {
        mMobilePhone = intent.getStringExtra("phone")
        clickProxy.mMobilePhoneLD.value = mMobilePhone
    }

    override fun startObserve() {

    }

    override fun init(savedInstanceState: Bundle?) {

        initListener()
    }

    private fun initListener() {

        mBinding.editTextFirstCode.setOnKeyListener(this)
        mBinding.editTextSecondCode.setOnKeyListener(this)
        mBinding.editTextThirdCode.setOnKeyListener(this)
        mBinding.editTextFourthCode.setOnKeyListener(this)
        mBinding.editTextFifthCode.setOnKeyListener(this)
        mBinding.editTextSixthCode.setOnKeyListener(this)

        //默认展示第一个
        mBinding.editTextFirstCode.isFocusable = true
        mBinding.editTextFirstCode.isFocusableInTouchMode = true
        setFocusedBackground(mBinding.frameFirstCode)
        CommUtils.getHandler().postDelayed({
            KeyboardUtils.openSoftKeyboard(mActivity, mBinding.editTextHidden)
        }, 250)

    }

    private fun setFocusedBackground(frameLayout: FrameLayout) {
        setViewBackground(frameLayout, R.drawable.white_input_finish)
    }

    private fun setDefaultBackground(frameLayout: FrameLayout) {
        setViewBackground(frameLayout, R.drawable.white_input_field)
    }

    private fun setViewBackground(frameLayout: FrameLayout, resource: Int) {
        if (resource == 0) return
        frameLayout.background = ContextCompat.getDrawable(mContext, resource)
    }

    private fun setFocus(editText: EditText?) {
        if (editText == null) return
        editText.isFocusable = true
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
        editText.setSelection(editText.text.length)
    }

    /**
     * 检查焦点
     */
    fun checkFocus(view: View) {
        when (view.id) {
            R.id.edit_text_first_code -> {
                setFocusedBackground(mBinding.frameFirstCode)
                setFocus(mBinding.editTextHidden)
                KeyboardUtils.showKeyboard(mActivity)
            }
            R.id.edit_text_second_code -> {
                setFocus(mBinding.editTextHidden)
                KeyboardUtils.showKeyboard(mActivity)
            }
            R.id.edit_text_third_code -> {
                setFocus(mBinding.editTextHidden)
                KeyboardUtils.showKeyboard(mActivity)
            }
            R.id.edit_text_fourth_code -> {
                setFocus(mBinding.editTextHidden)
                KeyboardUtils.showKeyboard(mActivity)
            }
            R.id.edit_text_fifth_code -> {
                setFocus(mBinding.editTextHidden)
                KeyboardUtils.showKeyboard(mActivity)
            }
            R.id.edit_text_sixth_code -> {
                setFocus(mBinding.editTextHidden)
                KeyboardUtils.showKeyboard(mActivity)
            }

        }
    }

    /**
     * 展示在顶部的Top
     */
    private fun showFramCode(charSequence: String) {

        if (charSequence.isEmpty()) {
            setFocusedBackground(mBinding.frameFirstCode)
            setDefaultBackground(mBinding.frameSecondCode)
            setDefaultBackground(mBinding.frameThirdCode)
            setDefaultBackground(mBinding.frameFourthCode)
            setDefaultBackground(mBinding.frameFifthCode)
            setDefaultBackground(mBinding.frameSixthCode)
            mBinding.editTextFirstCode.setText("")
        } else if (charSequence.length == 1) {
            setFocusedBackground(mBinding.frameFirstCode)
            setFocusedBackground(mBinding.frameSecondCode)
            setDefaultBackground(mBinding.frameThirdCode)
            setDefaultBackground(mBinding.frameFourthCode)
            setDefaultBackground(mBinding.frameFifthCode)
            setDefaultBackground(mBinding.frameSixthCode)
            mBinding.editTextFirstCode.setText(charSequence[0].toString())
            mBinding.editTextSecondCode.setText("")
            mBinding.editTextThirdCode.setText("")
            mBinding.editTextFourthCode.setText("")
            mBinding.editTextFifthCode.setText("")
            mBinding.editTextSixthCode.setText("")
        } else if (charSequence.length == 2) {
            setFocusedBackground(mBinding.frameFirstCode)
            setFocusedBackground(mBinding.frameSecondCode)
            setFocusedBackground(mBinding.frameThirdCode)
            setDefaultBackground(mBinding.frameFourthCode)
            setDefaultBackground(mBinding.frameFifthCode)
            setDefaultBackground(mBinding.frameSixthCode)
            mBinding.editTextSecondCode.setText(charSequence[1].toString())
            mBinding.editTextThirdCode.setText("")
            mBinding.editTextFourthCode.setText("")
            mBinding.editTextFifthCode.setText("")
            mBinding.editTextSixthCode.setText("")
        } else if (charSequence.length == 3) {
            setFocusedBackground(mBinding.frameFirstCode)
            setFocusedBackground(mBinding.frameSecondCode)
            setFocusedBackground(mBinding.frameThirdCode)
            setFocusedBackground(mBinding.frameFourthCode)
            setDefaultBackground(mBinding.frameFifthCode)
            setDefaultBackground(mBinding.frameSixthCode)
            mBinding.editTextThirdCode.setText(charSequence[2].toString())
            mBinding.editTextFourthCode.setText("")
            mBinding.editTextFifthCode.setText("")
            mBinding.editTextSixthCode.setText("")
        } else if (charSequence.length == 4) {
            setFocusedBackground(mBinding.frameFirstCode)
            setFocusedBackground(mBinding.frameSecondCode)
            setFocusedBackground(mBinding.frameThirdCode)
            setFocusedBackground(mBinding.frameFourthCode)
            setFocusedBackground(mBinding.frameFifthCode)
            setDefaultBackground(mBinding.frameSixthCode)
            mBinding.editTextFourthCode.setText(charSequence[3].toString())
            mBinding.editTextFifthCode.setText("")
            mBinding.editTextSixthCode.setText("")
        } else if (charSequence.length == 5) {
            setFocusedBackground(mBinding.frameFirstCode)
            setFocusedBackground(mBinding.frameSecondCode)
            setFocusedBackground(mBinding.frameThirdCode)
            setFocusedBackground(mBinding.frameFourthCode)
            setFocusedBackground(mBinding.frameFifthCode)
            setFocusedBackground(mBinding.frameSixthCode)
            mBinding.editTextFifthCode.setText(charSequence[4].toString())
            mBinding.editTextSixthCode.setText("")
        } else if (charSequence.length == 6) {
            setFocusedBackground(mBinding.frameFirstCode)
            setFocusedBackground(mBinding.frameSecondCode)
            setFocusedBackground(mBinding.frameThirdCode)
            setFocusedBackground(mBinding.frameFourthCode)
            setFocusedBackground(mBinding.frameFifthCode)
            setFocusedBackground(mBinding.frameSixthCode)
            mBinding.editTextSixthCode.setText(charSequence[5].toString())
            KeyboardUtils.closeSoftKeyboard(mBinding.editTextSixthCode)

            val code: String = mBinding.editTextHidden.text.toString()

            if (!CheckUtil.isEmpty(code)) {
                verifyCode(code)
            }
        }
    }

    /**
     * 键盘监听
     */
    override fun onKey(view: View?, keyCode: Int, event: KeyEvent?): Boolean {
        if (event?.action == KeyEvent.ACTION_DOWN) {
            val id = view?.id
            if (id == R.id.edit_text_hidden) {
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    when (mBinding.editTextHidden.text.length) {
                        6 -> {
                            mBinding.editTextSixthCode.setText("")
                        }
                        5 -> {
                            mBinding.editTextFifthCode.setText("")
                        }
                        4 -> {
                            mBinding.editTextFourthCode.setText("")
                        }
                        3 -> {
                            mBinding.editTextThirdCode.setText("")
                        }
                        2 -> {
                            mBinding.editTextSecondCode.setText("")
                        }
                        1 -> {
                            mBinding.editTextFirstCode.setText("")
                        }
                    }

                    if (mBinding.editTextHidden.length() > 0) {
                        mBinding.editTextHidden.setText(mBinding.editTextHidden.text.subSequence(0, mBinding.editTextHidden.length() - 1))
                        mBinding.editTextHidden.setSelection(mBinding.editTextHidden.text.length)
                    }

                    return true
                }
            }
        }
        return false
    }

    /**
     * 检测验证码
     */
    private fun verifyCode(code: String) {
        showStateProgress()

        if (mSMSService == null) {
            mSMSService = YYRouterService.appComponentServer?.initSMS()
        }

        mSMSService?.verifySMSCode(mActivity, code) { isSuccess ->
            hideStateProgress()
            if (isSuccess) {
                verifySuccess()
            }
        }
    }

    //检测成功之后的跳转
    private fun verifySuccess() {
        ResetPasswordActivity.startInstance(isFromBusiness = false, isForgort = true)
    }

    /**
     * DataBinding事件处理
     */
    inner class ClickProxy {

        //被验证的电话号码
        val mMobilePhoneLD: MutableLiveData<String> = MutableLiveData()

        //重新发送
        fun resendCode() {
            if (mSMSService == null) {
                mSMSService = YYRouterService.appComponentServer?.initSMS()
            }

            showStateProgress()
            mSMSService?.sendSMSCode(mActivity, mMobilePhone ?: "",
                sendAction = { isSuccess ->
                    hideStateProgress()
                    if (isSuccess) {
                        toast("Send Success!")
                    }
                }, verifyAction = { isSuccess ->
                    if (isSuccess) {
                        verifySuccess()
                    }
                })

        }

        //获取焦点的监听
        val onFocusGet: (textView: TextView) -> Unit = {
            checkFocus(it)
        }

        val onTextChange: (str: String) -> Unit = {
            showFramCode(it)
        }

    }


}