package com.yidian.shenghuoquan.newscontent.wallet.ui

import android.annotation.SuppressLint
import android.os.Bundle
import com.orhanobut.hawk.Hawk
import com.yidian.common.HawkConfig
import com.yidian.common.XRouterPathConstants
import com.yidian.common.base.BaseActivity
import com.yidian.common.extensions.clickAntiShake
import com.yidian.common.extensions.initTitleBar
import com.yidian.shenghuoquan.newscontent.databinding.ActivityVerifyIdentifyBinding
import com.yidian.shenghuoquan.newscontent.utils.CountDownTimerUtils
import com.yidian.shenghuoquan.newscontent.utils.TextWatcherAdapter
import com.yidian.xpage.XPageManager

/**
 * 钱包主人验证身份
 */
class VerifyIdentityActivity : BaseActivity<ActivityVerifyIdentifyBinding>() {

  private lateinit var mCountDownTimerUtils: CountDownTimerUtils

  override fun createViewBinding(): ActivityVerifyIdentifyBinding {
    return ActivityVerifyIdentifyBinding.inflate(layoutInflater)
  }

  override fun getXPageName(): String {
    return XRouterPathConstants.VERIFY_IDENTITY
  }

  override fun init(savedInstanceState: Bundle?) {
    super.init(savedInstanceState)
    initView()
    initClick()
    requestSmsCode()
  }

  private fun initView() {
    initTitleBar(viewBind.include.toolbar, viewBind.include.tvTitle, "")
    // 默认显示空，等发送成功后再提示接收的手机号
    viewBind.tvSendMobile.text = ""
    // 初始化倒计时
    mCountDownTimerUtils = CountDownTimerUtils(viewBind.tvGetCode, 60000, 1000, "重新获取")
  }

  private fun initClick() {
    // 重新获取验证码
    viewBind.tvGetCode.clickAntiShake {
      viewBind.etSmsCode.setText("")
      requestSmsCode()
    }
    // 验证码输入监听
    viewBind.etSmsCode.addTextChangedListener(object : TextWatcherAdapter() {
      override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (s?.length == 6) {
          // 校验验证码
          checkSmsCode()
        }
      }
    })
  }

  /**
   * 请求验证码
   */
  @SuppressLint("SetTextI18n")
  private fun requestSmsCode() {
    // todo 请求验证码，成功后开始倒计时
    mCountDownTimerUtils.start()
    //  todo 请求验证码成功则，显示接收信息的手机号
    val mobile = Hawk.get(HawkConfig.Mobile, "")
    viewBind.tvSendMobile.text = "验证码已发送至$mobile"
  }

  /**
   * 校验验证码
   */
  private fun checkSmsCode() {
    // todo 校验成功后，进入微信授权
    XPageManager.push(XRouterPathConstants.WECHAT_AUTH, null)
    // 关闭当前页
    XPageManager.pop(null)
  }

  override fun onDestroy() {
    super.onDestroy()
    mCountDownTimerUtils.cancel()
  }


}
