<template>
  <el-card class="launch-login">
    <el-row class="launch-login-title">{{title}}</el-row>

    <el-form :model="form" ref="loginRef" :rules="rules">
      <el-form-item prop="username">
        <el-input @keyup.enter.native="enterFun" v-model="form.username" :prefix-icon="User"/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input @keyup.enter.native="enterFun" v-model="form.password" type="password" show-password :prefix-icon="Lock"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" >登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <launch-affix/>
</template>

<script setup>
import { reactive, ref, getCurrentInstance, onMounted } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'

const {proxy} = getCurrentInstance()
const loginApi = proxy.$launchApi.loginApi

let title = ref(import.meta.env.VITE_LOGIN_TITLE?import.meta.env.VITE_LOGIN_TITLE:"Launch 登录" )

let form = ref({})
const loginRef = ref(null)

// 表单校验规则
const rules = reactive({
  username:[
    { required: true, message: '用户名不能为空',trigger: 'change'}
  ],
  password:[
    { required: true, message: '密码不能为空',trigger: 'change'}
  ]
})


function onSubmit() {

  let valid = loginRef.value.validate((valid, fields) => {
    return valid
  })
  valid.then(val => {
    if(!val){
      proxy.$message.error("请输入所有必填项")
      return
    }

    loginApi.login(form.value).then(data => {
      if(data){
        proxy.$message.success("登录成功！")
        localStorage.setItem("token", data.token)
        localStorage.setItem("launchUser", JSON.stringify(data.user))
        proxy.$router.push("/main/home")
      }
    })
  })


}

// 键盘确定事件
function enterFun(e){
  onSubmit()
}

onMounted(() => {


})


</script>

<style scoped>
.launch-login{
  width: var(--launch-login-w);
  margin-left: calc(calc(100vw - var(--launch-login-w)) / 2);
  margin-top: 30vh;

}
.launch-login-title {
  font-size: var(--launch-login-font-size);
  color: var(--launch-font-color);
  margin-bottom: 25px;
}
</style>