layui.use(['form', 'layer'], function(){
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.$;
    
    // 检查用户是否已登录
    function checkIfLoggedIn() {
        const token = localStorage.getItem('token');
        if (token) {
            window.location.href = '/';
        }
    }

    // 页面加载时检查登录状态
    checkIfLoggedIn();

    // 加载验证码
    function loadCaptcha() {
        fetch('/api/captcha')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.error) {
                    layer.msg(data.error);
                    return;
                }
                // 确保图片数据正确加载
                if (data.imageBase64) {
                    $('#captchaImg').attr('src', 'data:image/png;base64,' + data.imageBase64);
                    $('input[name=captchaId]').val(data.captchaId);
                } else {
                    throw new Error('验证码图片数据无效');
                }
            })
            .catch(error => {
                layer.msg('获取验证码失败：' + error.message);
                // 设置一个默认的错误图片
                $('#captchaImg').attr('src', '/static/images/captcha-error.png');
            });
    }

    // 页面加载时获取验证码
    loadCaptcha();

    // 点击验证码图片刷新
    $('#captchaImg').on('click', function() {
        loadCaptcha();
    });

    // 登录表单提交
    form.on('submit(login)', function(data){
        var field = data.field;
        
        // 添加验证码验证
        if (!field.captcha) {
            layer.msg('请输入验证码');
            return false;
        }
        
        if (!field.captchaId) {
            layer.msg('验证码已失效，请刷新');
            loadCaptcha();
            return false;
        }
        
        fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: field.username,
                password: field.password,
                captcha: field.captcha,
                captchaId: field.captchaId
            })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(result => {
            if (result.error) {
                layer.msg(result.error);
                loadCaptcha(); // 刷新验证码
                return;
            }
            // 确保 token 被正确设置
            document.cookie = `token=${result.token}; path=/; secure; samesite=strict`;
            localStorage.setItem('token', result.token);
            window.location.href = '/';
        })
        .catch(error => {
            layer.msg('登录失败：' + error.message);
            loadCaptcha(); // 刷新验证码
        });
        
        return false;
    });
    
    // 注册账号点击事件
    $('.register').on('click', function(){
        layer.open({
            type: 2,
            title: '注册账号',
            area: ['500px', '400px'],
            content: '/register.html'
        });
    });
    
    // 忘记密码点击事件
    $('.forget-pwd').on('click', function(){
        layer.open({
            type: 2,
            title: '重置密码',
            area: ['500px', '300px'],
            content: '/reset-password.html'
        });
    });

}); 