<template>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <h1 class="login-title">泰豪电源 AI 数智化平台</h1>
                <p class="login-subtitle">Urban Lifeline Platform</p>
            </div>

            <el-form
                ref="loginFormRef"
                :model="loginForm"
                :rules="loginRules"
                class="login-form"
                @submit.prevent="handleLogin"
            >
                <el-form-item prop="username">
                    <el-input
                        v-model="loginForm.username"
                        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
                        @keyup.enter="handleLogin"
                    />
                </el-form-item>

                <el-form-item>
                    <el-checkbox v-model="loginForm.rememberMe">
                        记住我
                    </el-checkbox>
                </el-form-item>

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

            <div class="login-footer">
                <span class="footer-link">忘记密码？</span>
                <span class="footer-divider">|</span>
                <span class="footer-link">注册账号</span>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { LoginParam } from 'shared/types'
import { authAPI } from 'shared/api/auth'
import { TokenManager } from 'shared/api'
import { getAesInstance } from 'shared/utils'
import { resetDynamicRoutes } from '@/router'

// 路由
const router = useRouter()

// 表单引用
const loginFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 登录表单
const loginForm = reactive({
    username: '',
    password: '',
    rememberMe: false
})

// 表单验证规则
const loginRules: FormRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码至少6个字符', trigger: 'blur' }
    ]
}

/**
 * 处理登录
 */
async function handleLogin() {
    if (!loginFormRef.value) return

    try {
        // 1. 表单验证
        await loginFormRef.value.validate()

        // 2. 显示加载状态
        loading.value = true

        // 3. 获取 AES 加密实例
        const aes = getAesInstance()

        // 4. 加密密码
        const encryptedPassword = await aes.encryptPassword(loginForm.password)

        // 5. 构建登录参数
        const loginParam: LoginParam = {
            username: loginForm.username,
            password: encryptedPassword,  // 使用加密后的密码
            loginType: 'password'
        }

        // 6. 调用登录接口
        const response = await authAPI.login(loginParam)

        // 7. 检查登录结果
        if (response.success && response.data) {
            const loginData = response.data

            // 8. 保存 Token（只用 TokenManager，避免格式不一致）
            if (loginData.token) {
                TokenManager.setToken(loginData.token, loginForm.rememberMe)
            }

            // 9. 保存 LoginDomain 到 LocalStorage
            if (loginData) {
                localStorage.setItem('loginDomain', JSON.stringify(loginData))
                localStorage.setItem('views', JSON.stringify(loginData.userViews))
            }

            // 10. 保存用户信息（用于路由守卫检查）
            if (loginData.user) {
                localStorage.setItem('userInfo', JSON.stringify(loginData.user))
            } else if (loginData.userInfo) {
                localStorage.setItem('userInfo', JSON.stringify(loginData.userInfo))
            }

            // 11. 重置动态路由加载状态（让路由守卫重新加载）
            resetDynamicRoutes()

            // 12. 显示成功消息
            ElMessage.success('登录成功！')

            // 13. 跳转到首页或重定向地址
            const redirect = router.currentRoute.value.query.redirect as string
            router.push(redirect || '/')
        } else {
            // 登录失败
            ElMessage.error(response.message || '登录失败，请检查用户名和密码')
        }
    } catch (error: any) {
        console.error('登录失败:', error)
        
        // 显示错误消息
        if (error.response) {
            // HTTP 错误
            ElMessage.error(error.response.data?.message || '登录失败，请稍后重试')
        } else if (error.message) {
            // 其他错误
            ElMessage.error(error.message)
        } else {
            ElMessage.error('登录失败，请检查网络连接')
        }
    } finally {
        // 隐藏加载状态
        loading.value = false
    }
}
</script>

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

.login-card {
    width: 100%;
    max-width: 420px;
    padding: 40px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.login-header {
    text-align: center;
    margin-bottom: 40px;
}

.login-title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
}

.login-subtitle {
    font-size: 14px;
    color: #999;
}

.login-form {
    :deep(.el-form-item) {
        margin-bottom: 24px;
    }

    :deep(.el-input__wrapper) {
        padding: 12px 16px;
    }
}

.login-button {
    width: 100%;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
    border-radius: 8px;
}

.login-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 24px;
    font-size: 14px;
    color: #999;
}

.footer-link {
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
        color: var(--el-color-primary);
    }
}

.footer-divider {
    margin: 0 12px;
}

// 响应式设计
@media (max-width: 480px) {
    .login-card {
        padding: 30px 20px;
    }

    .login-title {
        font-size: 20px;
    }
}
</style>