<template>
  <div class="bac">
    <div class="loginBox">
      <p>账号密码登陆</p>
      <el-space direction="vertical" :size="30">
        <el-input v-model="subform.id" placeholder="学号" clearable style="width: 240px;height: 40px;"/>
        <el-input v-model="subform.password" placeholder="密码" type="password" style="width: 240px;height: 40px;"/>
      </el-space>
      <el-button type="primary" @click="login()" @keyup.enter="login()" style="width: 240px;height: 40px;font-size: 14px">登陆</el-button>
    </div>
  </div>
</template>

<script>
import { Avatar, Key } from '@element-plus/icons-vue'
import {ElNotification} from "element-plus";
export default {
  name: 'Login',
  data(){
    return{
      subform:{
        id:'',
        password:'',
      }
    }
  },
  mounted() {
    document.addEventListener('keydown', this.handleEnterKey);
  },
  methods:{
    handleEnterKey(){
      // 检查是否按下回车键（keyCode为13）
      if (event.keyCode === 13) {
        // 触发按钮的点击事件
        this.login();
      }
    },
    login(){
      this.$http({
        method:'post',
        url:'/login',
        data:this.subform
      }).then(res =>{
        if(res.data.code!==200){
          ElNotification({
            title: '登陆失败',
            message: res.data.msg,
            type: 'warning',
          })
        }else if (res.data.code === 200){
          ElNotification({
            title: '登陆成功',
            message: '你好，' + res.data.username,
            type: 'success',
          })

          //保存信息
          window.sessionStorage.setItem('role',res.data.role);
          window.sessionStorage.setItem('username',res.data.username);
          window.sessionStorage.setItem('userId', res.data.id.toString());
          window.sessionStorage.setItem('token', res.data.token);

          this.$router.push('/Home');
        }else {
          ElNotification({
            title: '服务器错误',
            message: '工具人QQ：3231977651',
            type: 'error',
          })
        }
      })
    }

  },
  components:{
    Avatar,
    Key
  }

}
</script>

<style scoped>
.bac{
  width: 1440px;
  height: 900px;
  background: url("../assets/img/loginBac.png");
}

.loginBox{
  width: 250px;
  height: 320px;
  position: absolute;
  left: 62%;
  top: 320px;
}
</style>
