layui.use(['form', 'upload', 'layer'], function(){
    var form = layui.form;
    var upload = layui.upload;
    var layer = layui.layer;
    var $ = layui.$;
    
    // 加载当前配置
    fetch('/api/site/settings', {
        credentials: 'include',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
    })
    .then(response => {
        if (response.status === 401) {
            window.location.href = '/login';
            throw new Error('认证失败');
        }
        return response.json();
    })
    .then(data => {
        if (data.error) {
            layer.msg(data.error);
            return;
        }
        console.log(data);
        // 填充表单数据
        form.val('siteSettingsForm', {
            'title': data.title,
            'description': data.description,
            'baseUrl': data.base_url,
            'icp': data.icp,
            'copyright': data.copyright,
            'logo': data.logo,
            'favicon': data.favicon
        });
        
        // 显示当前图片
        if (data.logo) {
            $('#currentLogo').attr('src', data.logo).show();
        }
        if (data.favicon) {
            $('#currentFavicon').attr('src', data.favicon).show();
        }
    })
    .catch(error => {
        layer.msg('加载配置失败：' + error.message);
    });
    
    // 上传Logo
    upload.render({
        elem: '#uploadLogo',
        url: '/api/uploads/site',
        accept: 'images',
        acceptMime: 'image/*',
        field: 'file',
        before: function() {
            layer.load();
        },
        done: function(res) {
            layer.closeAll('loading');
            if (res.error) {
                layer.msg(res.error);
                return;
            }
            $('input[name=logo]').val(res.url);
            $('#currentLogo').attr('src', res.url).show();
            layer.msg('Logo上传成功');
        },
        error: function() {
            layer.closeAll('loading');
            layer.msg('上传失败');
        }
    });
    
    // 上传Favicon
    upload.render({
        elem: '#uploadFavicon',
        url: '/api/uploads/site',
        accept: 'images',
        acceptMime: 'image/*',
        field: 'file',
        before: function() {
            layer.load();
        },
        done: function(res) {
            layer.closeAll('loading');
            if (res.error) {
                layer.msg(res.error);
                return;
            }
            $('input[name=favicon]').val(res.url);
            $('#currentFavicon').attr('src', res.url).show();
            layer.msg('Favicon上传成功');
        },
        error: function() {
            layer.closeAll('loading');
            layer.msg('上传失败');
        }
    });
    
    // 表单提交
    form.on('submit(siteSubmit)', function(data){
        // 转换字段名以匹配后端
        const submitData = {
            title: data.field.title,
            description: data.field.description,
            base_url: data.field.baseUrl,
            icp: data.field.icp,
            copyright: data.field.copyright,
            logo: data.field.logo,
            favicon: data.field.favicon
        };

        fetch('/api/site/settings', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('token')
            },
            credentials: 'include',
            body: JSON.stringify(submitData)
        })
        .then(response => {
            if (response.status === 401) {
                window.location.href = '/login';
                throw new Error('认证失败');
            }
            return response.json();
        })
        .then(result => {
            if (result.error) {
                layer.msg(result.error);
                return;
            }
            layer.msg('保存成功');
            // 刷新父页面
            parent.window.location.reload();
        })
        .catch(error => {
            layer.msg('保存失败：' + error.message);
        });
        
        return false;
    });
}); 