<template>
	<div class="auth-container">
		<div class="tech-decoration">
			<div class="tech-circle"></div>
			<div class="tech-circle"></div>
			<div class="tech-circle"></div>
		</div>

		<div class="auth-card">
			<div class="auth-header">
				<h1 class="auth-title">欢迎回来</h1>
				<p class="auth-subtitle">登录您的账户继续探索科技世界</p>
			</div>

			<a-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="auth-form" @finish="handleLogin" layout="vertical">
				<a-form-item name="username">
					<a-input v-model:value="loginForm.username" placeholder="请输入用户名/邮箱" size="large">
						<template #prefix>
							<UserOutlined />
						</template>
					</a-input>
				</a-form-item>

				<a-form-item name="password">
					<a-input-password v-model:value="loginForm.password" placeholder="请输入密码" size="large" @pressEnter="handleLogin">
						<template #prefix>
							<LockOutlined />
						</template>
					</a-input-password>
				</a-form-item>

				<div class="auth-links">
					<a-checkbox v-model:checked="loginForm.rememberMe" class="remember-me"> 记住我 </a-checkbox>
					<router-link to="/reset-password" class="forgot-password"> 忘记密码？ </router-link>
				</div>

				<a-form-item>
					<a-button type="primary" :loading="loading" size="large" html-type="submit" block>
						{{ loading ? '登录中...' : '登录' }}
					</a-button>
				</a-form-item>
			</a-form>

			<div class="auth-footer">
				<p class="auth-footer-text">
					还没有账户？
					<router-link to="/userRegister" class="auth-link"> 立即注册 </router-link>
				</p>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/modules/user'
import { useDictionaryStore } from '@/stores/modules/dictionary'
import auth from '@/api/auth'
import config from '@/config'
import '@/assets/style/auth.scss'

defineOptions({
	name: 'LoginPage',
})

const router = useRouter()
const route = useRoute()
const loginFormRef = ref(null)
const loading = ref(false)

const userStore = useUserStore()
const dictionaryStore = useDictionaryStore()

// Login form data
const loginForm = reactive({
	username: '',
	password: '',
	rememberMe: false,
})

// Form validation rules
const loginRules = {
	username: [
		{ required: true, message: '请输入用户名或邮箱' },
		{ min: 3, max: 50, message: '长度在 3 到 50 个字符' },
	],
	password: [
		{ required: true, message: '请输入密码' },
		{ min: 6, message: '密码长度不能少于 6 位' },
	],
}

// Handle login
const handleLogin = async () => {
	if (!loginFormRef.value) return

	try {
		// Validate form
		await loginFormRef.value.validate()
		loading.value = true

		// 1. Call login API
		const loginResponse = await auth.login.post({
			username: loginForm.username,
			password: loginForm.password,
		})

		// Check if login was successful
		if (loginResponse.code !== 200) {
			throw new Error(loginResponse.message || '登录失败')
		}

		const loginData = loginResponse.data

		// 2. Store token persistently (接口返回的是 token 字段)
		if (loginData.token) {
			userStore.setToken(loginData.token)
		}

		// Store user information if available (登录接口已返回用户信息)
		if (loginData.user) {
			userStore.setUserInfo(loginData.user)
		}

		// 3. Store menu and permissions from login response
		// 根据接口文档，登录接口已返回 menu 和 permissions 数据
		if (loginData.menu) {
			userStore.setMenu(loginData.menu)
		}

		if (loginData.permissions) {
			userStore.setPermissions(loginData.permissions)
		}

		// 4. Load dictionary data (缓存字典数据)
		dictionaryStore.loadAllDictionaries().catch((error) => {
			console.error('加载字典数据失败:', error)
		})

		// Success message
		message.success('登录成功！')

		// Redirect to dashboard or redirect parameter
		setTimeout(() => {
			// Get redirect from query parameter
			const redirect = route.query.redirect

			if (redirect) {
				// If there's a redirect parameter, go there
				router.push(redirect)
			} else {
				// Otherwise, go to configured dashboard URL
				router.push(config.DASHBOARD_URL)
			}
		}, 500)
	} catch (error) {
		// Clear user data on login failure
		userStore.logout()

		// Show error message
		const errorMsg = error.response?.data?.msg || error.msg || error.message || '登录失败，请检查用户名和密码'
		message.error(errorMsg)
	} finally {
		loading.value = false
	}
}
</script>
