<template>
    <login-layout>
      <template #header>
        <span @click="toggle('phone-login')">手机号登录</span>
      </template>
      <template #form-title>
        <div>邮箱</div>
      </template>
      <template>
        <email-input v-model="email" :canEditEmail="canEditEmail"></email-input>
        <code-input
          v-model="code"
          :canGetCode="canGetCode"
          :countDown.sync="count"
          @get-code="getCode"></code-input>
      </template>
      <template #form-buttons>
        <main-button @click.native="login" :disabled="!canSubmit"></main-button>
      </template>
      <template #footer>
        <span @click="toggle('email-pwd-login')">密码登录</span>
      </template>
    </login-layout>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch, Inject, Emit } from 'vue-property-decorator';
import { Form, Field, CellGroup, Button } from 'vant';
import { Action } from 'vuex-class';
import LoginInterface from './login';
import { isCode, isEmail } from '@/const/pattern';
import { LoginType } from '@/const/enum';
import LoginLayout from '@/layout/LoginLayout.vue';
@Component({
  name: 'emailLogin',
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    LoginLayout,
  },
})
export default class Login extends Vue implements LoginInterface {
  @Inject('validate') private validate!: any;

  private email: string = '';
  private code: string = '';
  private count: number = 0;

  private get emailRule() {
    return {
      word: this.email,
      pattern: isEmail,
      message: '请输入正确的邮箱',
    };
  }
  private get codeRule() {
    return {
      word: this.code,
      pattern: isCode,
      message: '请输入验证码',
    };
  }

  private get canSubmit(): boolean {
    const { emailRule, codeRule, validate } = this;
    return !validate([emailRule, codeRule]);
  }
  private get canGetCode(): boolean {
    const { emailRule, validate } = this;
    return !validate([emailRule]);
  }
  private get canEditEmail(): boolean {
    return this.count <= 0;
  }
  public login() {
    const { email, code, emailRule, codeRule } = this;
    if (!this.canSubmit) { return; }
    this.$emit('login', {
      login_type: LoginType.EmailCode,
      email,
      code,
    });
  }
  @Emit('change-state')
  public toggle(state: string) {
    return state;
  }
  private getCode() {
    this.$api.user.sendEmail(this.email);
  }
}
</script>