<template>
  <div id="login" class="app">
    <van-image :src="require('../../assets/image/0.jpg')" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="手机号"
        label="手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      >
        <template #button>
          <van-button
            size="small"
            v-if="!code"
            :disabled="!username"
            @click="getCodes"
          >
            发送验证码
          </van-button>
          <van-count-down v-else format="ss" @finish="endTime" :time="60000" />
        </template>
      </van-field>
      <van-field
        v-model="password"
        center
        clearable
        label="短信验证码"
        :rules="[{ required: true, message: '请填写验证码' }]"
      >
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="danger" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import {
  Form as vanForm,
  Button as vanButton,
  Field as vanField,
  CountDown as vanCountDown,
  Image as vanImage
} from "vant";
import { login, getCode } from "@/api/user/user.js";
import "vant/lib/button/style";
import "vant/lib/field/style";
import "vant/lib/form/style";
import { getToken, setToken, setUserInfo } from "@/utils/common.js";

export default {
  name: "app",
  data: function() {
    return {
      username: "",
      password: "",
      code: false
    };
  },
  created() {
    if (getToken()) location.replace("./index.html");
  },
  methods: {
    endTime() {
      this.code = false;
    },
    getCodes() {
      getCode({
        phone: this.username
      })
        .then(() => {
          this.code = true;
        })
        .catch(() => {
          // console.log(err);
        });
    },
    onSubmit() {
      login({
        phone: this.username,
        code: this.password
      }).then(res => {
        setToken(res.accessToken);
        setUserInfo({
          userName: res.nickName
        });
        location.href = "./index.html";
      });
    }
  },
  mounted() {},
  beforeDestroy: function() {},
  components: { vanForm, vanButton, vanField, vanCountDown, vanImage }
};
</script>
<style lang="scss">
#login {
  height: 100%;
  .van-image {
    margin: 5em auto;
    width: 5em;
    display: block;
  }
  .van-form {
    height: 100%;
  }
}
</style>
