layui.use(['form', 'layer'], function(){
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.$;
    
    // 加载验证码
    var captchaId = '';
    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);
                    captchaId = data.captchaId;
                } else {
                    throw new Error('验证码图片数据无效');
                }
            })
            .catch(error => {
                layer.msg('获取验证码失败：' + error.message);
                // 设置一个默认的错误图片
                $('#captchaImg').attr('src', '/static/images/captcha-error.png');
            });
    }
    loadCaptcha();

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

    // 表单提交
    form.on('submit(login)', function(data){
        data.field.captchaId = captchaId;
        
        fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data.field)
        })
        .then(response => response.json())
        .then(result => {
            if(result.error) {
                layer.msg(result.error);
                loadCaptcha();
                return;
            }
            // 保存token到localStorage
            localStorage.setItem('token', result.data.token);
            localStorage.setItem('user', JSON.stringify(result.data.user));
            
            // 跳转到首页
            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'
        });
    });

}); 