$(document).ready(function() {
    const API_BASE_URL = 'http://localhost:3000/api';

    // 检查是否已登录
    const token = localStorage.getItem('adminToken');
    if (token) {
        $.ajax({
            url: `${API_BASE_URL}/admin/profile`,
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`
            },
            success: function() {
                window.location.href = 'index.html';
            },
            error: function() {
                localStorage.removeItem('adminToken');
            }
        });
    }

    // 处理登录表单提交
    $('#loginForm').submit(function(e) {
        e.preventDefault();
        
        const loginData = {
            username: $('#username').val().trim(),
            password: $('#password').val().trim()
        };

        if (!loginData.username || !loginData.password) {
            $('#errorAlert').text('请填写用户名和密码').show();
            return;
        }

        // 显示加载状态
        $('#loginBtn').prop('disabled', true);
        $('#loginBtn .spinner-border').removeClass('d-none');
        $('#errorAlert').hide();

        // 发送登录请求
        $.ajax({
            url: `${API_BASE_URL}/admin/login`,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                admin_name: loginData.username || null,
                admin_password: loginData.password || null,
                role: 'admin' // 添加角色标识
            }),
            success: function(response) {
                console.log('Login response:', response); // 添加响应日志
                if (response && response.token) {
                    localStorage.setItem('adminToken', response.token);
                    window.location.href = 'index.html';
                } else {
                    $('#errorAlert').text('登录失败：未获取到token').show();
                }
            },
            error: function(xhr) {
                let errorMessage = '登录失败';
                if (xhr.responseJSON) {
                    console.error('Server error:', xhr.responseJSON);
                    errorMessage += '：' + (xhr.responseJSON.message || xhr.responseJSON.error || '未知错误');
                }
                $('#errorAlert').text(errorMessage).show();
            }
        });
    });
});