<!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') }}">
    @include('admin.partials.permission-script')
</head>
<body>
<div class="pear-container">
    <div class="layui-card">
        <div class="layui-card-body">
            <form class="layui-form" action="">
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <input type="text" name="keyword" placeholder="角色名称/角色代码" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select name="status">
                            <option value="">全部状态</option>
                            <option value="1">正常</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn layui-btn-md" lay-submit lay-filter="role-query">
                        <i class="layui-icon layui-icon-search"></i> 查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-md layui-btn-primary">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="layui-card">
        <div class="layui-card-body">
            <table id="role-table" lay-filter="role-table"></table>
        </div>
    </div>

    <script type="text/html" id="role-toolbar">
        <button class="layui-btn layui-btn-sm" lay-event="add" data-permission="admin.role.store">
            <i class="layui-icon layui-icon-add-1"></i> 新增
        </button>
    </script>

    <script type="text/html" id="role-bar">
        <div class="layui-btn-container">
            <a class="layui-btn layui-btn-xs" lay-event="more">操作 <i class="layui-icon layui-icon-down"></i></a>
        </div>
    </script>

    @verbatim
    <script type="text/html" id="role-name-tpl">
        {{# if(d.is_super === 1){ }}
            <span class="layui-badge">超管</span> {{ d.name }}
        {{# } else { }}
            {{ d.name }}
        {{# } }}
    </script>
    @endverbatim

    @verbatim
    <script type="text/html" id="role-status-tpl">
        <input type="checkbox" name="status" value="{{ d.id }}" lay-skin="switch" lay-text="正常|禁用" lay-filter="role-status" {{ d.status == 1 ? 'checked' : '' }} />
    </script>
    @endverbatim

    @verbatim
    <script type="text/html" id="role-create-time-tpl">
        <span>{{ d.created_at || '-' }}</span>
    </script>
    @endverbatim
</div>
<script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
<script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
<script>
    layui.use(['table', 'form', 'jquery', 'dropdown'], function() {
        var table = layui.table;
        var form = layui.form;
        var $ = layui.jquery;
        var dropdown = layui.dropdown;

        $.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);
                    });
                }
            }
        });

        // 根据权限隐藏工具栏按钮
        $('#role-toolbar [data-permission]').each(function() {
            if (!window.hasPermission || !window.hasPermission($(this).data('permission'))) {
                $(this).hide();
            }
        });

        var cols = [[
            { type: 'checkbox', fixed: 'left' },
            { title: 'ID', field: 'id', align: 'center', width: 80, sort: true },
            { title: '角色名称', field: 'name', align: 'center', width: 160, templet: '#role-name-tpl' },
            { title: '角色代码', field: 'code', align: 'center', width: 140 },
            { title: '描述', field: 'description', align: 'center', minWidth: 200 },
            { title: '排序', field: 'sort', align: 'center', width: 100, sort: true },
            { title: '状态', field: 'status', align: 'center', width: 110, templet: '#role-status-tpl' },
            { title: '创建时间', field: 'created_at', align: 'center', width: 170, templet: '#role-create-time-tpl' },
            { title: '操作', toolbar: '#role-bar', align: 'center', width: 130, fixed: 'right' }
        ]];

        var inst = table.render({
            elem: '#role-table',
            url: '/api/admin/roles',
            page: {
                layout: ['count', 'prev', 'page', 'next', 'limit'],
                groups: 5,
                limit: 20,
                limits: [10, 20, 50, 100]
            },
            cols: cols,
            skin: false,
            toolbar: '#role-toolbar',
            defaultToolbar: [{
                title: '刷新',
                layEvent: 'refresh',
                icon: 'layui-icon-refresh'
            }, 'filter', 'print', 'exports'],
            parseData: function(res) {
                return {
                    "code": res.code === 0 ? 0 : 1,
                    "msg": res.message || "",
                    "count": res.data && res.data.pagination ? res.data.pagination.total : 0,
                    "data": res.data ? res.data.items : []
                };
            }
        });

        form.on('submit(role-query)', function(data) {
            table.reload('role-table', { where: data.field, page: { curr: 1 } });
            return false;
        });

        form.on('switch(role-status)', function(obj) {
            var id = this.value;
            $.ajax({
                url: '/api/admin/roles/' + id + '/status',
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify({ status: obj.elem.checked ? 1 : 0 }),
                success: function(res) {
                    if (res.code === 0) {
                        layer.msg('状态更新成功', { icon: 1, time: 1000 });
                    } else {
                        layer.msg(res.message || '操作失败', { icon: 2, time: 1000 });
                        $(obj.elem).prop('checked', !obj.elem.checked);
                        form.render();
                    }
                },
                error: function() {
                    layer.msg('请求失败', { icon: 2, time: 1000 });
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render();
                }
            });
        });

        table.on('toolbar(role-table)', function(obj) {
            if (obj.event === 'add') {
                window.add();
            } else if (obj.event === 'refresh') {
                table.reload('role-table');
            }
        });

        table.on('tool(' + inst.config.id + ')', function(obj) {
            if (obj.event === 'more') {
                var menuData = [
                    { title: '编辑', id: 'edit', permission: 'admin.role.update' },
                    { title: '分配权限', id: 'permission', permission: 'admin.role.permissions.update' },
                    { title: '分配菜单', id: 'menu', permission: 'admin.role.menus.update' },
                    { title: '删除', id: 'del', permission: 'admin.role.destroy' }
                ];
                // 根据权限过滤菜单项
                if (window.hasPermission) {
                    menuData = menuData.filter(function(item) {
                        return window.hasPermission(item.permission);
                    });
                }
                if (menuData.length === 0) return;
                dropdown.render({
                    elem: this,
                    show: true,
                    align: 'right',
                    data: menuData,
                    click: function(menudata) {
                        if (menudata.id === 'edit') {
                            window.edit(obj);
                        } else if (menudata.id === 'permission') {
                            window.assignPermission(obj);
                        } else if (menudata.id === 'menu') {
                            window.assignMenu(obj);
                        } else if (menudata.id === 'del') {
                            window.remove(obj);
                        }
                    }
                });
            }
        });

        window.add = function() {
            layer.open({
                type: 2,
                title: '新增角色',
                shade: 0.1,
                area: ['550px', '504px'],
                content: '/admin/role/form'
            });
        };

        window.edit = function(obj) {
            layer.open({
                type: 2,
                title: '编辑角色：' + obj.data.name,
                shade: 0.1,
                area: ['550px', '504px'],
                content: '/admin/role/form?id=' + obj.data.id
            });
        };

        window.assignPermission = function(obj) {
            layer.open({
                type: 2,
                title: '分配权限：' + obj.data.name,
                shade: 0.1,
                area: ['80%', '80%'],
                content: '/admin/role/permissions?id=' + obj.data.id
            });
        };

        window.assignMenu = function(obj) {
            layer.open({
                type: 2,
                title: '分配菜单：' + obj.data.name,
                shade: 0.1,
                area: ['500px', '80%'],
                content: '/admin/role/menus?id=' + obj.data.id
            });
        };

        window.remove = function(obj) {
            layer.confirm('确定要删除该角色？删除后无法恢复！', {
                icon: 3,
                title: '操作提示',
                btn: ['确定', '取消']
            }, function(index) {
                layer.close(index);
                var loading = layer.load();
                $.ajax({
                    url: '/api/admin/roles/' + obj.data.id,
                    type: 'DELETE',
                    dataType: 'json',
                    success: function(res) {
                        layer.close(loading);
                        if (res.code === 0) {
                            layer.msg('删除成功', { icon: 1, time: 1000 }, function() {
                                table.reload('role-table');
                            });
                        } else {
                            layer.msg(res.message || '删除失败', { icon: 2, time: 1000 });
                        }
                    },
                    error: function() {
                        layer.close(loading);
                        layer.msg('请求失败', { icon: 2, time: 1000 });
                    }
                });
            });
        };
    });
</script>
</body>
</html>
