<!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>
    .config-wrap { display: flex; gap: 12px; height: calc(100vh - 60px); }
    .group-panel { width: 220px; min-width: 220px; background: #fff; border-radius: 6px; display: flex; flex-direction: column; }
    .group-panel .panel-header { padding: 12px 15px; border-bottom: 1px solid #f0f0f0; font-weight: 600; font-size: 14px; display: flex; justify-content: space-between; align-items: center; }
    .group-panel .panel-header .add-btn { cursor: pointer; color: #16b777; font-size: 18px; }
    .group-panel .panel-body { flex: 1; overflow-y: auto; padding: 8px 0; }
    .group-item { padding: 9px 15px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: #333; transition: background .2s; }
    .group-item:hover { background: #f6f6f6; }
    .group-item.active { background: #e8f5e9; color: #16b777; font-weight: 500; }
    .group-item .group-name { display: flex; align-items: center; gap: 6px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .group-item .group-name i { font-size: 14px; color: #999; }
    .group-item .group-ops { display: none; gap: 4px; }
    .group-item:hover .group-ops { display: flex; }
    .group-item .group-ops i { font-size: 13px; color: #999; padding: 2px; }
    .group-item .group-ops i:hover { color: #16b777; }
    .content-panel { flex: 1; display: flex; flex-direction: column; gap: 12px; min-width: 0; overflow-y: auto; }
    .config-form-card { background: #fff; border-radius: 6px; padding: 20px; }
    .config-form-card .card-title { font-size: 15px; font-weight: 600; margin-bottom: 20px; padding-bottom: 12px; border-bottom: 1px solid #f0f0f0; display: flex; justify-content: space-between; align-items: center; }
    .config-row { display: flex; align-items: flex-start; margin-bottom: 18px; }
    .config-row .config-label { width: 140px; min-width: 140px; text-align: right; padding-right: 12px; line-height: 38px; font-size: 14px; color: #333; }
    .config-row .config-label .required { color: #ff5722; margin-right: 2px; }
    .config-row .config-label .tips { display: block; font-size: 12px; color: #999; line-height: 1.4; margin-top: -2px; }
    .config-row .config-input { flex: 1; max-width: 500px; }
    .config-row .config-input .layui-input { width: 100%; }
    .config-row .config-input textarea { width: 100%; min-height: 80px; padding: 8px 10px; border: 1px solid #e6e6e6; border-radius: 2px; font-size: 14px; resize: vertical; }
    .config-row .config-input textarea:focus { border-color: #16b777; }
    .config-actions { text-align: center; padding: 20px 0 10px; border-top: 1px solid #f0f0f0; margin-top: 10px; }
    .item-manage-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
    .item-manage-bar .title { font-size: 14px; font-weight: 600; color: #333; }
    .type-tag { display: inline-block; padding: 1px 6px; border-radius: 3px; font-size: 12px; }
    .type-tag.text { background: #e8f5e9; color: #4caf50; }
    .type-tag.number { background: #e3f2fd; color: #2196f3; }
    .type-tag.switch { background: #fff3e0; color: #ff9800; }
    .type-tag.select { background: #f3e5f5; color: #9c27b0; }
    .type-tag.textarea { background: #e0f2f1; color: #009688; }
    .type-tag.image { background: #fce4ec; color: #e91e63; }
.type-tag.password { background: #efebe9; color: #795548; }
    .empty-tip { text-align: center; color: #999; padding: 60px 0; font-size: 14px; }
</style>
    @include('admin.partials.permission-script')
</head>
<body>
<div class="pear-container" style="padding: 12px;">
    <div class="config-wrap">
        <div class="group-panel">
            <div class="panel-header">
                <span>配置分组</span>
                <i class="layui-icon layui-icon-add-1 add-btn" id="addGroupBtn" title="新增分组"></i>
            </div>
            <div class="panel-body" id="groupList"></div>
        </div>

        <div class="content-panel" id="contentPanel">
            <div class="empty-tip"><i class="layui-icon layui-icon-set" style="font-size:48px; color:#16b777; display:block; margin-bottom:15px;"></i>请选择左侧配置分组</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 = [];
        var currentGroupId = null;

        var API = {
            groups: '/api/admin/config-groups',
            items: '/api/admin/config-items',
            batch: '/api/admin/config-items/batch'
        };

        function ajaxRequest(opts) {
            $.ajax({
                url: opts.url,
                type: opts.method || 'GET',
                dataType: 'json',
                contentType: opts.contentType || 'application/json',
                data: opts.data,
                success: function(res) {
                    if (res.code === 0) {
                        if (opts.onSuccess) opts.onSuccess(res);
                    } else {
                        layer.msg(res.message || '操作失败', { icon: 2 });
                    }
                },
                error: function() { layer.msg('请求失败', { icon: 2 }); }
            });
        }

        function confirmDelete(msg, url, onDone) {
            layer.confirm(msg, { icon: 3, title: '操作提示' }, function(index) {
                layer.close(index);
                ajaxRequest({ url: url, method: 'DELETE', onSuccess: onDone });
            });
        }

        function buildFormItem(label, inputHtml) {
            return '<div class="layui-form-item"><label class="layui-form-label">' + label + '</label>'
                + '<div class="layui-input-block">' + inputHtml + '</div></div>';
        }

        function buildFormFooter(cancelId, submitId) {
            return '<div class="layui-form-item" style="text-align:right;margin-top:16px;">'
                + '<button type="button" class="layui-btn layui-btn-primary" id="' + cancelId + '">取消</button> '
                + '<button type="button" class="layui-btn" id="' + submitId + '">确定</button></div>';
        }

        function bindFormButtons(layero, cancelId, submitId, onSubmit) {
            form.render();
            layero.find('#' + cancelId).on('click', function() { layer.closeAll(); });
            layero.find('#' + submitId).on('click', onSubmit);
        }

        loadGroups();

        function loadGroups() {
            $.get(API.groups, function(res) {
                if (res.code !== 0) return;
                groups = res.data || [];
                renderGroupList();
                if (!currentGroupId && groups.length > 0) {
                    currentGroupId = groups[0].id;
                    $('.group-item').first().addClass('active');
                    renderContent();
                } else if (currentGroupId) {
                    renderContent();
                }
            });
        }

        function renderGroupList() {
            var html = '';
            for (var i = 0; i < groups.length; i++) {
                var g = groups[i];
                html += '<div class="group-item' + (currentGroupId === g.id ? ' active' : '') + '" data-id="' + g.id + '">'
                    + '<div class="group-name"><i class="fa fa-cog"></i> ' + g.name + '</div>'
                    + '<div class="group-ops">'
                    + '<i class="fa fa-edit" data-action="edit" data-id="' + g.id + '" data-name="' + g.name + '" data-code="' + g.code + '" data-sort="' + g.sort + '" title="编辑"></i>'
                    + '<i class="fa fa-trash-o" data-action="del" data-id="' + g.id + '" data-name="' + g.name + '" title="删除"></i>'
                    + '</div></div>';
            }
            $('#groupList').html(html);
            bindGroupEvents();
            // 根据权限隐藏操作元素
            if (window.hasPermission && !window.hasPermission('admin.config-group.update')) {
                $('.group-ops i[data-action=edit]').hide();
            }
            if (window.hasPermission && !window.hasPermission('admin.config-group.destroy')) {
                $('.group-ops i[data-action=del]').hide();
            }
            if (window.hasPermission && !window.hasPermission('admin.config-group.store')) {
                $('#addGroupBtn').hide();
            }
        }

        function bindGroupEvents() {
            $('.group-item').on('click', function(e) {
                if ($(e.target).closest('.group-ops').length) return;
                currentGroupId = $(this).data('id');
                $('.group-item').removeClass('active');
                $(this).addClass('active');
                renderContent();
            });
            $('.group-ops i').on('click', function(e) {
                e.stopPropagation();
                var action = $(this).data('action');
                var id = $(this).data('id');
                if (action === 'edit') {
                    if (!window.hasPermission || !window.hasPermission('admin.config-group.update')) {
                        layer.msg('无操作权限', { icon: 2, time: 1000 });
                        return;
                    }
                    openGroupForm(id, $(this).data('name'), $(this).data('code'), $(this).data('sort'));
                } else {
                    if (!window.hasPermission || !window.hasPermission('admin.config-group.destroy')) {
                        layer.msg('无操作权限', { icon: 2, time: 1000 });
                        return;
                    }
                    confirmDelete('确定删除分组"' + $(this).data('name') + '"？分组下的所有配置项将一并删除！',
                        API.groups + '/' + id, function() {
                            if (currentGroupId == id) currentGroupId = null;
                            loadGroups();
                        });
                }
            });
        }

        $('#addGroupBtn').on('click', function() {
            if (!window.hasPermission || !window.hasPermission('admin.config-group.store')) {
                layer.msg('无操作权限', { icon: 2, time: 1000 });
                return;
            }
            openGroupForm(null, '', '', 0);
        });

        function openGroupForm(id, name, code, sort) {
            var isEdit = !!id;
            var fields = [
                buildFormItem('名称', '<input type="text" name="name" value="' + (name || '') + '" class="layui-input" placeholder="分组名称">'),
                buildFormItem('编码', '<input type="text" name="code" value="' + (code || '') + '" class="layui-input" placeholder="分组编码（英文）">'),
                buildFormItem('排序', '<input type="number" name="sort" value="' + (sort || 0) + '" class="layui-input">')
            ];
            layer.open({
                type: 1, title: isEdit ? '编辑分组' : '新增分组', area: ['400px', '306px'],
                content: '<form class="layui-form" style="padding:20px;" lay-filter="groupForm">'
                    + fields.join('') + buildFormFooter('gCancelBtn', 'gSubmitBtn') + '</form>',
                success: function(layero) {
                    form.render(null, 'groupForm');
                    bindFormButtons(layero, 'gCancelBtn', 'gSubmitBtn', function() {
                        var gName = layero.find('input[name=name]').val().trim();
                        var gCode = layero.find('input[name=code]').val().trim();
                        var gSort = parseInt(layero.find('input[name=sort]').val()) || 0;
                        if (!gName || !gCode) { layer.msg('名称和编码不能为空', { icon: 5 }); return; }
                        ajaxRequest({
                            url: isEdit ? API.groups + '/' + id : API.groups,
                            method: isEdit ? 'PUT' : 'POST',
                            data: JSON.stringify({ name: gName, code: gCode, sort: gSort }),
                            onSuccess: function() {
                                layer.msg(isEdit ? '更新成功' : '创建成功', { icon: 1, time: 1000 });
                                layer.closeAll(); loadGroups();
                            }
                        });
                    });
                }
            });
        }

        function renderContent() {
            if (!currentGroupId) {
                $('#contentPanel').html('<div class="empty-tip"><i class="layui-icon layui-icon-set" style="font-size:48px;color:#16b777;display:block;margin-bottom:15px;"></i>请选择左侧配置分组</div>');
                return;
            }
            var group = findGroup(currentGroupId);
            if (!group) return;

            var items = group.items || [];
            var html = buildConfigForm(group, items) + buildItemTable(items);
            $('#contentPanel').html(html);
            form.render();

            $('#saveConfigBtn').on('click', saveConfig);
            $('#resetConfigBtn').on('click', function() { renderContent(); });
            $('#addItemBtn').on('click', function() { openItemForm(null); });

            // 根据权限隐藏操作元素
            if (window.hasPermission && !window.hasPermission('admin.config-item.batch')) {
                $('#saveConfigBtn').hide();
            }
            if (window.hasPermission && !window.hasPermission('admin.config-item.store')) {
                $('#addItemBtn').hide();
            }
        }

        function findGroup(id) {
            for (var i = 0; i < groups.length; i++) {
                if (groups[i].id == id) return groups[i];
            }
            return null;
        }

        function findItem(id) {
            for (var i = 0; i < groups.length; i++) {
                for (var j = 0; j < (groups[i].items || []).length; j++) {
                    if (groups[i].items[j].id == id) return groups[i].items[j];
                }
            }
            return null;
        }

        function buildConfigForm(group, items) {
            var html = '<div class="config-form-card">';
            html += '<div class="card-title"><span>' + group.name + '</span></div>';
            if (items.length > 0) {
                html += '<form class="layui-form" lay-filter="configForm">';
                for (var j = 0; j < items.length; j++) {
                    var item = items[j];
                    html += '<div class="config-row">';
                    html += '<div class="config-label"><span>' + item.name + '</span>';
                    if (item.tips) { html += '<span class="tips">' + item.tips + '</span>'; }
                    html += '</div>';
                    html += '<div class="config-input">' + renderInput(item) + '</div>';
                    html += '</div>';
                }
                html += '<div class="config-actions">';
                html += '<button type="button" class="layui-btn" id="saveConfigBtn"><i class="layui-icon layui-icon-ok"></i> 保存配置</button> ';
                html += '<button type="button" class="layui-btn layui-btn-primary" id="resetConfigBtn"><i class="layui-icon layui-icon-refresh"></i> 重置</button>';
                html += '</div></form>';
            } else {
                html += '<div class="empty-tip">暂无配置项</div>';
            }
            html += '</div>';
            return html;
        }

        function buildItemTable(items) {
            var html = '<div class="config-form-card">';
            html += '<div class="item-manage-bar"><span class="title">配置项管理</span>';
            html += '<button type="button" class="layui-btn layui-btn-sm" id="addItemBtn"><i class="layui-icon layui-icon-add-1"></i> 新增配置项</button></div>';
            if (items.length > 0) {
                html += '<table class="layui-table" lay-size="sm"><colgroup><col width="150"><col width="150"><col width="80"><col><col width="80"><col width="140"></colgroup>';
                html += '<thead><tr><th>名称</th><th>标识</th><th>类型</th><th>当前值</th><th>排序</th><th>操作</th></tr></thead><tbody>';
                for (var k = 0; k < items.length; k++) {
                    var it = items[k];
                    var valDisplay = it.value || '-';
                    if (valDisplay.length > 40) valDisplay = valDisplay.substring(0, 40) + '...';
                    html += '<tr><td>' + it.name + '</td><td>' + it.code + '</td>';
                    html += '<td><span class="type-tag ' + it.type + '">' + it.type + '</span></td>';
                    html += '<td title="' + (it.value || '') + '">' + valDisplay + '</td>';
                    html += '<td>' + it.sort + '</td>';
                    html += '<td><a class="layui-btn layui-btn-xs" onclick="editItem(' + it.id + ')">编辑</a>';
                    html += '<a class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteItem(' + it.id + ',\'' + it.name + '\')">删除</a></td></tr>';
                }
                html += '</tbody></table>';
            } else {
                html += '<div class="empty-tip" style="padding:20px;">暂无配置项，点击上方按钮新增</div>';
            }
            html += '</div>';
            return html;
        }

        function renderInput(item) {
            var val = item.value || '';
            var name = 'config_' + item.id;
            var attrs = 'data-id="' + item.id + '"';
            switch (item.type) {
                case 'switch':
                    var checked = val === '1' || val === 'true';
                    return '<input type="checkbox" name="' + name + '" lay-skin="switch" lay-text="开启|关闭" ' + (checked ? 'checked' : '') + ' ' + attrs + ' data-type="switch">';
                case 'select':
                    var selHtml = '<select name="' + name + '" ' + attrs + '>';
                    var opts = item.options || [];
                    for (var i = 0; i < opts.length; i++) {
                        var opt = opts[i];
                        if (typeof opt === 'object') {
                            selHtml += '<option value="' + opt.value + '"' + (opt.value == val ? ' selected' : '') + '>' + opt.label + '</option>';
                        } else {
                            selHtml += '<option value="' + opt + '"' + (opt == val ? ' selected' : '') + '>' + opt + '</option>';
                        }
                    }
                    return selHtml + '</select>';
                case 'textarea':
                    return '<textarea name="' + name + '" ' + attrs + '>' + val + '</textarea>';
                case 'number':
                    return '<input type="number" name="' + name + '" value="' + val + '" class="layui-input" ' + attrs + '>';
                case 'password':
                    return '<input type="password" name="' + name + '" value="' + val + '" class="layui-input" ' + attrs + ' autocomplete="new-password" placeholder="请输入密码（留空则不修改）">';
                case 'image':
                    return '<input type="text" name="' + name + '" value="' + val + '" class="layui-input" placeholder="图片URL" ' + attrs + ' style="display:inline-block;width:calc(100% - 80px);margin-right:8px;">'
                        + '<button type="button" class="layui-btn layui-btn-sm" onclick="chooseImage(' + item.id + ')">选择</button>';
                default:
                    return '<input type="text" name="' + name + '" value="' + val + '" class="layui-input" ' + attrs + '>';
            }
        }

        function saveConfig() {
            if (!window.hasPermission || !window.hasPermission('admin.config-item.batch')) {
                layer.msg('无操作权限', { icon: 2, time: 1000 });
                return;
            }
            var items = [];
            $('#contentPanel').find('[data-id]').each(function() {
                var id = $(this).data('id');
                var type = $(this).data('type');
                var value = type === 'switch' ? ($(this).prop('checked') ? '1' : '0') : $(this).val();
                items.push({ id: id, value: value });
            });
            if (items.length === 0) { layer.msg('没有需要保存的配置', { icon: 3 }); return; }
            var loading = layer.load(2);
            ajaxRequest({
                url: API.batch, method: 'POST',
                data: JSON.stringify({ items: items }),
                onSuccess: function(res) {
                    layer.close(loading);
                    layer.msg('保存成功', { icon: 1, time: 1000 });
                    loadGroups();
                },
                onError: function() { layer.close(loading); }
            });
        }

        window.editItem = function(id) { openItemForm(id); };

        window.deleteItem = function(id, name) {
            if (!window.hasPermission || !window.hasPermission('admin.config-item.destroy')) {
                layer.msg('无操作权限', { icon: 2, time: 1000 });
                return;
            }
            confirmDelete('确定删除配置项"' + name + '"？', API.items + '/' + id, function() { loadGroups(); });
        };

        function openItemForm(id) {
            var isEdit = !!id;
            if (isEdit) {
                if (!window.hasPermission || !window.hasPermission('admin.config-item.update')) {
                    layer.msg('无操作权限', { icon: 2, time: 1000 });
                    return;
                }
            } else {
                if (!window.hasPermission || !window.hasPermission('admin.config-item.store')) {
                    layer.msg('无操作权限', { icon: 2, time: 1000 });
                    return;
                }
            }
            var item = isEdit ? findItem(id) : null;

            var typeOptions = ['text', 'number', 'switch', 'select', 'textarea', 'image', 'password'];
            var typeSelectHtml = '';
            for (var t = 0; t < typeOptions.length; t++) {
                var sel = (item && item.type === typeOptions[t]) ? ' selected' : (!item && typeOptions[t] === 'text' ? ' selected' : '');
                typeSelectHtml += '<option value="' + typeOptions[t] + '"' + sel + '>' + typeOptions[t] + '</option>';
            }

            var groupSelectHtml = '';
            for (var g = 0; g < groups.length; g++) {
                var gsel = (item && item.group_id == groups[g].id) || (!item && groups[g].id == currentGroupId) ? ' selected' : '';
                groupSelectHtml += '<option value="' + groups[g].id + '"' + gsel + '>' + groups[g].name + '</option>';
            }

            var optionsVal = (item && item.options) ? (typeof item.options === 'string' ? item.options : JSON.stringify(item.options)) : '';

            var fields = [
                buildFormItem('分组', '<select name="group_id">' + groupSelectHtml + '</select>'),
                buildFormItem('名称', '<input type="text" name="name" value="' + (item ? item.name : '') + '" class="layui-input" placeholder="配置项名称">'),
                buildFormItem('标识', '<input type="text" name="code" value="' + (item ? item.code : '') + '" class="layui-input" placeholder="配置项编码（英文）">'),
                buildFormItem('类型', '<select name="type">' + typeSelectHtml + '</select>'),
                buildFormItem('值', '<input type="text" name="value" value="' + (item ? (item.value || '') : '') + '" class="layui-input" placeholder="配置值">'),
                buildFormItem('选项', '<textarea name="options" class="layui-input" style="min-height:80px;resize:vertical;" placeholder="select类型的选项JSON，如：[{&quot;label&quot;:&quot;选项1&quot;,&quot;value&quot;:&quot;1&quot;}]">' + optionsVal + '</textarea>'),
                buildFormItem('提示', '<input type="text" name="tips" value="' + (item ? (item.tips || '') : '') + '" class="layui-input" placeholder="配置项提示说明">'),
                buildFormItem('排序', '<input type="number" name="sort" value="' + (item ? item.sort : 0) + '" class="layui-input">')
            ];
            layer.open({
                type: 1, title: isEdit ? '编辑配置项' : '新增配置项', area: ['500px', '480px'],
                content: '<form class="layui-form" style="padding:20px;" lay-filter="itemForm">'
                    + fields.join('') + buildFormFooter('iCancelBtn', 'iSubmitBtn') + '</form>',
                success: function(layero) {
                    form.render(null, 'itemForm');
                    bindFormButtons(layero, 'iCancelBtn', 'iSubmitBtn', function() {
                        var data = {
                            group_id: parseInt(layero.find('select[name=group_id]').val()),
                            name: layero.find('input[name=name]').val().trim(),
                            code: layero.find('input[name=code]').val().trim(),
                            type: layero.find('select[name=type]').val(),
                            value: layero.find('input[name=value]').val(),
                            tips: layero.find('input[name=tips]').val().trim(),
                            sort: parseInt(layero.find('input[name=sort]').val()) || 0
                        };
                        var optStr = (layero.find('textarea[name=options]').val() || '').trim();
                        if (optStr) {
                            try { data.options = JSON.parse(optStr); } catch(e) { data.options = optStr; }
                        }
                        if (!data.name || !data.code) { layer.msg('名称和标识不能为空', { icon: 5 }); return; }
                        ajaxRequest({
                            url: isEdit ? API.items + '/' + id : API.items,
                            method: isEdit ? 'PUT' : 'POST',
                            data: JSON.stringify(data),
                            onSuccess: function() {
                                layer.msg(isEdit ? '更新成功' : '创建成功', { icon: 1, time: 1000 });
                                layer.closeAll(); loadGroups();
                            }
                        });
                    });
                }
            });
        }

        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>
