<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head th:replace="~{admin/include::head}">
    </head>
    
    <body style="background-color: #f2f2f2">
        <ul th:replace="~{admin/include::nav}"></ul>
        
        <div class="manage-body">
            <div>
            <h2 class="manage-title"><b>分类管理</b><a href="#" class="operate">新增</a></h2>
            
            </div>
            <button class="layui-btn layui-btn-sm operdown">
                <span>选中项<i class="layui-icon layui-icon-sm layui-icon-triangle-d"></i></span>
            </button>
            <div>
                <table class="layui-table" id="categories" lay-filter="categories"></table>
            </div>
        </div>
        <div th:replace="~{admin/include::feet}"></div>
        <script type="text/html" id="postTpl">
            {{# if (d.postCount) { }}
            <a href="/admin/v2/post/?categoryId={{d.mid}}" target="_blank">
                <span class="layui-badge layui-bg-cyan">{{d.postCount}}</span>
            </a>
            {{# } }}
        </script>
        <div type="text/html" id="toolbar" style="display:none" >
            <div class="layui-btn-container">
                <a class="layui-btn layui-btn-xs" lay-event="add"> <i class="layui-icon layui-icon-add-1"></i>新增子项</a>
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
            </div>
        </div>
        <input type="hidden" name="unfolded"/>
        <script type="text/html" id="chooseCategory">
            <div style="padding: 0 10px">
                <table class="layui-table" id="categoriesForChoose" lay-filter="categoriesForChoose"></table>
            </div>
            <div class="layui-form" style="margin:10px 15px" id="chooseCategoryForm" lay-filter="chooseCategoryForm">
                <div style="display:none" class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="submitCategory">提交</button>
                    </div>
                </div>
            </div>
        </script>
        <script type="text/html" id="editCategory">
            <div class="layui-form" style="margin:10px 15px" id="editCategoryForm" lay-filter="editCategoryForm">
                <div class="layui-form-item">
                    <input type="hidden" name="mid"/>
                    <input type="hidden" name="parentId" value="0"/>
                    <input type="hidden" name="type" value="CATEGORY"/>
                    <label class="layui-form-label">名称</label>
                    <div class="layui-input-block">
                        <input type="text" lay-verify="required" name="name" placeholder="" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">排序号</label>
                    <div class="layui-input-block">
                        <input type="text" lay-verify="required|number" name="no" placeholder="" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">友好名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="friendlyName" placeholder="" autocomplete="off" class="layui-input">
                        <div class="layui-form-mid layui-word-aux">
                        用于生成友好连接时的名称，若留空，默认以分类名称小写填充，但不允许与其他分类的友好名称重复
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">描述</label>
                    <div class="layui-input-block">
                        <textarea type="text" name="description" placeholder="" autocomplete="off" class="layui-textarea"></textarea>
                        <div class="layui-form-mid layui-word-aux">
                        分类描述，可能用在某些地方的提示性描述
                        </div>
                    </div>
                </div>
                <div style="display:none" class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="editCategory">提交</button>
                    </div>
                </div>
            </div>
        </script>
        <th:block th:replace="~{admin/include::head-script}"></th:block>
        <script>
            layui
            .config({base: '/admin/layuiadmin/lib/'})
            .use(['table', 'dropdown', 'layer', 'treeTable1'], function(){
            	var dropdown = layui.dropdown, treeTable1 = layui.treeTable1, laypage = layui.laypage;
            	var getRenderOpt = function (forChoose) {
                    var opt = {
                        elem: !forChoose ? '#categories' : '#categoriesForChoose',
                        url: './category/list',
                        request: {
                            pidName: 'parentId'
                        },
                        page: true, skin:'line',
                        tree: {
                            iconIndex: 3, // 折叠图标显示在第几列
                            isPidData: false, // 是否是id、pid形式数据
                            idName: 'id', // id字段名称
                            pidName: 'parentId', // pid字段名称
                            haveChildName: 'hasChildren',
                            openName: 'spread',
                            checkMode: {
                                indeterminate: false,
                                fullUncheck: {
                                    parentToChildren: false,
                                    childrenToParent: false
                                },
                                fullCheck: {
                                    parentToChildren: false,
                                    childrenToParent: false
                                }
                            }
                        },
                        cols: [ [
                            {type: !forChoose ? 'checkbox' : 'radio'},
                            {field: 'postCount', width: 58, templet:'#postTpl', title: '文章'},
                            {field: 'mid',title: '编号',hide: true},
                            {field: 'name',title: '分类名称',minWidth: 140},
                            {field: 'friendlyName',title: '友好名称'},
                            {field: 'no', width: 60, title: '排序'}]]
                    };
                    if (!forChoose)
                        opt.cols[0].push({title: '操作',toolbar: '#toolbar',width: 230,fixed: 'right'});
                    return opt;
                }
            	
                var categoryTable = treeTable1.render(getRenderOpt());
                
                function addOrEdit(row, isEdit) {
                    var opName = isEdit ? `编辑 ${row.name} 分类` : row ? `新增 ${row.name} 下的分类` : '新增分类';
                    layui.layer.open({
                        type: 1,
                        title: opName,
                        btn: ['提交', '关闭'],
                        yes: function(index, layero) {
                            layero.find('[lay-filter="editCategory"]').click();
                        },
                        area: ['500px', '500px'],
                        content: $('#editCategory').html(),
                        success: function (layero, layerIndex) {
                            if (row) {
                                if (isEdit) {
                                    $('#editCategoryForm [name="parentId"]').val(row.parentId);
                                    $('#editCategoryForm [name="mid"]').val(row.mid);
                                    $('#editCategoryForm [name="name"]').val(row.name);
                                    $('#editCategoryForm [name="no"]').val(row.no);
                                    $('#editCategoryForm [name="friendlyName"]').val(row.friendlyName);
                                    $('#editCategoryForm [name="description"]').val(row.description);
                                }
                                else {
                                    $('#editCategoryForm [name="parentId"]').val(row.id);
                                }
                            }
                            layui.form.on('submit(editCategory)', function (data) {
                                $.ajax({
                                    url: '/admin/v2/category/update',
                                    method: 'POST',
                                    data: data.field,
                                    success: function () {
                                        layui.layer.close(layerIndex);
                                        layui.treeTable1.reload('categories', {});
                                        layer.msg(opName + '成功', {
                                            offset: '15px',
                                            icon: 1,
                                            time: 1000
                                        })
                                    },
                                    error: function (res) {
                                        var r = res.responseJSON;
                                        layer.msg(r && r.data || '服务器错误', {
                                            offset: '15px',
                                            icon: 2,
                                            time: 2000
                                        });
                                    }
                                })
                            });
                            layui.form.render();
                        }
                    });
                }
                
                $('.operate').on('click', function (){
                    addOrEdit();
                    return false;
                });
                
                treeTable1.on('tool(categories)', function (rowObj){
                    console.log(rowObj)
                    if (rowObj.event != 'del')
                        addOrEdit(rowObj.data, rowObj.event == 'edit')
                    else {
                        layui.layer.confirm(`确认删除 ${rowObj.data.name} 吗？${rowObj.data.hasChildren?'其下所有子分类都会一并删除':''}`, function (index){
                            layer.close(index);
                            $.ajax({
                                url: '/admin/v2/category/delete',
                                method: 'POST',
                                data: {
                                    id: rowObj.data.id
                                },
                                success: function () {
                                    layer.msg('删除成功',
                                        {offset: '15px', icon: 1, time: 1000}, 
                                        function() {layui.treeTable1.reload('categories', {});})
                                },
                                error: function (res) {
                                    var r = res.responseJSON;
                                    layer.msg(r&&r.data||'服务器错误', 
                                        {offset: '15px', icon: 2, time: 2000});
                                    return
                                }
                            });
                        });
                    }
                });
                treeTable1.on('fold(categories)', function (rowObj){
                	var el = $('[name=unfolded]'), unfolded = el.val().split(','),
                	    id = rowObj.data.mid + '', index = unfolded.indexOf(id);
                	if (el.val().trim() == '') {
                		unfolded = [];
                	}
                	if (rowObj.folded && index > -1) {
                		unfolded.splice(index, 1);
                	}
                	else if (!rowObj.folded && index == -1) {
                		unfolded.push(id);
                		unfolded.sort();
                	}
                	el.val(unfolded.join(','));
                	categoryTable.options.where['unfolded[]'] = el.val();
                });
            	dropdown.render({
            	    elem: '.operdown',
            	    data: [
            	    	{title: '删除', op: null},
            	    	{title: '移动', op: 'move'},
                    {title: '移动至顶级', op: 'moveToTop'}],
            	    click: function (data, othis) {
            	    	var checked = categoryTable.checkStatus(), categoryIds = [], op = data.op,
            	    	    doAjax = function (data, callback) {
                            $.ajax({
                                url: '/admin/v2/category/batchOp',
                                method: 'POST', data: data,
                                success: function (res) {
                                    layer.msg('批量操作成功', 
                                        {offset: '15px', icon: 1, time: 1000}, 
                                        function() {layui.treeTable1.reload('categories', {});});
                                    return callback && typeof callback === 'function' && callback(res);
                                  },
                                  error: function (res) {
                                      var r = res.responseJSON;
                                      layer.msg(r && r.data || '服务器错误', 
                                          {offset: '15px', icon: 2, time: 2000});
                                      return callback && typeof callback === 'function' && callback(r);
                                  }
                              })
                          };
            	    	if (!checked.length) {
            	    		 layui.layer.msg('未选中任何项', {time: 1000});
            	    		 return;
            	    	}
            	    	$.each(checked, function (i, category){
            	    		 categoryIds.push(category.id);
            	    	});
            	    	
            	    	if (op == 'move') {
            	    	  layui.layer.open({
            	    	    type: 1,
            	    	    title: '选择要移动至的分类',
            	    	    btn: ['提交', '关闭'],
            	    	    yes: function(index, layero) {
            	    	      layero.find('[lay-filter="submitCategory"]').click();
          	    	      },
          	    	      area: ['500px', '500px'],
          	    	      content: $('#chooseCategory').html(),
          	    	      success: function (layero, layerIndex) {
          	    	        var categoryTableForChoose = treeTable1.render(getRenderOpt(true));
          	    	        layui.form.on('submit(submitCategory)', function (data) {
          	    	          var choosen = categoryTableForChoose.checkStatus();
          	    	            if (!choosen.length) {
          	    	              layui.layer.msg('未选中任何项', {time: 1000});
          	    	              return;
          	    	            }
          	    	            doAjax({
          	    	              ids: categoryIds,
          	    	                op: op,
        	    	                  to: choosen[0].id
    	    	                  }, function (){layui.layer.close(layerIndex)});
        	    	          });
                          layui.form.render();
                        }
                      });
                    }
                    else {
                      doAjax({ids: categoryIds, op: op});
                    }
            	    }
        	    });
            })
        </script>
    </body>

</html>