<template>
  <transition name="login-fade" mode="out-in">
        <keep-alive>
          <component :is="state" @change-state="changeState" @login="login"></component>
        </keep-alive>
      </transition>
</template>
<script lang="ts">
import { Component, Prop, Vue, Provide } from 'vue-property-decorator';
import { Form, Field, CellGroup, Button } from 'vant';
import { PhoneLogin, PhonePwdLogin, EmailLogin, EmailPwdLogin } from './components';
import { Action, Mutation } from 'vuex-class';
@Component({
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    PhoneLogin,
    PhonePwdLogin,
    EmailLogin,
    EmailPwdLogin,
  },
})
export default class Login extends Vue {
  @Action('getUserInfo') private getUserInfo!: () => void;
  private state: string = 'phone-login'; // phone-pwd-login, email-login, email-pwd-login

  @Mutation('save') private save!: (payload: any) => void;

  private changeState(state: string) {
    this.state = state;
  }
  @Provide('validate')
  private validate(rules: any[], tip: string) {
    for ( const { word, pattern, message} of rules) {
      if (!pattern.test(word)) {
        if (tip === 'toast') {
          return this.$toast(message);
        } else {
          return true;
        }
      }
    }
  }
  private async login(params: any) {
    const res = await this.$api.user.login(params);
    localStorage.setItem('userInfo', JSON.stringify(res));
    this.save({
      isLogin2: null,
    })
    await this.getUserInfo();
    this.$router.replace({path: '/'});
  }
}
</script>