<!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>
    .bottom {
        bottom: 0px;
    }
    #menuArea {
        overflow: auto;
        height: 0;
        padding: 10px;
    }
    .menu-tree {
        padding-left: 20px;
    }
    .menu-item {
        margin: 4px 0;
    }
    .menu-item .menu-label {
        cursor: pointer;
        display: inline-block;
        line-height: 28px;
    }
    .menu-children {
        border-left: 1px dashed #e6e6e6;
        margin-left: 8px;
        padding-left: 12px;
    }
    /* 半选状态样式 */
    .layui-form-checkbox.layui-form-indeterminate[lay-skin="primary"] i {
        border-color: #16b777 !important;
        background-color: #16b777;
    }
    .layui-form-checkbox.layui-form-indeterminate[lay-skin="primary"] i::before {
        content: "";
        display: block;
        width: 10px;
        height: 2px;
        background-color: #fff;
        margin: 6px auto 0;
    }
    /* 编辑自身角色限制遮罩 — 参考 _no_hospital_overlay 全屏固定遮罩模式 */
    .own-role-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: #fff;
        z-index: 9999;
        text-align: center;
        padding-top: 15%;
    }
    .own-role-overlay-inner {
        display: inline-block;
        text-align: center;
    }
    .own-role-overlay-inner .overlay-icon {
        font-size: 48px;
        color: #ff5722;
    }
    .own-role-overlay-inner .overlay-title {
        font-size: 20px;
        font-weight: 600;
        color: #333;
        margin-top: 12px;
    }
    .own-role-overlay-inner .overlay-desc {
        font-size: 14px;
        color: #888;
        margin-top: 8px;
        line-height: 1.6;
    }
</style>

