<?php defined('EM_ROOT') || exit('access denied!'); ?>

<div style="padding: 20px 0px;">
    <table class="layui-hide" id="index" lay-filter="index"></table>


</div>
<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="refresh">
            刷新
        </button>
        <button id="toolbar-del" class="layui-btn layui-btn-sm layui-bg-red layui-btn-disabled" lay-event="del">
            删除
        </button>
    </div>
</script>
<script type="text/html" id="money">
    <div class="layui-clear-space">
        <a href="javascript:;" style="color: #16baaa;" data-id="{{ d.uid }}" lay-event="money">{{ d.money }}</a>
    </div>
</script>
<script type="text/html" id="operate">
    <div class="layui-clear-space">
        <a class="layui-btn" lay-event="edit">编辑</a>
        <a class="layui-btn layui-bg-red" lay-event="del">删除</a>
    </div>
</script>
<script type="text/html" id="show">
    <input type="checkbox" name="{{= d.id }}" value="{{= d.id }}" title=" ON |OFF " lay-skin="switch" lay-filter="switch" {{= d.hide == 'n' ? "checked" : "" }}>
</script>
<div>
    <div class="layui-row layui-col-space15">

        <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
            <div class="layui-card">
                <div class="layui-card-header">添加自定义导航</div>
                <div class="layui-card-body">
                    <form class="layui-form">
                        <div style="" id="open-box">
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <input type="text" placeholder="导航名称" name="naviname" class="layui-input" value="">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <input type="text" placeholder="导航网址" name="url" class="layui-input" value="">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <input type="checkbox" value="y" name="newtab" title="新窗口打开" lay-skin="tag">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <select name="pid">
                                        <option value="">上级导航</option>
                                        <?php
                                        foreach ($navis as $key => $value):
                                            if ($value['type'] != Navi_Model::navitype_custom || $value['pid'] != 0) {
                                                continue;
                                            }
                                            ?>
                                            <option value="<?= $value['id'] ?>"><?= $value['naviname'] ?></option>
                                        <?php endforeach ?>
                                    </select>
                                </div>
                            </div>

                            <input name="token" id="token" value="<?= LoginAuth::genToken() ?>" type="hidden"/>
                        </div>
                        <div class="layui-input-block" style="margin: 0 auto;">
                            <button data-action="?action=add_ajax" type="submit" class="layui-btn" lay-submit lay-filter="submit">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
            <div class="layui-card">
                <div class="layui-card-header">添加商品分类到导航</div>
                <div class="layui-card-body">
                    <form class="layui-form">
                        <div style="" id="open-box">
                            <div class="layui-form-item">

                                <?php foreach ($sorts as $key => $value):
                                        if ($value['pid'] != 0) {
                                            continue;
                                        }
                            ?>
                                    <div class="layui-input-block">
                                        <input type="checkbox" name="sort_ids[]" value="<?= $value['sid'] ?>">
                                        <div lay-checkbox><?= $value['sortname'] ?></div>
                                    </div>
                            <?php
                            $children = $value['children'];
                            foreach ($children as $key):
                                $value = $sorts[$key];
                                ?>
                                <div class="layui-input-block">
                                    &nbsp; &nbsp; &nbsp; <input type="checkbox" name="sort_ids[]" value="<?= $value['sid'] ?>">
                                    <div lay-checkbox><?= $value['sortname'] ?></div>
                                </div>
                            <?php
                            endforeach;
                        endforeach;
                        ?>
                            </div>
                            <input name="token" id="token" value="<?= LoginAuth::genToken() ?>" type="hidden"/>
                        </div>
                        <div class="layui-input-block" style="margin: 0 auto;">
                            <button data-action="?action=add_sort" type="submit" class="layui-btn" lay-submit lay-filter="submit">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
            <div class="layui-card">
                <div class="layui-card-header">添加文章分类到导航</div>
                <div class="layui-card-body">
                    <form class="layui-form">
                        <div style="" id="open-box">
                            <div class="layui-form-item">

                                <?php foreach ($blog_sorts as $key => $value):
                                    if ($value['pid'] != 0) {
                                        continue;
                                    }
                                    ?>
                                    <div class="layui-input-block">
                                        <input type="checkbox" name="sort_ids[]" value="<?= $value['sid'] ?>">
                                        <div lay-checkbox><?= $value['sortname'] ?></div>
                                    </div>
                                    <?php
                                    $children = $value['children'];
                                    foreach ($children as $key):
                                        $value = $blog_sorts[$key];
                                        ?>
                                        <div class="layui-input-block">
                                            &nbsp; &nbsp; &nbsp; <input type="checkbox" name="sort_ids[]" value="<?= $value['sid'] ?>">
                                            <div lay-checkbox><?= $value['sortname'] ?></div>
                                        </div>
                                    <?php
                                    endforeach;
                                endforeach;
                                ?>
                            </div>
                            <input name="token" id="token" value="<?= LoginAuth::genToken() ?>" type="hidden"/>
                        </div>
                        <div class="layui-input-block" style="margin: 0 auto;">
                            <button data-action="?action=add_blogsort" type="submit" class="layui-btn" lay-submit lay-filter="submit">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
            <div class="layui-card">
                <div class="layui-card-header">添加页面到导航</div>
                <div class="layui-card-body">
                    <form class="layui-form">
                        <div style="" id="open-box">
                            <div class="layui-form-item">

                                <?php
                                if ($pages):
                                    foreach ($pages as $key => $value):
                                        ?>
                                        <div class="layui-input-block">
                                            <input type="checkbox" name="pages[<?= $value['gid'] ?>]" value="<?= $value['title'] ?>">
                                            <div lay-checkbox><?= $value['title'] ?></div>
                                        </div>
                                    <?php endforeach ?>
                                <?php else: ?>
                                    <div class="form-group">还没页面，<a href="page.php?action=new">新建页面</a></div>
                                <?php endif ?>

                            </div>
                            <input name="token" id="token" value="<?= LoginAuth::genToken() ?>" type="hidden"/>
                        </div>
                        <div class="layui-input-block" style="margin: 0 auto;">
                            <button data-action="?action=add_page" type="submit" class="layui-btn" lay-submit lay-filter="submit">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>


