<template>
  <div class="login-form code-login">
    <div class="login-form__item">
      <input
        type="text"
        class="login-input"
        placeholder="手机号"
        v-model="ruleForm.account"
      />
    </div>
    <div class="login-form__item">
      <input
        type="password"
        class="login-input"
        placeholder="验证码"
        v-model="ruleForm.password"
        @keyup.enter="onSubmit"
      />
      <countdown-button
        @click.native="onSendCode"
        ref="countdown"
      ></countdown-button>
    </div>
  </div>
</template>

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

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 true
    },
    // 发送验证码
    onSendCode() {
      this.$refs.form.validate('account').then(response => {
        if (!response) {
          // 开始倒计时
          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>
