<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>系统设置</title>
    <link rel="stylesheet" href="{{ asset('CmsProUi/component/pear/css/pear.css') }}">
    <link rel="stylesheet" href="{{ asset('CmsProUi/font-awesome/4.7.0/css/font-awesome.min.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/admin.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/variables.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/reset.css') }}">
    <style>
    .layui-form-item { display: flex; align-items: flex-start; margin-bottom: 15px; }
    .layui-form-label { width: 140px; flex-shrink: 0; padding: 9px 15px 0 0; text-align: right; box-sizing: border-box; float: none; }
    .layui-input-block { margin-left: 0 !important; flex: 1; min-width: 0; float: none; }
    .layui-input, .layui-textarea { display: unset; }
    .setting-card { background: #fff; border-radius: 6px; padding: 20px 24px 10px; }
    .setting-card .card-title { font-size: 15px; font-weight: 600; margin-bottom: 16px; padding-bottom: 12px; border-bottom: 1px solid #f0f0f0; }
    .form-tips { font-size: 12px; color: #999; margin-top: 4px; line-height: 1.5; }
    .image-preview { max-width: 200px; max-height: 80px; margin-top: 6px; border: 1px solid #e6e6e6; border-radius: 4px; display: none; }
    .image-input-wrap { display: flex; align-items: center; gap: 8px; }
    .image-input-wrap .layui-input { flex: 1; }
</style>
    @include('admin.partials.permission-script')
</head>
<body>
<div class="pear-container" style="padding: 12px;">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="setting-card">
                <form class="layui-form" lay-filter="settingForm">
                    <div class="layui-tab layui-tab-brief" lay-filter="settingTab">
                        <ul class="layui-tab-title" id="tabTitles"></ul>
                        <div class="layui-tab-content" id="tabContent"></div>
                    </div>
                    <div class="layui-form-item" style="margin-top: 20px;">
                        <div class="layui-input-block">
                            <button type="submit" class="layui-btn" lay-submit lay-filter="saveSetting"><i class="fa fa-check"></i> 提交</button>
                            <button type="reset" class="layui-btn layui-btn-primary"><i class="fa fa-refresh"></i> 重置</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
<script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
<script>
    layui.use(['form', 'jquery', 'layer'], function() {
        var form = layui.form;
        var $ = layui.jquery;
        var layer = layui.layer;

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            statusCode: {
                401: function() {
                    layer.msg('登录已过期，请重新登录', {icon: 2, time: 1500}, function() {
                        window.location.href = '/admin/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                    });
                }
            }
        });

        var groups = [];

        loadConfig();

        function loadConfig() {
            var loading = layer.load(2);
            $.get('/api/admin/config-groups', function(res) {
                layer.close(loading);
                if (res.code !== 0) {
                    layer.msg('加载配置失败', { icon: 2 });
                    return;
                }
                groups = res.data || [];
                renderTabs();
            }).fail(function() {
                layer.close(loading);
                layer.msg('请求失败', { icon: 2 });
            });
        }

        function renderTabs() {
            if (groups.length === 0) {
                $('#tabTitles').html('<li class="layui-this">暂无配置</li>');
                $('#tabContent').html('<div class="layui-tab-item layui-show" style="padding:40px;text-align:center;color:#999;">暂无配置分组，请先在系统配置中添加</div>');
                return;
            }

            var titleHtml = '';
            var contentHtml = '';

            for (var i = 0; i < groups.length; i++) {
                var g = groups[i];
                var items = g.items || [];
                var isActive = i === 0;

                titleHtml += '<li' + (isActive ? ' class="layui-this"' : '') + '>' + g.name + '</li>';

                contentHtml += '<div class="layui-tab-item' + (isActive ? ' layui-show' : '') + '">';
                if (items.length > 0) {
                    for (var j = 0; j < items.length; j++) {
                        contentHtml += renderItem(items[j]);
                    }
                } else {
                    contentHtml += '<div style="padding:30px;text-align:center;color:#999;">该分组暂无配置项</div>';
                }
                contentHtml += '</div>';
            }

            $('#tabTitles').html(titleHtml);
            $('#tabContent').html(contentHtml);
            form.render();

            bindImagePreviews();
        }

        function renderItem(item) {
            var val = item.value || '';
            var tips = item.tips ? '<div class="form-tips">' + item.tips + '</div>' : '';
            var html = '<div class="layui-form-item">';
            html += '<label class="layui-form-label">' + item.name + '</label>';
            html += '<div class="layui-input-block">';

            switch (item.type) {
                case 'switch':
                    var checked = val === '1' || val === 'true';
                    html += '<input type="checkbox" name="config_' + item.id + '" lay-skin="switch" lay-text="开启|关闭" ' + (checked ? 'checked' : '') + ' data-id="' + item.id + '" data-type="switch">';
                    break;
                case 'select':
                    var opts = item.options || [];
                    html += '<select name="config_' + item.id + '" data-id="' + item.id + '">';
                    for (var i = 0; i < opts.length; i++) {
                        var opt = opts[i];
                        if (typeof opt === 'object') {
                            html += '<option value="' + opt.value + '"' + (opt.value == val ? ' selected' : '') + '>' + opt.label + '</option>';
                        } else {
                            html += '<option value="' + opt + '"' + (opt == val ? ' selected' : '') + '>' + opt + '</option>';
                        }
                    }
                    html += '</select>';
                    break;
                case 'textarea':
                    html += '<textarea name="config_' + item.id + '" class="layui-textarea" data-id="' + item.id + '">' + val + '</textarea>';
                    break;
                case 'number':
                    html += '<input type="number" name="config_' + item.id + '" value="' + val + '" class="layui-input" data-id="' + item.id + '">';
                    break;
                case 'image':
                    html += '<div class="image-input-wrap">';
                    html += '<input type="text" name="config_' + item.id + '" value="' + val + '" class="layui-input" placeholder="图片URL" data-id="' + item.id + '" data-type="image">';
                    html += '<button type="button" class="layui-btn layui-btn-sm" onclick="chooseImage(' + item.id + ')">选择</button>';
                    html += '</div>';
                    html += '<img class="image-preview" id="preview_' + item.id + '" src="' + val + '">';
                    break;
                default:
                    html += '<input type="text" name="config_' + item.id + '" value="' + val + '" class="layui-input" data-id="' + item.id + '">';
            }

            html += tips;
            html += '</div></div>';
            return html;
        }

        function bindImagePreviews() {
            $('input[data-type="image"]').each(function() {
                var input = $(this);
                var id = input.data('id');
                var preview = $('#preview_' + id);
                if (input.val()) {
                    preview.show();
                }
                input.on('input', function() {
                    if ($(this).val()) {
                        preview.attr('src', $(this).val()).show();
                    } else {
                        preview.hide();
                    }
                });
            });
        }

        form.on('submit(saveSetting)', function(data) {
            var items = [];
            $('form').find('[data-id]').each(function() {
                var id = $(this).data('id');
                var type = $(this).data('type');
                var value;
                if (type === 'switch') {
                    value = $(this).prop('checked') ? '1' : '0';
                } else {
                    value = $(this).val();
                }
                items.push({ id: id, value: value });
            });

            if (items.length === 0) {
                layer.msg('没有需要保存的配置', { icon: 3 });
                return false;
            }

            var loading = layer.load(2);
            $.ajax({
                url: '/api/admin/config-items/batch',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify({ items: items }),
                success: function(res) {
                    layer.close(loading);
                    if (res.code === 0) {
                        layer.msg('保存成功', { icon: 1, time: 1500 });
                    } else {
                        layer.msg(res.message || '保存失败', { icon: 2 });
                    }
                },
                error: function() {
                    layer.close(loading);
                    layer.msg('请求失败', { icon: 2 });
                }
            });
            return false;
        });

        window.chooseImage = function(itemId) {
            layer.open({
                type: 2,
                title: '选择图片',
                area: ['90%', '80%'],
                content: '/admin/attachment?picker=1',
                end: function() {
                    var selectedUrl = sessionStorage.getItem('selectedAttachmentUrl');
                    if (selectedUrl) {
                        $('input[data-id="' + itemId + '"]').val(selectedUrl).trigger('input');
                        sessionStorage.removeItem('selectedAttachmentUrl');
                    }
                }
            });
        };
    });
</script>
</body>
</html>