<script>
    layui.use(function(){
        var $ = layui.$;
        var treeTable = layui.treeTable;
        var form = layui.form;
        // 创建渲染实例
        window.table = treeTable.render({
            elem: '#index',
            autoSort: false,
            url: '?action=index', // 此处为静态模拟数据，实际使用时需换成真实接口
            tree: {
                customName: {
                    children: 'children',
                    pid: 'pid',
                    name: 'naviname',
                    icon: null
                },
                view: {
                    showIcon: false,
                    expandAllDefault: true
                }

            },
            toolbar: '#toolbar',
            limits: [10,20,30,50,100],
            page: false,
            defaultToolbar: ['filter', 'exports', 'print'],


            cols: [[
                {type: 'checkbox'},
                {field:'naviname', title: '导航名称', minWidth: 130},
                {field:'type_name', title:'类型', minWidth: 170},
                {field:'url', title:'地址', minWidth: 100},
                {field:'show', title:'显示', minWidth: 100, templet: '#show'},
                {field:'taxis', title:'排序', minWidth: 100},
                {title:'操作', templet: '#operate', width: 140}
            ]],

            error: function(res, msg){
                console.log(res, msg)
            }
        });

        // 状态 - 开关操作
        form.on('switch(switch)', function(obj){
            var active = obj.elem.checked == true ? 'show' : 'hide';
            var id = this.name;
            var loadSwitch = layer.load(2);
            $.ajax({
                url: '?action=' + active,
                type: 'POST',
                dataType: 'json',
                data: { id: id, token: '<?= LoginAuth::genToken() ?>' },
                success: function(res) {
                    layer.msg('操作成功');
                },
                error: function(err) {
                    layer.msg(err.responseJSON.msg);
                },
                complete: function() {
                    layer.close(loadSwitch);
                }
            });
        });

        form.on('submit(submit)', function(data){
            var field = data.field; // 获取表单全部字段值
            $.ajax({
                type: "POST",
                url: $(this).data('action'),
                data: field,
                dataType: "json",
                success: function (e) {
                    parent.layer.msg('操作成功');
                    window.table.reload();
                },
                error: function (xhr) {
                    layer.msg(JSON.parse(xhr.responseText).msg);
                }
            });
            return false; // 阻止默认 form 跳转
        });

        // 搜索提交
        form.on('submit(index-search)', function(data){
            var field = data.field; // 获得表单字段
            // 执行搜索重载
            treeTable.reload('index', {
                page: {
                    curr: 1 // 重新从第 1 页开始
                },
                where: field // 搜索的字段
            });
            return false; // 阻止默认 form 跳转
        });


        // 工具栏事件
        treeTable.on('toolbar(index)', function(obj){
            var id = obj.config.id;
            var checkStatus = treeTable.checkStatus(id);
            var othis = lay(this);
            switch(obj.event){
                case 'refresh':
                    treeTable.reload(id);
                    break;
                case 'del':
                    var data = checkStatus.data;
                    if(data.length == 0){
                        break;
                    }
                    var ids = $.map(data, function(item) {
                        return item.id; // 提取每个对象的uid
                    }).join(',');
                    layer.confirm('确定要删除选中的数据吗？', {
                        btn: ['确认', '取消'], // 按钮
                        icon: 3,             // 图标，3表示问号
                        title: '温馨提示'
                    }, function(index) {
                        layer.close(index); // 关闭对话框
                        $.ajax({
                            url: '?action=del',
                            type: 'POST',
                            dataType: 'json',
                            data: { ids: ids, token: '<?= LoginAuth::genToken() ?>' },
                            success: function(res) {
                                layer.msg('删除成功');
                                treeTable.reload(id);
                            },
                            error: function(err) {
                                layer.msg(err.responseJSON.msg);
                            }
                        });
                    });
                    break;
            };
        });

        // 触发单元格工具事件
        treeTable.on('tool(index)', function(obj){ // 双击 toolDouble
            var data = obj.data; // 获得当前行数据
            var id = obj.config.id;
            if(obj.event == 'del'){
                layer.confirm('确定删除？', {
                    btn: ['确认', '取消'], // 按钮
                    icon: 3,             // 图标，3表示问号
                    title: '温馨提示'
                }, function(index) {
                    layer.close(index); // 关闭对话框
                    $.ajax({
                        url: '?action=del',
                        type: 'POST',
                        dataType: 'json',
                        data: { ids: data.id, token: '<?= LoginAuth::genToken() ?>' },
                        success: function(res) {
                            layer.msg('删除成功');
                            treeTable.reload(id);
                        },
                        error: function(err) {
                            layer.msg(err.responseJSON.msg);
                        }
                    });
                });
            }

            if(obj.event === 'edit'){
                let isMobile = window.innerWidth < 768;
                let area = isMobile ? ['98%', 'auto']  : ['700px', 'auto'];
                layer.open({
                    id: 'edit',
                    title: '编辑',
                    type: 2,
                    area: area,
                    // skin: 'layui-layer-win10',
                    skin: 'layui-layer-molv',
                    content: '?action=edit&id=' + data.id,
                    fixed: false, // 不固定
                    maxmin: true,
                    shadeClose: true,
                    success: function(layero, index, that){
                        layer.iframeAuto(index); // 让 iframe 高度自适应
                        that.offset(); // 重新自适应弹层坐标
                    }
                });
            }
            if(obj.event === 'money'){
                let isMobile = window.innerWidth < 768;
                let area = isMobile ? ['98%', 'auto']  : ['500px', 'auto'];
                layer.open({
                    id: 'money',
                    title: '调整用户余额',
                    type: 2,
                    area: area,
                    // skin: 'layui-layer-win10',
                    skin: 'layui-layer-molv',
                    content: 'user.php?action=money&uid=' + data.uid,
                    fixed: false, // 不固定
                    maxmin: true,
                    shadeClose: true,
                    success: function(layero, index, that){
                        layer.iframeAuto(index); // 让 iframe 高度自适应
                        that.offset(); // 重新自适应弹层坐标
                    }
                });
            }
        });

        // 触发排序事件
        treeTable.on('sort(index)', function(obj){
            console.log(obj.field); // 当前排序的字段名
            console.log(obj.type); // 当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
            console.log(this); // 当前排序的 th 对象

            // 尽管我们的 table 自带排序功能，但并没有请求服务端。
            // 有些时候，你可能需要根据当前排序的字段，重新向后端发送请求，从而实现服务端排序，如：
            treeTable.reload('index', {
                initSort: obj, // 记录初始排序，如果不设的话，将无法标记表头的排序状态。
                where: { // 请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    field: obj.field, // 排序字段
                    order: obj.type // 排序方式
                }
            });
        });

        // 触发表格复选框选择
        treeTable.on('checkbox(index)', function(obj){
            var id = obj.config.id;
            var checkData = treeTable.checkStatus(id).data;
            console.log(checkData)
            if(checkData.length == 0){
                $('#toolbar-del').addClass('layui-btn-disabled');
            }else{
                $('#toolbar-del').removeClass('layui-btn-disabled');
            }
        });

        // 分页栏事件
        treeTable.on('pagebar(index)', function(obj){
            alert()
            console.log(obj); // 查看对象所有成员
            console.log(obj.config); // 当前实例的配置信息
            console.log(obj.event); // 属性 lay-event 对应的值
        });


        // 表头自定义元素工具事件 --- 2.8.8+
        treeTable.on('colTool(test)', function(obj){
            var event = obj.event;
            console.log(obj);
            if(event === 'email-tips'){
                layer.alert(layui.util.escape(JSON.stringify(obj.col)), {
                    title: '当前列属性选项'
                });
            }
        });


    });
</script>





<script>
    $(function () {
        $("#menu-appearance").attr('class', 'admin-menu-item has-list in');
        $("#menu-appearance .fa-angle-right").attr('class', 'admin-arrow fa fa-angle-right active');
        $("#menu-appearance > .submenu").css('display', 'block');
        $('#menu-navi > a').attr('class', 'menu-link active')
    });
</script>
