<template>
  <div class="simple-login-container">
    <el-card style="width: 350px;" id="loginCard">
      <template #header>
        <div style="text-align: center; font-weight: bold;">系统登录</div>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginRef">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%;"
            @click="handleLogin"
          >
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import service from '../api/service.ts'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const loginRef = ref<FormInstance>()

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const handleLogin = async () => {
  if (!loginRef.value) return

  await loginRef.value.validate((valid) => {
    if (valid) {
     service.post("/login",loginForm).then(res=>{
       console.log(res)
       if (res.code == 0){
       localStorage.setItem("token",res.data.token)
         ElMessage.success("登录成功，3秒后跳转")
         setTimeout(()=>{
           router.push("/")
         },3000)
       }
       else if (res.code== 450) {
         ElMessage.error("密码错误")
       }
       else if (res.code==451){
         ElMessage.error("用户名不存在")
       }
       else {
         ElMessage.error("未知错误")
       }
     })
    }
  })
}
</script>

<style scoped>
/* 针对所有 Element Plus 图标，强行锁死大小，无视任何外部干扰 */
:deep(.el-input__icon),
:deep(.el-icon),
:deep(svg) {
  width: 1em !important;
  height: 1em !important;
  font-size: 16px !important; /* 眼睛图标的标准大小 */
}

/* 针对密码框那只“大眼睛”的专属镇压 */
:deep(.el-input__password) {
  width: 25px !important;
  height: 25px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

/* 确保输入框本身不会被撑大 */
:deep(.el-input__wrapper) {
  padding: 1px 11px !important;
}

#loginCard{
  position: absolute;
  left: 40%;
  height: 60%;
  align-items: center;
}
</style>
