<template>
  <div class="login-page">
    <div class="login-card">
      <h2 class="login-title">CNC机床数据采集系统</h2>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="0" @submit.prevent="handleLogin">
        <el-form-item prop="username">
          <!-- 用户名输入，限制最大输入长度为50字符 -->
          <el-input v-model="form.username" placeholder="用户名" prefix-icon="User" size="large" clearable maxlength="50" />
        </el-form-item>
        <el-form-item prop="password">
          <!-- 密码输入，限制最大输入长度为50字符 -->
          <el-input v-model="form.password" type="password" placeholder="密码" prefix-icon="Lock" size="large" show-password clearable maxlength="50" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.rememberMe">记住我</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="large" :loading="loading" style="width: 100%" native-type="submit">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/utils/request'
import type { ApiResponse } from '@/types'

const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const loading = ref(false)

const form = reactive({
  username: '',
  password: '',
  rememberMe: false,
})

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

const handleLogin = async () => {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  loading.value = true
  try {
    const res: ApiResponse<{ token: string }> = await request.post('/admin/login', {
      username: form.username,
      password: form.password,
      rememberMe: form.rememberMe,
    })
    localStorage.setItem('token', res.data.token)
    ElMessage.success('登录成功')
    const redirect = (route.query.redirect as string) || (route.path.startsWith('/mock') ? '/mock/dashboard' : '/dashboard')
    router.push(redirect)
  } catch {
    // 错误已在拦截器中处理
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.login-page {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  .login-card {
    width: 400px;
    padding: 40px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);

    .login-title {
      text-align: center;
      margin-bottom: 30px;
      color: #303133;
      font-size: 22px;
    }
  }
}
</style>
