<template>
  <ElForm :model="model" :size="loginVm.size" class="x-login-password" @submit.native.prevent>
    <ElFormItem prop="username">
      <ElInput v-model="model.username"
               ref="username"
               autocomplete="on"
               maxlength="30"
               @change="handleNameChange"
               :placeholder="texts.usernamePlaceholder"></ElInput>
    </ElFormItem>
    <ElFormItem prop="password">
      <PasswordInput v-model="model.password"
                     ref="password"
                     autocomplete="on"
                     :placeholder="texts.passwordPlaceholder"></PasswordInput>
    </ElFormItem>
    <ElFormItem v-if="loginVm.supportResetPassword" class="x-login-password__forget">
      <ElButton type="text" @click="handleForget">{{texts.forgetPassword}}</ElButton>
    </ElFormItem>
    <ElFormItem v-else>
      <ElInput class="x-login__holder"></ElInput>
    </ElFormItem>
    <ElFormItem>
      <ElButton @click="handleLogin"
                :loading="loading"
                type="primary"
                native-type="submit"
                class="x-login-password__submit">
        {{texts.submitButtonText}}
      </ElButton>
    </ElFormItem>
  </ElForm>
</template>

<script>
import {
  Form as ElForm,
  FormItem as ElFormItem,
  Input as ElInput,
  Button as ElButton,
  Notification
} from 'element-ui';
import PasswordInput from './PasswordInput';

export default {
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    PasswordInput
  },
  inject: ['loginVm'],
  data() {
    return {
      model: {
        loginType: 'password',
        username: '',
        password: ''
      }
    };
  },
  computed: {
    loading() {
      return this.loginVm.loading;
    },
    texts() {
      return this.loginVm.texts;
    }
  },
  watch: {
    'loginVm.username': {
      immediate: true,
      handler(val) {
        this.model.username = val;
      }
    }
  },
  methods: {
    handleNameChange(val) {
      this.loginVm.username = val;
    },
    handleForget() {
      this.loginVm.showForgetPassword = true;
    },
    validate() {
      const {username, password} = this.model;
      if (!username) {
        Notification({
          message: '请输入您的手机号或用户名',
          type: 'warning'
        });
        this.$refs.username.focus();
        return false;
      }
      if (!password && this.currentTab === 'password') {
        Notification({
          message: '请输入密码',
          type: 'warning'
        });
        this.$refs.password.focus();
        return false;
      }
      return true;
    },
    handleLogin() {
      if (!this.validate()) return;
      this.loginVm.userLogin(this.model);
    }
  }
};
</script>
