<template>
  <div class="code-login">
    <van-form class="login-form" ref="form" v-on="$listeners">
      <van-field v-model="ruleForm.account" name="account" label="手机号" placeholder="请输入手机号" />
      <van-field
        v-model="ruleForm.password"
        :maxlength="4"
        name="password"
        label="验证码"
        placeholder="请输入验证码"
      >
        <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() {
      if (!this.ruleForm.account) {
        this.$notify('请输手机号')
        return false
      } else if (!this.ruleForm.password) {
        this.$notify('请输入验证码')
        return false
      }
      return this.$refs.form.submit()
    },
    // 发送验证码
    onSendCode() {
      if (!this.ruleForm.account) {
        this.$notify('请输手机号')
        return false
      }
      // 开始倒计时
      this.$refs.countdown.start()
      this.sendCodeRequest()
    },
    // 验证码
    sendCodeRequest() {
      api
        .sendResetPasswordCode({ account: this.ruleForm.account })
        .then(response => {
          if (response.code === 0) {
            this.$notify({ type: 'success', message: '验证码发送成功' })
          } else {
            // 停止计时
            this.$refs.countdown.stop()
            this.$notify(response.msg)
          }
        })
        .catch(error => {
          // 停止计时
          this.$refs.countdown.stop()
          error.response && this.$notify(error.response.data.message)
        })
    }
  }
}
</script>