<body>
    <form class="layui-form" action="">
        <input type="hidden" id="roleId" name="role_id" value="">
        <div class="mainBox" id="menuArea">
            <div class="main-container" id="menuList"></div>
        </div>
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="layui-btn layui-btn-sm" lay-submit lay-filter="save">
                    <i class="layui-icon layui-icon-ok"></i> 提交
                </button>
                <button type="button" class="layui-btn layui-btn-sm" id="selectAll">
                    <i class="layui-icon layui-icon-ok-circle"></i> 全选
                </button>
                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="unselectAll">
                    <i class="layui-icon layui-icon-close-fill"></i> 取消全选
                </button>
            </div>
        </div>
    </form>

    <div class="own-role-overlay" id="ownRoleOverlay">
        <div class="own-role-overlay-inner">
            <div class="overlay-icon"><i class="layui-icon layui-icon-password"></i></div>
            <div class="overlay-title">编辑菜单限制</div>
            <div class="overlay-desc">不允许编辑自己所在角色的菜单</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'], 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 roleId = new URLSearchParams(window.location.search).get('id');
            $('#roleId').val(roleId);

            var newHeight = $(window).height() - 80;
            $('#menuArea').height(newHeight);

            $(window).resize(function() {
                $('#menuArea').height($(window).height() - 80);
            });

            $.ajax({
                url: '/api/admin/roles/' + roleId + '/menus',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 0 && res.data) {
                        buildTree(res.data.all_menus || [], res.data.selected_ids || []);
                        // 编辑自身角色时显示限制遮罩
                        if (res.data.is_own_role === true) {
                            $('#ownRoleOverlay').show();
                            // 禁用所有交互
                            $('input[name="menu_ids[]"]').prop('disabled', true);
                            $('#selectAll, #unselectAll').prop('disabled', true);
                            $('button[lay-filter="save"]').prop('disabled', true);
                        }
                    } else {
                        layer.msg(res.message || '获取菜单数据失败', { icon: 2, time: 2000 }, function() {
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                        });
                    }
                },
                error: function() {
                    layer.msg('请求失败', { icon: 2, time: 2000 }, function() {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    });
                }
            });

            function buildTree(menus, selectedIds) {
                function getChildren(parentId) {
                    return menus.filter(function(m) { return (m.parent_id || 0) == parentId; });
                }

                function renderNode(item) {
                    var isChecked = selectedIds.indexOf(item.id) > -1 ? ' checked' : '';
                    var children = getChildren(item.id);
                    var html = '<div class="menu-item">';
                    html += '<input type="checkbox" name="menu_ids[]" value="' + item.id + '" title="' + item.name + '"' + isChecked + ' lay-skin="primary" lay-filter="menuCascade">';
                    if (children.length > 0) {
                        html += '<div class="menu-children">';
                        children.forEach(function(child) {
                            html += renderNode(child);
                        });
                        html += '</div>';
                    }
                    html += '</div>';
                    return html;
                }

                var roots = getChildren(0);
                var html = '';
                roots.forEach(function(item) {
                    html += renderNode(item);
                });
                $('#menuList').html(html);
                form.render('checkbox');
                updateIndeterminateStates();
            }

            // 根据所有子孙节点的选中状态，更新父节点的全选/半选/未选
            function updateIndeterminateStates() {
                // 从最深层向上遍历，确保子级状态先计算完毕
                var $parents = $('.menu-item').has('.menu-children');
                var arr = $parents.get().reverse();

                $(arr).each(function() {
                    var $item = $(this);
                    var $parentCb = $item.find('> input[name="menu_ids[]"]');
                    // 查找所有子孙 checkbox（子、孙、曾孙……）
                    var $descendantCbs = $item.find('.menu-children input[name="menu_ids[]"]');

                    if ($descendantCbs.length === 0) return;

                    var checkedCount = $descendantCbs.filter(function() { return this.checked; }).length;

                    // 先清除当前状态
                    $parentCb.prop('checked', false);
                    var $rendered = $parentCb.next('.layui-form-checkbox');
                    $rendered.removeClass('layui-form-checked layui-form-indeterminate');

                    if (checkedCount === $descendantCbs.length) {
                        // 所有子孙都选中 → 全选
                        $parentCb.prop('checked', true);
                        $rendered.addClass('layui-form-checked');
                    } else if (checkedCount > 0) {
                        // 部分子孙选中 → 半选
                        $rendered.addClass('layui-form-indeterminate');
                    }
                });
            }

            // 勾选上级 → 自动勾选/取消所有下级，并更新父级半选状态
            form.on('checkbox(menuCascade)', function(data) {
                var $cb = $(data.elem);
                var checked = data.elem.checked;

                // 级联子节点：当前节点的所有子孙 checkbox 同步状态
                $cb.closest('.menu-item').find('.menu-children input[name="menu_ids[]"]').each(function() {
                    this.checked = checked;
                    $(this).next('.layui-form-checkbox')
                        .removeClass('layui-form-checked layui-form-indeterminate')
                        .toggleClass('layui-form-checked', checked);
                });

                // 清除当前节点的半选状态
                $cb.next('.layui-form-checkbox').removeClass('layui-form-indeterminate');

                // 更新所有父级的选中/半选状态
                updateIndeterminateStates();

                // 重新渲染，让 UI 与 state 同步
                form.render('checkbox');
                updateIndeterminateStates();
            });

            $('#selectAll').on('click', function() {
                $('input[name="menu_ids[]"]').prop('checked', true);
                $('.layui-form-checkbox').removeClass('layui-form-indeterminate');
                form.render('checkbox');
            });

            $('#unselectAll').on('click', function() {
                $('input[name="menu_ids[]"]').prop('checked', false);
                $('.layui-form-checkbox').removeClass('layui-form-checked layui-form-indeterminate');
                form.render('checkbox');
            });

            form.on('submit(save)', function(data) {
                var ids = [];
                $('input[name="menu_ids[]"]:checked').each(function() {
                    ids.push(parseInt($(this).val()));
                });

                $.ajax({
                    url: '/api/admin/roles/' + roleId + '/menus',
                    type: 'PUT',
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify({ menu_ids: ids }),
                    success: function(res) {
                        if (res.code === 0) {
                            layer.msg('菜单分配成功', { icon: 1, time: 1000 }, function() {
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            });
                        } else {
                            layer.msg(res.message || '操作失败', { icon: 2, time: 1500 });
                        }
                    },
                    error: function() {
                        layer.msg('请求失败', { icon: 2, time: 1500 });
                    }
                });
                return false;
            });
        });
    </script>
</body>
</html>
