<!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>
    .permission-group {
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #f0f0f0;
    }
    .permission-group .group-title {
        margin-bottom: 10px;
        font-weight: bold;
        font-size: 14px;
    }
    .permission-group .group-items {
        padding: 0 20px;
    }
    .bottom {
        bottom: 0px;
    }
    #permissionArea {
        overflow: auto;
        height: 0;
    }
    /* 半选状态样式 */
    .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="permissionArea">
            <div class="main-container" id="permissionList"></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;
            $('#permissionArea').height(newHeight);

            $(window).resize(function() {
                var newHeight = $(window).height() - 80;
                $('#permissionArea').height(newHeight);
            });

            $.ajax({
                url: '/api/admin/roles/' + roleId + '/permissions',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 0 && res.data) {
                        renderPermissions(res.data.all_permissions || [], res.data.selected_ids || []);
                        // 编辑自身角色时显示限制遮罩
                        if (res.data.is_own_role === true) {
                            $('#ownRoleOverlay').show();
                            // 禁用所有交互
                            $('input[name="permission_ids[]"]').prop('disabled', true);
                            $('input[lay-filter="module-check"]').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 renderPermissions(permissions, selectedIds) {
                var grouped = {};
                permissions.forEach(function(item) {
                    var mod = item.module_name || item.module || '其他';
                    if (!grouped[mod]) grouped[mod] = [];
                    grouped[mod].push(item);
                });

                var html = '';
                for (var mod in grouped) {
                    html += '<div class="permission-group">';
                    html += '<div class="group-title"><input type="checkbox" lay-skin="primary" lay-filter="module-check" data-module="' + mod + '" title="' + mod + '"></div>';
                    html += '<div class="group-items">';
                    grouped[mod].forEach(function(item) {
                        var isChecked = selectedIds.indexOf(item.id) > -1 ? ' checked' : '';
                        html += '<input type="checkbox" name="permission_ids[]" value="' + item.id + '" data-module="' + mod + '" title="' + item.name + '"' + isChecked + ' lay-skin="primary" lay-filter="permission-check">';
                    });
                    html += '</div></div>';
                }
                $('#permissionList').html(html);
                form.render('checkbox');
                updateModuleStates();
            }

            // 根据子项选中状态更新模块标题的全选/半选/未选
            function updateModuleStates() {
                $('input[lay-filter="module-check"]').each(function() {
                    var $moduleCb = $(this);
                    var mod = $moduleCb.data('module');
                    var $childCbs = $('input[data-module="' + mod + '"][name="permission_ids[]"]');

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

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

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

                    if (checkedCount === total) {
                        // 全部选中
                        $moduleCb.prop('checked', true);
                        $rendered.addClass('layui-form-checked');
                    } else if (checkedCount > 0) {
                        // 部分选中 → 半选
                        $rendered.addClass('layui-form-indeterminate');
                    }
                });
            }

            form.on('checkbox(module-check)', function(obj) {
                var mod = $(this).data('module');
                var checked = obj.elem.checked;
                // 级联：模块标题勾选/取消 → 所有子项同步
                $('input[data-module="' + mod + '"][name="permission_ids[]"]').prop('checked', checked);
                form.render('checkbox');
                updateModuleStates();
            });

            // 权限子项变化时更新模块标题状态
            form.on('checkbox(permission-check)', function(data) {
                updateModuleStates();
            });

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

            $('#unselectAll').on('click', function() {
                $('input[name="permission_ids[]"]').prop('checked', false);
                $('input[lay-filter="module-check"]').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="permission_ids[]"]:checked').each(function() {
                    ids.push(parseInt($(this).val()));
                });

                $.ajax({
                    url: '/api/admin/roles/' + roleId + '/permissions',
                    type: 'PUT',
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify({ permission_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>
