<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head th:replace="~{admin/include::head}">
    </head>
    <style>
        .mov-active, .mov-active:hover {
            background: #fff4d6!important;
            transition: all 1s ease-in-out;
        }
    </style>
    <body style="background-color: #f2f2f2">
        <ul th:replace="~{admin/include::nav}"></ul>
        
        <div class="manage-body">
            <div>
            <h2 class="manage-title"><b th:text="${manageTitle}">Wiki 页面列表</b><a href="./edit" 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="posts" lay-filter="posts">
                </table>
            </div>
        </div>
        <script type="text/html" id="choosePost">
            <div style="padding: 0 10px">
                <table class="layui-table" id="postsForChoose" lay-filter="postsForChoose"></table>
            </div>
            <div class="layui-form" style="margin:10px 15px" id="choosePostForm" lay-filter="choosePostForm">
                <div style="display:none" class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="submitPost">提交</button>
                    </div>
                </div>
            </div>
        </script>
        <div th:replace="~{admin/include::feet}"></div>
        <script type="text/html" id="commentTpl">
            <a href="/admin/v2/comment?postId={{d.postId}}">
                {{# if (d.commentCount > 0) { }}
                <span class="layui-badge layui-bg-cyan">{{d.commentCount}}</span>
                {{# } else { }}
                <span class="layui-badge layui-bg-cyan" style="opacity: .6;">{{d.commentCount}}</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" href="./edit?parentId={{d.postId}}"> <i class="layui-icon layui-icon-add-1"></i>新增子项</a>
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="up"><i class="layui-icon layui-icon-up"></i>上移</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="down"><i class="layui-icon layui-icon-down"></i>下移</a>
            </div>
        </div>
        <script type="text/html" id="titleTpl">
            <a href="./edit?postId={{d.postId}}" post-id="{{d.postId}}" title="编辑 {{d.postTitle}}">{{d.postTitle}}</a>
            {{# if (d.postStatus != '公开') { }}
            <span class="layui-badge 
            {{# if (d.postStatus == '草稿'){ }}
            badge-draft
            {{# }else if (d.postStatus == '隐藏'){ }}
            badge-hidden
            {{# }else if (d.postStatus == '私密'){ }}
            badge-private
            {{# } }}
            ">{{d.postStatus}}</span>
            {{# } }}
            {{# if (d.password != '') { }}
            <span class="layui-badge badge-encrypted" title="本文包含密码">加密</span>
            {{# } }}
            
            <a class="external-link" target="_blank" href="{{d.link}}" title="浏览 {{d.postTitle}}">
               <i class="fa fa-external-link-alt"></i>
            </a>
        </script>
        <th:block th:replace="~{admin/include::head-script}"></th:block>
        <script th:src="@{/blog/plugins/doghouse/js/doghouse.js}"></script>
        <script th:inline="javascript">
          layui
            .config({base: '/admin/layuiadmin/lib/'})
            .use(['table', 'dropdown', 'layer', 'treeTable1'], function(){
            const query = Admin.getQueryParams();
            var dropdown = layui.dropdown, treeTable1 = layui.treeTable1, laypage = layui.laypage,
          	getRenderOpt = function (forChoose) {
              var opt = {
                  elem: !forChoose ? '#posts':'#postsForChoose',
                  url:'./list', 
                  skin:'line',
                  page: Admin.buildPaginateFromQuery(),
                  request: {
                    pidName: 'parentId'
                  },
                  done: function (res, curr, count) {
                    Admin.updateQueryParams({
                      ...Admin.getQueryParams(),
                      page: curr,
                      limit: res.limit
                    }, true);
                  },
                  tree: {
                    iconIndex: 2, // 折叠图标显示在第几列
                    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:'commentCount', width:50, templet:'#commentTpl', title: '评论'},
                    {field:'postTitle', templet:'#titleTpl', title: '标题'},
                    {field:'no', minWidth: 20, width: 50, title: '排序号'},
                    {field:'createTime', minWidth:35, title: '时间'}
                  ]]
              };
              if (!forChoose)
                opt.cols[0].push({title: '操作',toolbar: '#toolbar',width: 230,fixed: 'right'});
              return opt;
            },
          	wikiTable = treeTable1.render(getRenderOpt());
            treeTable1.on('fold(posts)', function (r){
              var w = window.Doghole.Wiki, i = r.data.postId;
              if (r.folded) w.rm(i);
              else w.add(i);
            });
            treeTable1.on('tool(posts)', function(rowObj) {
              console.log(rowObj);
              var $this = $(this);
              if (rowObj.event != 'add') {
                if ($this.hasClass('layui-btn-disabled')) return false;
                $('[lay-event="up"], [lay-event="down"]').addClass('layui-btn-disabled');
                var up = rowObj.event == 'up';
                $.ajax({
                  url: '/admin/v2/wiki/reorder',
                  method: 'POST',
                  data: {
                    postId: rowObj.data.postId,
                    up: up
                  },
                  success: function (res) {
                    layui.treeTable1.reload('posts', {done: function(data) {
                      console.log(data);
                      var x = wikiTable.getComponents().$tBody.find(`[post-id="${res.data}"]:first`)
                      .closest('tr').addClass('mov-active');
                      setTimeout(function (){x.removeClass('mov-active')}, 2000);
                    }});
                    $('[lay-event="up"], [lay-event="down"]').removeClass('layui-btn-disabled');
                  },
                  error: function (res) {
                    var r = res.responseJSON;
                    layer.msg(r&&r.data||'服务器错误', 
                      {offset: '15px', icon: 2, time: 2000},
                      function(){
                        $('[lay-event="up"], [lay-event="down"]').removeClass('layui-btn-disabled');
                      });
                    return
                  }
                })
              }
            });
            window.addEventListener('popstate', function () {
              layui.treeTable1.reload('posts', {
                where: Admin.buildWhereFromQuery(),
                page: Admin.buildPaginateFromQuery()
              });
            });
          	dropdown.render({
          	    elem: '.operdown',
          	    data: [
          	    	{title: '删除'}, 
          	    	{title: '设为公开', postStatus: 'RELEASED'}, 
                  {title: '设为私密', postStatus: 'PRIVATE'},
                  {title: '设为草稿', postStatus: 'DRAFT'},
                  {title: '设为隐藏', postStatus: 'HIDDEN'},
                  {title: '移动...', to: null},
                  {title: '移动至顶级', to: -1}],
          	    click: function (data, othis){
          	    	var checked = wikiTable.checkStatus(), postIds = [],
          	    	postData = {},
          	    	doAjax = function (data, callback) {
                    $.ajax({
                      url: '/admin/v2/post/batchOp',
                      method: 'POST',
                      data: data,
                      success: function (res) {
                        layer.msg('批量操作成功', {offset: '15px', icon: 1, time: 1000}, 
                          function() {
                            window.dispatchEvent(new PopStateEvent('popstate'));
                          }
                        );
                        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(res);
                      }
                    })
                  };
          	    	if (!checked.length) {
          	    		layui.layer.msg('未选中任何项', {time: 1000});
          	    		return;
          	    	}
          	    	$.each(checked, function (i, post){
          	    		postIds.push(post.postId);
          	    	});
                  postData = $.extend(postData, data, {ids: postIds});
          	    	if (postData.to === null) {
                      layui.layer.open({
                        type: 1,
                        title: '选择要移动至的 Wiki',
                        btn: ['提交', '关闭'],
                        yes: function(index, layero) {
                          layero.find('[lay-filter="submitPost"]').click();
                        },
                        area: ['500px', '500px'],
                        content: $('#choosePost').html(),
                        success: function (layero, layerIndex) {
                          var postTableForChoose = treeTable1.render(getRenderOpt(true));
                          layui.form.on('submit(submitPost)', function (choosenData) {
                            var choosen = postTableForChoose.checkStatus();
                            if (!choosen.length) {
                              layui.layer.msg('未选中任何项', {time: 1000});
                              return;
                            }
                            postData.to = choosen[0].postId
                            doAjax(postData, function (){layui.layer.close(layerIndex)});
                          });
                          layui.form.render();
                        }
                    });
                  }
                  else {
                    doAjax(postData);
                  }
          	    }
      	    });
          })
        </script>
    </body>

</html>