<template>
  <div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100">
    <div class="max-w-md w-full mx-4">
      <!-- 登录卡片 -->
      <div class="bg-white rounded-2xl shadow-xl p-8">
        <!-- 标题 -->
        <div class="text-center mb-8">
          <h1 class="text-3xl font-bold text-gray-800 mb-2">腾讯广告自动化系统</h1>
          <p class="text-gray-500">请使用工号和密码登录</p>
        </div>

        <!-- 登录表单 -->
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          @keyup.enter="handleLogin"
        >
          <el-form-item prop="jobNumber">
            <el-input
              v-model="loginForm.jobNumber"
              placeholder="请输入工号"
              size="large"
              prefix-icon="User"
              clearable
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              @click="handleLogin"
              class="w-full"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 提示信息 -->
        <div class="mt-4 text-center text-sm text-gray-500">
          <p>默认密码：123456</p>
          <p class="mt-1">首次登录后请及时修改密码</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Login'
})

import { ref, reactive } from 'vue'
import { onMounted } from 'vue'

import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '@/api/user'

const router = useRouter()

// 表单数据
const loginForm = reactive({
  jobNumber: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  jobNumber: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const loginFormRef = ref(null)
const loading = ref(false)

onMounted(() => {
   if (import.meta.env.MODE === 'development') {
     loginForm.jobNumber = '12458'
     loginForm.password = '123qwe!@#'
   }
})

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return

    loading.value = true
    try {
      const res = await login({
        jobNumber: loginForm.jobNumber,
        password: loginForm.password
      })

      if (res.success) {
        const { user, loginToken, isAuthenticated, needAuthentication, isDefaultPassword } = res.data

        // 保存用户信息和登录令牌到 localStorage
        localStorage.setItem('userInfo', JSON.stringify(user))
        localStorage.setItem('jobNumber', user.jobNumber)
        localStorage.setItem('loginToken', loginToken)
        localStorage.setItem('needAuthentication', needAuthentication)
        localStorage.setItem('isDefaultPassword', isDefaultPassword)

        ElMessage.success(res.message || '登录成功')

        // 登录成功后直接跳转到个人中心
        if (isAuthenticated) {
          router.push('/dashboard')
        } else {
          router.push('/profile')
        }
      } else {
        ElMessage.error(res.message || '登录失败')
      }
    } catch (error) {   
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请检查网络连接')
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped>
/* 自定义样式 */
</style>
