<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-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') }}">
</head>

<body class="pear-container">
    <div class="layui-card">
        <div class="layui-card-body">
            <table class="layui-hide" id="terminal-table" lay-filter="terminal-table"></table>
        </div>
    </div>

    @verbatim
    <script type="text/html" id="terminal-toolbar">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="add">
                <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>
        </div>
    </script>

    <script type="text/html" id="terminal-bar">
        <button class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i></button>
        <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="remove"><i class="layui-icon layui-icon-delete"></i></button>
    </script>

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

    <script type="text/html" id="terminal-sort-tpl">
        <input type="text" name="sort" class="layui-input terminal-sort-input" value="{{ d.sort || 0 }}" style="width: 60px; text-align: center;" />
        <input type="hidden" name="id" value="{{ d.id }}" />
    </script>
    @endverbatim

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

            table.render({
                elem: '#terminal-table',
                url: '/api/admin/menus/terminals',
                page: {
                    layout: ['count', 'prev', 'page', 'next', 'limit'],
                    groups: 5,
                    limit: 20,
                    limits: [20, 50, 100]
                },
                toolbar: '#terminal-toolbar',
                defaultToolbar: [{
                    title: '刷新',
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh'
                }, 'filter', 'print', 'exports'],
                cols: [[
                    { field: 'id', title: 'ID', width: 80, align: 'center' },
                    { field: 'type', title: '类型', width: 120, align: 'center' },
                    { field: 'name', title: '名称', width: 100 },
                    { field: 'description', title: '描述' },
                    { field: 'sort', title: '排序', width: 90, align: 'center', templet: '#terminal-sort-tpl' },
                    { field: 'status', title: '状态', width: 100, align: 'center', templet: '#terminal-status-tpl' },
                    { fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#terminal-bar' }
                ]],
                parseData: function(res) {
                    if (res.code === 0) {
                        return {
                            "code": 0,
                            "msg": res.message || "",
                            "count": res.data?.pagination?.total || (res.data || []).length,
                            "data": res.data?.items || res.data || []
                        };
                    }
                    return {
                        "code": 1,
                        "msg": res.message || "数据格式错误",
                        "count": 0,
                        "data": []
                    };
                }
            });

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

            table.on('tool(terminal-table)', function(obj) {
                if (obj.event === 'edit') {
                    window.edit(obj);
                } else if (obj.event === 'remove') {
                    window.remove(obj);
                }
            });

            form.on('switch(terminal-status)', function(obj) {
                $.ajax({
                    url: '/api/admin/menus/terminals/' + this.value + '/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: 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() {
                layer.open({
                    type: 2,
                    title: '添加终端',
                    shade: 0.1,
                    area: ['500px', '440px'],
                    content: '/admin/menu/terminal-form'
                });
            };

            window.edit = function(obj) {
                layer.open({
                    type: 2,
                    title: '编辑终端：' + obj.data.name,
                    shade: 0.1,
                    area: ['500px', '440px'],
                    content: '/admin/menu/terminal-form?id=' + obj.data.id,
                    success: function(layero) {
                        setTimeout(function() {
                            var iframeBody = layero.find('iframe').contents();
                            iframeBody.find('#id').val(obj.data.id);
                            iframeBody.find('#type').val(obj.data.type);
                            iframeBody.find('#name').val(obj.data.name);
                            iframeBody.find('#description').val(obj.data.description);
                            iframeBody.find('#sort').val(obj.data.sort);
                            iframeBody.find('input[name="status"][value="' + obj.data.status + '"]').prop('checked', true);
                            iframeBody.find('.layui-form').find('[lay-filter]').each(function() {
                                form.render($(this).attr('lay-filter'));
                            });
                        }, 300);
                    }
                });
            };

            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/terminals/' + 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('terminal-table');
                                });
                            } 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 = [];
                $('.terminal-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/terminals/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() {
                                table.reload('terminal-table');
                            });
                        } else {
                            layer.msg(res.message || '保存失败', { icon: 2, time: 2000 });
                        }
                    },
                    error: function() {
                        layer.close(load);
                        layer.msg('请求失败', { icon: 2, time: 2000 });
                    }
                });
            };

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