<template>
  <div class="login">
    <div class="form-box">
      <div class="login-text">
        <img src="@/assets/image/titleIcon.png" alt="" />
      </div>
      <el-form ref="form" :model="form" :rules="loginRules">
        <el-form-item prop="account">
          <el-input
            maxlength="11"
            v-model.trim="form.account"
            prefix-icon="el-icon-user"
            placeholder="请输入账号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            v-model="form.password"
            show-password
            @keyup.enter.native="loginFun('form')"
          ></el-input>
        </el-form-item>
        <el-button type="primary" class="loginButton" @click="loginFun('form')"
          >登录
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/login'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value == '') {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    return {
      form: {
        account: '',
        password: ''
      },
      loginRules: {
        account: [{ required: true, trigger: 'blur', message: '账号不能为空' }],
        password: [{ required: true, trigger: 'blur', validator: validatePass }]
      }
    }
  },
  mounted() {
    this.clearRouter()
  },
  methods: {
    ...mapMutations({
      clearRouter: 'permission/ClEAR_LIST'
    }),
    loginFun(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = {
            account: this.form.account,
            password: this.form.password
          }
          login(params).then(res => {
            localStorage.setItem('Token', res.data.token)
            localStorage.setItem('userInfo', JSON.stringify(res.data))
            this.$store.commit('getLoginReturnInformation', res.data)
            sessionStorage.setItem('currentPage', '/index')
            this.$router.push('/index')
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import 'index.less';
</style>
