<template>
  <div class="login">
    <div class="login-logo" />
    <h1 class="title-1">欢迎登录</h1>
    <van-form @submit="login">
      <div class="login-title">手机号</div>
      <van-field
        v-model="phone"
        placeholder="请输入手机号"
      >
        <template #button>
          <a class="count-down" :class="{not:count!==60}" href="javascript:;" @click="sendSMS">{{ count===60?'发送验证码':'重新获取('+count+')' }}</a>
        </template>
      </van-field>

      <div class="login-title">验证码</div>
      <van-field
        v-model="code"
        placeholder="请输入验证码"
      />
      <div style="border-radius: 15px;margin-top: 20px">
        <van-button block :loading="loading" loading-text="系统登录中..." type="info" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import '@/styles/login.scss'
import { sendSms } from '../../api/main'

export default {
  data() {
    return {
      code: '',
      phone: '',
      count: 60,
      loading: false
    }
  },
  mounted() {
    this.$toast.clear()
  },
  methods: {
    sendSMS() {
      if (!(/^1[3456789]\d{9}$/.test(this.phone))) {
        this.$toast('请输入正确的手机号')
        return
      }
      if (this.count !== 60) return
      this.count--
      sendSms({
        phone: this.phone
      })
      const intal = setInterval(() => {
        this.count--
        if (this.count === 0) {
          this.count = 60
          clearInterval(intal)
        }
      }, 1000)
    },
    login() {
      if (!this.code) {
        this.$toast('请输入验证码')
        return
      }
      if (this.loading) return
      this.loading = true
      this.$store.dispatch('user/login', {
        code: this.code,
        phone: this.phone
      }).then(res => {
        this.loading = false
        this.$router.push('/home')
      }, err => {
        this.loading = false
      })
    }
  }
}
</script>
