<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <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') }}" />
</head>
<style>
    .layui-form-label {
        padding: 9px 4px;
        width: unset;
    }
    .layui-input, .layui-textarea {
        width: 98%;
    }
</style>

<body>
    <form class="layui-form" action="">
        <input type="hidden" id="id" name="id" value="">
        <div class="layui-row">
            <div class="layui-col-md12">
                <div class="layui-card-body layui-row">
                    <div class="layui-col-md12">
                        <div class="layui-form-item">
                            <label class="layui-form-label">父角色</label>
                            <div class="layui-input-block">
                                <select id="parent_id" name="parent_id" lay-search="">
                                    <option value="0">顶级角色</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">角色名称</label>
                            <div class="layui-input-block">
                                <input type="text" id="name" name="name" lay-verify="required" lay-reqText="角色名称不能为空" placeholder="请输入角色名称" class="layui-input" autocomplete="off">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">角色代码</label>
                            <div class="layui-input-block">
                                <input type="text" id="code" name="code" lay-verify="required" lay-reqText="角色代码不能为空" placeholder="请输入角色代码" class="layui-input" autocomplete="off">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">描述</label>
                            <div class="layui-input-block">
                                <textarea id="description" name="description" placeholder="请输入描述" class="layui-textarea"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">排序</label>
                            <div class="layui-input-block">
                                <input type="number" id="sort" name="sort" value="0" placeholder="请输入排序" class="layui-input" autocomplete="off">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-block">
                                <select id="status" name="status">
                                    <option value="1">正常</option>
                                    <option value="0">禁用</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="layui-btn layui-btn-normal layui-btn-sm" lay-submit lay-filter="save">
                    <i class="layui-icon layui-icon-ok"></i> 提交
                </button>
                <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
                    <i class="layui-icon layui-icon-refresh"></i> 清空
                </button>
            </div>
        </div>
    </form>

    <script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
    <script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
    <script>
        layui.use(['form', 'jquery'], function() {
            var form = layui.form;
            var $ = layui.jquery;

            $.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 editId = new URLSearchParams(window.location.search).get('id');
            var isEdit = !!editId;

            $.ajax({
                url: '/api/admin/roles/all',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 0 && res.data) {
                        // 兼容新旧返回结构：新结构为 {items, is_super_privileged}，旧结构为数组
                        var list = Array.isArray(res.data) ? res.data : (res.data.items || []);
                        var isSuperPrivileged = Array.isArray(res.data) ? true : (res.data.is_super_privileged === true);

                        // 收集指定角色及其所有子孙的ID（编辑时排除自身子树，防止形成环）
                        function collectSubtreeIds(items, rootId) {
                            var ids = [rootId];
                            var children = items.filter(function(item) {
                                return (item.parent_id || 0) == rootId;
                            });
                            for (var i = 0; i < children.length; i++) {
                                ids = ids.concat(collectSubtreeIds(items, children[i].id));
                            }
                            return ids;
                        }

                        // 递归构建树形 option（使用 ├─ └─ │ 缩进前缀模拟树形层级）
                        function buildRoleTree(items, parentId, prefix, excludeIds) {
                            var html = '';
                            var children = items.filter(function(item) {
                                return (item.parent_id || 0) == parentId && excludeIds.indexOf(item.id) === -1;
                            });
                            for (var i = 0; i < children.length; i++) {
                                var item = children[i];
                                var isLast = (i === children.length - 1);
                                // 顶级角色不加前缀，子角色按层级加缩进
                                var treePrefix = parentId == 0 ? '' : (prefix + (isLast ? '└─ ' : '├─ '));
                                html += '<option value="' + item.id + '">' + treePrefix + item.name + '</option>';
                                html += buildRoleTree(items, item.id, prefix + (isLast ? '   ' : '│  '), excludeIds);
                            }
                            return html;
                        }

                        // 编辑时排除当前角色及其所有子孙，防止将自身子树选为父级形成环
                        var excludeIds = isEdit ? collectSubtreeIds(list, parseInt(editId)) : [];
                        // 非超权账号禁止创建顶级角色（后端 store() 校验），前端不显示"顶级角色"选项
                        var topOption = isSuperPrivileged ? '<option value="0">顶级角色</option>' : '';
                        var options = topOption + buildRoleTree(list, 0, '', excludeIds);
                        $('#parent_id').html(options);

                        if (isEdit) {
                            loadRoleData();
                        } else {
                            form.render('select');
                        }
                    }
                }
            });

            function loadRoleData() {
                $.ajax({
                    url: '/api/admin/roles/' + editId,
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 0 && res.data) {
                            var d = res.data;
                            $('#id').val(d.id);
                            $('#name').val(d.name);
                            $('#code').val(d.code);
                            $('#description').val(d.description);
                            $('#sort').val(d.sort);
                            $('#status').val(d.status);
                            $('#parent_id').val(d.parent_id || 0);
                            form.render('select');
                        }
                    }
                });
            }

            form.on('submit(save)', function(data) {
                var url = isEdit ? '/api/admin/roles/' + editId : '/api/admin/roles';
                var method = isEdit ? 'PUT' : 'POST';

                $.ajax({
                    url: url,
                    type: method,
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify(data.field),
                    success: function(res) {
                        if (res.code === 0) {
                            layer.msg(isEdit ? '编辑成功' : '新增成功', { icon: 1, time: 1000 }, function() {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                                parent.layui.table.reload('role-table');
                            });
                        } else {
                            layer.msg(res.message || '操作失败', { icon: 2, time: 1500 });
                        }
                    },
                    error: function() {
                        layer.msg('请求失败', { icon: 2, time: 1500 });
                    }
                });
                return false;
            });
        });
    </script>
</body>
</html>
