<template>
  <login-layout>
    <template #header>
      <span @click="toggle('email-login')">邮箱登录</span>
    </template>
    <template #form-title>
      <div>验证码登录</div>
    </template>
    <template>
      <phone-input v-model="phone"></phone-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" :btnText="'登录'"></main-button>
    </template>
    <template #footer>
      <span @click="toggle('phone-pwd-login')">密码登录</span>
    </template>
  </login-layout>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch, Inject, Emit } from 'vue-property-decorator';
import { Action } from 'vuex-class';
import LoginInterface from './login';
import { isPhone , isCode } from '@/const/pattern';
import { LoginType } from '@/const/enum';
import LoginLayout from '@/layout/LoginLayout.vue';

@Component({
  name: 'phoneLogin',
  components: {
    LoginLayout,
  },
})
export default class Login extends Vue {

  @Inject('validate') private validate!: any;

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

  private get phoneRule() {
    return {
      word: this.phone,
      pattern: isPhone,
      message: '请输入正确的手机号',
    };
  }
  private get codeRule() {
    return {
      word: this.code,
      pattern: isCode,
      message: '请输入验证码',
    };
  }
  private get canSubmit() {
    const { phoneRule, codeRule, validate } = this;
    return !validate([phoneRule, codeRule]);
  }
  private get canGetCode() {
    const { phoneRule, validate } = this;
    return !validate([phoneRule]);
  }
  private get canEditPhone(): boolean {
    return this.count <= 0;
  }

  @Emit('change-state')
  private toggle(state: string = 'email-login') {
    return state;
  }
  private getCode() {
    this.$api.user.sendSms(this.phone);
  }
  private login() {
    if (!this.canSubmit) { return; }
    this.$emit('login', {
      login_type: LoginType.PhoneCode,
      phone: this.phone,
      code: this.code,
    });
  }
}
</script>