<!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="category_id" id="searchCategoryId">
                            <option value="">全部分类</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select name="status">
                            <option value="">全部状态</option>
                            <option value="0">草稿</option>
                            <option value="1">已发布</option>
                            <option value="2">已下架</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn layui-btn-md" lay-submit lay-filter="content-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="content-table" lay-filter="content-table"></table>
        </div>
    </div>

    <script type="text/html" id="content-toolbar">
        <button class="layui-btn layui-btn-sm" id="btnAddContent" lay-event="add">
            <i class="layui-icon layui-icon-add-1"></i> 添加内容 <i class="layui-icon layui-icon-down layui-font-12"></i>
        </button>
        <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="batchRemove">
            <i class="layui-icon layui-icon-delete"></i> 批量删除
        </button>
    </script>

    <script type="text/html" id="content-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="content-status-tpl">
        {{# if(d.status === 0){ }}
            <span class="layui-badge layui-bg-orange">草稿</span>
        {{# } else if(d.status === 1){ }}
            <span class="layui-badge layui-bg-green">已发布</span>
        {{# } else if(d.status === 2){ }}
            <span class="layui-badge">已下架</span>
        {{# } else { }}
            <span class="layui-badge layui-bg-gray">{{ d.status }}</span>
        {{# } }}
    </script>

    <script type="text/html" id="content-category-tpl">
        {{# if(d.category){ }}{{ d.category.name }}{{# } else { }}-{{# } }}
    </script>

    <script type="text/html" id="content-model-tpl">
        {{# if(d.model){ }}{{ d.model.name }}{{# } else { }}-{{# } }}
    </script>

    <script type="text/html" id="content-author-tpl">
        {{# if(d.user){ }}{{ d.user.name }}{{# } else { }}-{{# } }}
    </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);
                    });
                }
            }
        });

        var addCategoryMenuData = [];

        loadCategoryTree();

        function loadCategoryTree() {
            $.ajax({
                url: '/api/admin/content-categories/tree',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 0 && res.data) {
                        var options = '<option value="">全部分类</option>';
                        function buildOptions(items, level) {
                            if (!items || !items.length) return;
                            items.forEach(function(item) {
                                var prefix = '';
                                for (var i = 0; i < level; i++) prefix += '├─ ';
                                options += '<option value="' + item.id + '">' + prefix + item.name + '</option>';
                                if (item.children && item.children.length) {
                                    buildOptions(item.children, level + 1);
                                }
                            });
                        }
                        buildOptions(res.data, 0);
                        $('#searchCategoryId').html(options);
                        form.render('select');

                        addCategoryMenuData = buildAddMenuData(res.data, 0);
                    }
                }
            });
        }

        function buildAddMenuData(items, level) {
            var menu = [];
            if (!items || !items.length) return menu;
            items.forEach(function(item) {
                var prefix = '';
                for (var i = 0; i < level; i++) prefix += '├─ ';
                var hasModel = (item.model_alias || '') !== '';
                menu.push({
                    title: prefix + item.name,
                    id: 'cat_' + item.id,
                    categoryId: item.id,
                    modelAlias: item.model_alias || '',
                    modelName: item.model_name || '',
                    categoryName: item.name || '',
                    disabled: !hasModel
                });
                if (item.children && item.children.length) {
                    menu = menu.concat(buildAddMenuData(item.children, level + 1));
                }
            });
            return menu;
        }

        var cols = [[
            { type: 'checkbox', fixed: 'left' },
            { title: 'ID', field: 'id', align: 'center', width: 70, sort: true },
            { title: '标题', field: 'title', minWidth: 180 },
            { title: '分类', field: 'category.name', align: 'center', width: 120, sort: true, templet: '#content-category-tpl' },
            { title: '模型', field: 'model.name', align: 'center', width: 100, templet: '#content-model-tpl' },
            { title: '作者', field: 'user.name', align: 'center', width: 90, templet: '#content-author-tpl' },
            { title: '发布时间', field: 'create_time', align: 'center', width: 170, sort: true },
            { title: '浏览', field: 'pv', align: 'center', width: 80, sort: true },
            { title: '状态', field: 'status', align: 'center', width: 100, templet: '#content-status-tpl' },
            { title: '操作', toolbar: '#content-bar', align: 'center', width: 100, fixed: 'right' }
        ]];

        var inst = table.render({
            elem: '#content-table',
            url: '/api/admin/contents',
            page: {
                layout: ['count', 'prev', 'page', 'next', 'limit'],
                groups: 5,
                limit: 20,
                limits: [10, 20, 50, 100]
            },
            cols: cols,
            skin: false,
            toolbar: '#content-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(content-query)', function(data) {
            table.reload('content-table', { where: data.field, page: { curr: 1 } });
            return false;
        });

        table.on('toolbar(content-table)', function(obj) {
            if (obj.event === 'add') {
                if (addCategoryMenuData.length === 0) {
                    layer.msg('分类数据加载中，请稍后再试', { icon: 3, time: 1000 });
                    return;
                }
                dropdown.render({
                    elem: '#btnAddContent',
                    show: true,
                    data: addCategoryMenuData,
                    click: function(menudata) {
                        if (!menudata.modelAlias) {
                            layer.msg('该分类未绑定模型，请选择其他分类', { icon: 5 });
                            return;
                        }
                        layer.open({
                            type: 2,
                            title: '添加内容' + (menudata.categoryName ? ' - ' + menudata.categoryName : '') + (menudata.modelName ? '（' + menudata.modelName + '）' : ''),
                            maxmin: true,
                            success: function(layero, idx) {
                                layer.full(idx);
                            },
                            shade: 0.1,
                            area: ['90vw', '90vh'],
                            content: '/admin/content/form?category_id=' + menudata.categoryId + '&model_alias=' + menudata.modelAlias
                        });
                    }
                });
            } else if (obj.event === 'refresh') {
                table.reload('content-table');
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj);
            }
        });

        table.on('tool(' + inst.config.id + ')', function(obj) {
            if (obj.event === 'more') {
                dropdown.render({
                    elem: this,
                    show: true,
                    align: 'right',
                    data: [
                        { title: '编辑', id: 'edit' },
                        { title: '删除', id: 'del' }
                    ],
                    click: function(menudata) {
                        if (menudata.id === 'edit') {
                            window.edit(obj);
                        } else if (menudata.id === 'del') {
                            window.remove(obj);
                        }
                    }
                });
            }
        });


        window.edit = function(obj) {
            layer.open({
                type: 2,
                title: '编辑内容：' + obj.data.title,
                maxmin: true,
                success: function(layero, idx) {
                    layer.full(idx);
                },
                shade: 0.1,
                area: ['90vw', '90vh'],
                content: '/admin/content/form?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/contents/' + 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('content-table');
                            });
                        } else {
                            layer.msg(res.message || '删除失败', { icon: 2, time: 1000 });
                        }
                    },
                    error: function() {
                        layer.close(loading);
                        layer.msg('请求失败', { icon: 2, time: 1000 });
                    }
                });
            });
        };

        window.batchRemove = function(obj) {
            var checkData = table.checkStatus('content-table').data;
            if (checkData.length === 0) {
                layer.msg('未选中数据', { icon: 3, time: 1000 });
                return false;
            }
            var ids = checkData.map(function(item) { return item.id; });
            layer.confirm('确定要删除选中的 ' + ids.length + ' 条内容？删除后无法恢复！', {
                icon: 3,
                title: '操作提示',
                btn: ['确定', '取消']
            }, function(index) {
                layer.close(index);
                var loading = layer.load();
                $.ajax({
                    url: '/api/admin/contents/batch',
                    type: 'DELETE',
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify({ ids: ids }),
                    success: function(res) {
                        layer.close(loading);
                        if (res.code === 0) {
                            layer.msg('删除成功', { icon: 1, time: 1000 }, function() {
                                table.reload('content-table');
                            });
                        } else {
                            layer.msg(res.message || '删除失败', { icon: 2, time: 1000 });
                        }
                    },
                    error: function() {
                        layer.close(loading);
                        layer.msg('请求失败', { icon: 2, time: 1000 });
                    }
                });
            });
        };
    });
</script>
</body>
</html>
