<!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-tab layui-tab-card" lay-filter="MenuType">
            <ul class="layui-tab-title" id="terminal-tabs"></ul>
        </div>
        <div class="layui-card-body">
            <table class="layui-hide" id="menu-table" lay-filter="menu-table"></table>
        </div>
    </div>

    @verbatim
    <script type="text/html" id="menu-toolbar">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="add" data-permission="admin.menu.store">
                <i class="layui-icon layui-icon-add-1"></i> 新增顶级菜单
            </button>
            <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="setSort">
                <i class="layui-icon layui-icon-ok-circle"></i> 保存排序
            </button>
            <button class="layui-btn layui-btn-sm" lay-event="expandAll">
                <i class="layui-icon layui-icon-spread-left"></i> 展开
            </button>
            <button class="layui-btn layui-btn-sm" lay-event="foldAll">
                <i class="layui-icon layui-icon-shrink-right"></i> 折叠
            </button>
            <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="terminal">
                <i class="layui-icon layui-icon-app"></i> 终端管理
            </button>
        </div>
    </script>

    <script type="text/html" id="menu-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>

    <script type="text/html" id="menu-type-tpl">
        {{# var t = parseInt(d.type); if(t === 1){ }}
            <span class="layui-badge layui-bg-blue">目录</span>
        {{# } else if(t === 2){ }}
            <span class="layui-badge layui-bg-green">菜单</span>
        {{# } else if(t === 3){ }}
            <span class="layui-badge layui-bg-orange">按钮</span>
        {{# } else { }}
            <span class="layui-badge layui-bg-gray">{{ d.type || '-' }}</span>
        {{# } }}
    </script>

    <script type="text/html" id="menu-icon-tpl">
        {{# var ico = d.icon || ''; }}
        {{# var iconMap = { IconSetting: 'layui-icon layui-icon-set', IconMenu: 'layui-icon layui-icon-menu-fill', IconImage: 'layui-icon layui-icon-picture', IconFile: 'layui-icon layui-icon-file' }; }}
        {{# if(ico.startsWith('Icon') && iconMap[ico]){ ico = iconMap[ico]; } }}
        {{# if(ico && ico.indexOf('/') !== 0){ }}
            <i class="{{ ico }}" style="font-size: 16px;"></i>
        {{# } else { }}
            <span style="color: #ccc;">-</span>
        {{# } }}
    </script>

    <script type="text/html" id="menu-visible-tpl">
        <input type="checkbox" name="visible" value="{{ d.id }}" lay-skin="switch" lay-text="显示|隐藏" lay-filter="menu-visible" {{ d.visible == 1 ? 'checked' : '' }} />
    </script>

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

    <script type="text/html" id="menu-sort-tpl">
        <input type="text" name="sort" class="layui-input menu-sort-input" value="{{ d.sort || 0 }}" style="width: 50px; text-align: center;" />
        <input type="hidden" name="id" value="{{ d.id }}" />
    </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', 'element'], function() {
        var table = layui.table;
        var form = layui.form;
        var $ = layui.jquery;
        var dropdown = layui.dropdown;
        var element = layui.element;
        var treeTable = layui.treeTable;

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

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

        var currentTerminal = '';
        var inst;

        function loadTerminals() {
            $.ajax({
                url: '/api/admin/menus/terminals?per_page=100',
                type: 'GET',
                dataType: 'json',
                async: false,
                success: function(res) {
                    if (res.code === 0 && res.data && res.data.items && res.data.items.length > 0) {
                        var html = '';
                        $.each(res.data.items, function(i, item) {
                            if (i === 0) {
                                currentTerminal = item.type;
                                html += '<li lay-id="' + item.type + '" class="layui-this">' + item.name + '</li>';
                            } else {
                                html += '<li lay-id="' + item.type + '">' + item.name + '</li>';
                            }
                        });
                        $('#terminal-tabs').html(html);
                        element.render('tab');
                    } else {
                        $('#terminal-tabs').html('<li lay-id="" class="layui-this">默认</li>');
                    }
                },
                error: function() {
                    $('#terminal-tabs').html('<li lay-id="" class="layui-this">默认</li>');
                }
            });
        }

        loadTerminals();

        element.on('tab(MenuType)', function(data) {
            currentTerminal = this.getAttribute('lay-id');
            if (inst) {
                var url = '/api/admin/menus';
                if (currentTerminal && currentTerminal !== '') {
                    url += '?terminal=' + currentTerminal;
                }
                inst.reload({ url: url });
            }
        });

        inst = treeTable.render({
            elem: '#menu-table',
            url: '/api/admin/menus' + (currentTerminal ? '?terminal=' + currentTerminal : ''),
            defaultToolbar: [{
                title: '刷新',
                layEvent: 'refresh',
                icon: 'layui-icon-refresh'
            }, 'filter', 'print', 'exports'],
            cellMinWidth: 80,
            maxHeight: ($(window).height() - 140) + 'px',
            tree: {
                view: {
                    expandAllDefault: false,
                    showIcon: false
                },
                data: {
                    idKey: 'id',
                    parentIdKey: 'parent_id'
                }
            },
            toolbar: '#menu-toolbar',
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'id', title: 'ID', width: 80, fixed: 'left', align: 'center', unresize: true },
                { field: 'name', title: '菜单名称', minWidth: 150, align: 'left' },
                { field: 'type', title: '类型', width: 80, align: 'center', templet: '#menu-type-tpl' },
                { field: 'icon', title: '图标', width: 80, align: 'center', templet: '#menu-icon-tpl' },
                { field: 'path', title: '路径', minWidth: 140, align: 'left' },
                { field: 'sort', title: '排序', width: 80, align: 'center', templet: '#menu-sort-tpl' },
                { field: 'visible', title: '可见', width: 100, align: 'center', templet: '#menu-visible-tpl' },
                { field: 'status', title: '状态', width: 100, align: 'center', templet: '#menu-status-tpl' },
                { fixed: 'right', title: '操作', width: 100, align: 'center', toolbar: '#menu-bar' }
            ]],
            parseData: function(res) {
                var menuData = res.data;
                if (Array.isArray(menuData)) {
                    return {
                        "code": res.code === 0 ? 0 : 1,
                        "msg": res.message || "",
                        "count": menuData.length,
                        "data": menuData
                    };
                }
                return {
                    "code": 1,
                    "msg": "数据格式错误",
                    "count": 0,
                    "data": []
                };
            },
            done: function(res, curr, count) {
                $('.menu-sort-input').on('focus', function() { $(this).select(); });
            }
        });

        treeTable.on('toolbar(menu-table)', function(obj) {
            if (obj.event === 'refresh') {
                treeTable.reload('menu-table');
            } else if (obj.event === 'add') {
                window.add();
            } else if (obj.event === 'setSort') {
                window.saveSort();
            } else if (obj.event === 'expandAll') {
                treeTable.expandAll('menu-table', true);
            } else if (obj.event === 'foldAll') {
                treeTable.expandAll('menu-table', false);
            } else if (obj.event === 'terminal') {
                window.openTerminal();
            }
        });

        treeTable.on('tool(' + inst.config.id + ')', function(obj) {
            if (obj.event === 'more') {
                var menuData = [
                    { title: '新增子菜单', id: 'add', permission: 'admin.menu.store' },
                    { title: '编辑', id: 'edit', permission: 'admin.menu.update' },
                    { title: '删除', id: 'del', permission: 'admin.menu.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 === 'add') {
                            window.add(obj);
                        } else if (menudata.id === 'edit') {
                            window.edit(obj);
                        } else if (menudata.id === 'del') {
                            window.remove(obj);
                        }
                    }
                });
            }
        });

        form.on('switch(menu-visible)', function(obj) {
            var id = this.value;
            $.ajax({
                url: '/api/admin/menus/' + id + '/visible',
                type: 'PUT',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify({ visible: 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: 2000 });
                        $(obj.elem).prop('checked', !obj.elem.checked);
                        form.render();
                    }
                },
                error: function() {
                    layer.msg('请求失败', { icon: 2, time: 2000 });
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render();
                }
            });
        });

        form.on('switch(menu-status)', function(obj) {
            var id = this.value;
            $.ajax({
                url: '/api/admin/menus/' + id + '/status',
                type: 'PUT',
                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: 2000 });
                        $(obj.elem).prop('checked', !obj.elem.checked);
                        form.render();
                    }
                },
                error: function() {
                    layer.msg('请求失败', { icon: 2, time: 2000 });
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render();
                }
            });
        });

        window.add = function(obj) {
            var parentId = 0;
            if (obj && obj.data) {
                parentId = obj.data.id;
            }
            layer.open({
                type: 2,
                title: '新增菜单',
                shade: 0.1,
                area: ['750px', '642px'],
                content: '/admin/menu/form?parent_id=' + parentId + '&terminal=' + currentTerminal
            });
        };

        window.edit = function(obj) {
            layer.open({
                type: 2,
                title: '编辑菜单：' + obj.data.name,
                shade: 0.1,
                area: ['750px', '642px'],
                content: '/admin/menu/form?id=' + obj.data.id + '&terminal=' + currentTerminal
            });
        };

        window.remove = function(obj) {
            layer.confirm('确定要删除该菜单？子菜单将一并删除，删除后无法恢复！', {
                icon: 3,
                title: '操作提示',
                btn: ['确定', '取消']
            }, function(index) {
                layer.close(index);
                var loading = layer.load(2);
                $.ajax({
                    url: '/api/admin/menus/' + obj.data.id,
                    type: 'DELETE',
                    dataType: 'json',
                    success: function(res) {
                        layer.close(loading);
                        if (res.code === 0) {
                            layer.msg('删除成功', { icon: 1, time: 1000 }, function() {
                                obj.del();
                            });
                        } else {
                            layer.msg(res.message || '删除失败', { icon: 2, time: 2000 });
                        }
                    },
                    error: function() {
                        layer.close(loading);
                        layer.msg('请求失败', { icon: 2, time: 2000 });
                    }
                });
            });
        };

        window.saveSort = function() {
            var load = layer.load(2);
            var ids = [];
            var sorts = [];
            $('.menu-sort-input').each(function() {
                var input = $(this);
                var hiddenId = input.siblings('input[name="id"]');
                if (hiddenId.val()) {
                    ids.push(hiddenId.val());
                    sorts.push(input.val() || 0);
                }
            });

            if (ids.length === 0) {
                layer.close(load);
                layer.msg('没有可保存的数据', { icon: 2, time: 1500 });
                return;
            }

            $.ajax({
                url: '/api/admin/menus/sort',
                type: 'PUT',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify({ ids: ids, sorts: sorts }),
                success: function(res) {
                    layer.close(load);
                    if (res.code === 0) {
                        layer.msg('排序保存成功', { icon: 1, time: 1000 }, function() {
                            treeTable.reload('menu-table');
                        });
                    } else {
                        layer.msg(res.message || '保存失败', { icon: 2, time: 2000 });
                    }
                },
                error: function() {
                    layer.close(load);
                    layer.msg('请求失败', { icon: 2, time: 2000 });
                }
            });
        };

        window.openTerminal = function() {
            layer.open({
                type: 2,
                title: '终端管理',
                shade: 0.1,
                area: ['800px', '600px'],
                content: '/admin/menu/terminal'
            });
        };

        window.refresh = function() {
            treeTable.reload('menu-table');
        };
    });
</script>
</body>
</html>
