<?php viewLoad('public/header'); ?>
<style>
html, body { height: 100%; margin: 0; padding: 0; }
#permPage { display: flex; height: 100%; gap: 12px; box-sizing: border-box; padding: 8px; }
#permTreeList { flex: 1; min-width: 0; }
#permEditPanel { width: 360px; border-left: 1px solid #eee; padding-left: 12px; overflow-y: auto; }
.field-row { margin-bottom: 12px; }
.field-row label { display: block; font-size: 12px; color: #666; margin-bottom: 4px; }
.type-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.type-row input[type="text"] { width: 110px; }
.btn-row { display: flex; gap: 8px; margin-top: 14px; }
</style>

<div id="permPage">
    <div id="permTreeList"></div>
    <div id="permEditPanel">
        <div id="codeBox" class="field-row"></div>
        <div id="nameBox" class="field-row"></div>
        <div id="enabledBox" class="field-row"></div>
        <div class="field-row">
            <label><?=lg('权限类型（启用+自定义名称）')?></label>
            <div id="typesArea"></div>
            <div id="addTypeBtn"></div>
        </div>
        <div class="field-row">
            <label><?=lg('额外配置schema（JSON，分组定义字段）')?></label>
            <div id="extraSchemaArea"></div>
        </div>
        <div class="btn-row">
            <div id="saveBtn"></div>
            <div id="deleteBtn"></div>
            <div id="newBtn"></div>
        </div>
        <div id="msgArea" style="color:#d0312d;font-size:12px;margin-top:8px;"></div>
    </div>
</div>

<script>
$(function () {
    var DEFAULT_TYPES = ['view', 'add', 'edit', 'delete', 'import', 'export', 'done', 'check1', 'check2', 'check3'];
    var isNew = true;
    var originalCode = null;

    var codeBoxInst = $('#codeBox').dxTextBox({ label: 'Code (5位，大写字母+数字)' }).dxTextBox('instance');
    var nameBoxInst = $('#nameBox').dxTextBox({ label: <?=json_encode(lg('名称'))?> }).dxTextBox('instance');
    var enabledBoxInst = $('#enabledBox').dxCheckBox({ text: <?=json_encode(lg('启用'))?>, value: true }).dxCheckBox('instance');
    var extraSchemaInst = $('#extraSchemaArea').dxTextArea({ height: 160, placeholder: '[{"group":"code","caption":"号码","items":[{"caption":"GSP型号","field":"outnum"}]}]' }).dxTextArea('instance');

    function renderTypeRows(typesObj) {
        var $area = $('#typesArea').empty();
        Object.keys(typesObj || {}).forEach(function (key) {
            var $row = $('<div class="type-row">').appendTo($area);
            $('<input type="checkbox" checked>').data('key', key).appendTo($row);
            var $label = $('<input type="text">').val(typesObj[key]).data('key', key).appendTo($row);
            $('<span>').text(key).appendTo($row);
        });
    }

    $('#addTypeBtn').dxButton({
        text: <?=json_encode(lg('+ 添加类型'))?>,
        onClick: function () {
            var key = window.prompt(<?=json_encode(lg('类型键名（如 check2）'))?>);
            if (!key) { return; }
            var $row = $('<div class="type-row">').appendTo('#typesArea');
            $('<input type="checkbox" checked>').data('key', key).appendTo($row);
            $('<input type="text">').val(key).data('key', key).appendTo($row);
            $('<span>').text(key).appendTo($row);
        }
    });

    function collectTypes() {
        var types = {};
        $('#typesArea .type-row').each(function () {
            var $row = $(this);
            if (!$row.find('input[type="checkbox"]').prop('checked')) { return; }
            var key = $row.find('input[type="text"]').data('key');
            var label = $row.find('input[type="text"]').val();
            types[key] = label;
        });
        return types;
    }

    function resetForm() {
        isNew = true;
        originalCode = null;
        codeBoxInst.option('value', '');
        codeBoxInst.option('readOnly', false);
        nameBoxInst.option('value', '');
        enabledBoxInst.option('value', true);
        extraSchemaInst.option('value', '');
        renderTypeRows({ view: <?=json_encode(lg('查看'))?> });
        $('#msgArea').text('');
    }

    function loadNode(node) {
        isNew = false;
        originalCode = node.sys_permission_code;
        codeBoxInst.option('value', node.sys_permission_code);
        codeBoxInst.option('readOnly', true);
        nameBoxInst.option('value', node.sys_permission_name);
        enabledBoxInst.option('value', !!node.sys_permission_enabled);
        extraSchemaInst.option('value', node.sys_permission_extra_schema ? JSON.stringify(node.sys_permission_extra_schema, null, 2) : '');
        renderTypeRows(node.sys_permission_types || {});
        $('#msgArea').text('');
    }

    var treeListInst = $('#permTreeList').dxTreeList({
        dataSource: [],
        keyExpr: 'sys_permission_code',
        parentIdExpr: 'sys_permission_parent_code',
        rootValue: null,
        height: '100%',
        allowColumnResizing: true,
        hoverStateEnabled: true,
        focusedRowEnabled: true,
        filterRow: { visible: true },
        columns: [
            { dataField: 'sys_permission_name', caption: <?=json_encode(lg('名称'))?> },
            { dataField: 'sys_permission_code', caption: 'Code', width: 90 },
            { dataField: 'sys_permission_enabled', caption: <?=json_encode(lg('启用'))?>, dataType: 'boolean', width: 70 }
        ],
        onRowClick: function (e) { loadNode(e.data); }
    }).dxTreeList('instance');

    function reloadTree() {
        return $.ajax({ url: APP.HOST + '/permission/tree', method: 'GET' }).then(function (res) {
            treeListInst.option('dataSource', res.data || []);
        });
    }

    $('#newBtn').dxButton({ text: <?=json_encode(lg('新建'))?>, onClick: resetForm });

    $('#saveBtn').dxButton({
        text: <?=json_encode(lg('保存'))?>, type: 'default',
        onClick: function () {
            var code = codeBoxInst.option('value').trim();
            var $msg = $('#msgArea').text('');

            if (!/^[A-Z0-9]{5}$/.test(code)) {
                $msg.text(<?=json_encode(lg('权限码必须是5位大写字母与数字'))?>);
                return;
            }

            var extraSchema = null;
            var raw = extraSchemaInst.option('value').trim();
            if (raw) {
                try { extraSchema = JSON.parse(raw); } catch (e) {
                    $msg.text(<?=json_encode(lg('额外配置schema不是合法的JSON'))?>);
                    return;
                }
            }

            var values = {
                sys_permission_code: code,
                sys_permission_name: nameBoxInst.option('value'),
                sys_permission_enabled: enabledBoxInst.option('value') ? 1 : 0,
                sys_permission_types: collectTypes(),
                sys_permission_extra_schema: extraSchema
            };

            $.ajax({
                url: APP.HOST + '/permission/save', method: 'POST', contentType: 'application/json',
                data: JSON.stringify({ code: isNew ? null : originalCode, values: values })
            }).then(function (res) {
                if (res.code === 0) {
                    DevExpress.ui.notify(<?=json_encode(lg('已保存'))?>, 'success', 1200);
                    reloadTree();
                    if (isNew) { isNew = false; originalCode = code; codeBoxInst.option('readOnly', true); }
                } else {
                    $msg.text(res.msg);
                }
            });
        }
    });

    $('#deleteBtn').dxButton({
        text: <?=json_encode(lg('删除'))?>, stylingMode: 'outlined', type: 'danger',
        onClick: function () {
            if (isNew || !originalCode) { return; }
            $.ajax({
                url: APP.HOST + '/permission/remove', method: 'POST', contentType: 'application/json',
                data: JSON.stringify({ code: originalCode })
            }).then(function (res) {
                if (res.code === 0) {
                    DevExpress.ui.notify(<?=json_encode(lg('已删除'))?>, 'success', 1200);
                    reloadTree();
                    resetForm();
                } else {
                    $('#msgArea').text(res.msg);
                }
            });
        }
    });

    resetForm();
    reloadTree();
});
</script>

<?php viewLoad('public/footer'); ?>
