<template>
  <div class="code-login">
    <van-form class="login-form" ref="form" v-on="$listeners">
      <van-field
        type="tel"
        v-model="ruleForm.account"
        name="account"
        label="手机号"
        placeholder="请输入手机号"
        :maxlength="11"
      />
      <van-field
        v-model="ruleForm.password"
        type="digit"
        name="password"
        label="验证码"
        placeholder="请输入验证码"
        :maxlength="4"
      >
        <template slot="button">
          <countdown-button @click.native="onSendCode" ref="countdown"></countdown-button>
        </template>
      </van-field>
    </van-form>
  </div>
</template>

<script>
import * as api from '@/api/account'
import CountdownButton from '@/components/CountdownButton.vue'

export default {
  name: 'CodeLogin',
  components: { CountdownButton },
  data() {
    return {
      ruleForm: { account: '', password: '' }
    }
  },
  methods: {
    submit() {
      const phone = this.ruleForm.account
      if (!phone || phone.length !== 11) {
        this.$toast('请输入正确的手机号码')
        return false
      } else if (!this.ruleForm.password) {
        this.$toast('验证码输入错误，请重新输入')
        return false
      }
      return this.$refs.form.submit()
    },
    // 发送验证码
    onSendCode() {
      if (!this.ruleForm.account) {
        this.$toast('请输入正确的手机号码')
        return false
      }
      // 开始倒计时
      this.$refs.countdown.start()
      this.sendCodeRequest()
    },
    // 验证码
    sendCodeRequest() {
      api
        .sendResetPasswordCode({ account: this.ruleForm.account })
        .then(response => {
          if (response.code === 0) {
            this.$toast({ type: 'success', message: '验证码已发送' })
          } else {
            // 停止计时
            this.$refs.countdown.stop()
            this.$toast(response.msg)
          }
        })
        .catch(error => {
          // 停止计时
          this.$refs.countdown.stop()
          error.response && this.$toast(error.response.data.message)
        })
    }
  }
}
</script>
