<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <script th:fragment="indexJS">
    var prevHash = '';
    layui.use(['table', 'dropdown'], function(){
      const query = Admin.getQueryParams();
      var table = layui.table,
      dropdown = layui.dropdown,
      opt = {
        RELEASED:{text:'通过', opColor: 'op-blue', layColor: 'blue', fa: 'check'},
        WAITING: {text:'待审', opColor: 'op-yellow', layColor: 'orange', fa: 'search'},
        SPAM:    {text:'垃圾', opColor: 'op-brown', layColor: 'red', fa: 'poop'}},
      renderData = function (d) {
        var o = [], s = [];
        $.each(opt, function (i, v) {
            var cs = d.commentStatus, icon = `<i class="fa fa-fw fa-${v.fa}"></i>`;
            if (cs == i) {
                s.push(`<span class="layui-badge layui-bg-${v.layColor}">${icon}${v.text}</span>`)
            }
            else {
                o.push(`<a href="#" class="${v.opColor} op-status" op="${i}">${icon}${v.text}</a>`);
            }
        });
        d.op = o.join('');
        d.cs = s.join('');
        return d;
      },
      updateStatus = function (data) {
        $.ajax({
          url: '/admin/v2/comment/batchOp',
          method: 'POST',
          data: data,
          success: function () {
            layer.msg((data.ids.length == 1?'':'批量') + '操作成功', {
              offset: '15px', icon: 1, time: 1000 },  function() {
                window.dispatchEvent(new PopStateEvent('popstate'));
              }
            )
          },
          error: function (res) {var r = res.responseJSON;
            layer.msg(r && r.data || '服务器错误', {offset: '15px', icon: 2, time: 2000});
            return
          }
        });
      },
      updateBtnGroup = function (q) {
        if (q.commentStatus) {
          $.each($('a.comment-status'), (i, v) => {
            v = $(v);
            if (v.data('status') == q.commentStatus) {
              v.removeClass('layui-btn-primary')
            }
            else {
              v.addClass('layui-btn-primary')
            }
          });
        }
        else {
          $('a.comment-status:first').removeClass('layui-btn-primary')
        }
      }
      updateBtnGroup(query);
      window.addEventListener('popstate', function () {
        const q = Admin.getQueryParams();
        table.reload('comments',  {
          where: Admin.buildWhereFromQuery(),
          page: Admin.buildPaginateFromQuery()
        });
        updateBtnGroup(q);
      });
      
      function renderBatchOpDropdown() {
          var data = [];
          $.each(opt, function(i, v){
            if ($(`[status="${i}"]`).hasClass('layui-btn-primary')) {
            	var icon = `<i class="fa fa-fw fa-${v.fa}"></i>`;
                data.push({
                	title: `<span class="${v.opColor}">
                	   <i class="fa fa-fw fa-${v.fa}"></i>${v.text}</span>`, op: i
            	});
            }
          });
          data.push({title: '<span class="op-red"><i class="fa fa-fw fa-trash"></i>删除</span>', op: void 0})
          if (!window._batchDropdown) {
              window._batchDropdown = dropdown.render({
                elem: '.operdown',
                data: data,
                click: function (data, othis){
                    var checked = layui.table.checkStatus('comments'), commentIds = [];
                    if (!checked.data.length) {
                        layui.layer.msg('未选中任何项', {time: 1000});
                        return;
                    }
                    $.each(checked.data, function (i, comment){
                        commentIds.push(comment.id);
                    });
                    updateStatus({
                      ids: commentIds,
                      op: data.op
                    });
                }
              });
          }
          else {
          	window._batchDropdown.reload({data:data});
          }
          
      }
      renderBatchOpDropdown();
      function resizeTable() {
      	var totalWidth = $('#comments').width(), maxWidth = 200;
      	$.each( $('[data-field="3"]'), function (i, elem){
      		elem = $(elem);
      		var width = (function(){
      			var width = 0;
      			$.each(elem.siblings(), function (j, v) {
      				width += $(v).width();
      			})
      			return width;
      		})();
      		elem.css('width', Math.max(maxWidth, totalWidth - width) + 'px');
      		elem.find('.laytable-cell-1-0-3').css('width', Math.max(maxWidth, totalWidth - width) - 2 + 'px');
      	}) 
      }
      let hash = location.hash.slice(1), hasHash = hash !== undefined && hash != null && hash.trim() != '';
      if (hasHash) {
          var that = $(`[href="#${hash}"]`);
          that.removeClass('layui-btn-primary').siblings().addClass('layui-btn-primary');
          renderBatchOpDropdown();
          resizeTable();
      }
      table.render({
        elem: '#comments',
        url: './comment/list',
        page: Admin.buildPaginateFromQuery(),
        id:'comments', 
        skin:'line',
        where: Admin.buildWhereFromQuery(),
        cols: [ [
          {type:'checkbox'},
          {width: '20%', minWidth:'120px', unresize: true, templet:'#authorTpl'},
          {unresize: true, templet:'#commentTpl'}
        ]],
        parseData: function (data) {
            $.each(data.data, function (i, row) {
                row.contentDisplay = row.content.replace(/</g, '&lt;');
                row.authorDisplay = row.author.replace(/</g, '&lt;');
                data.data[i] = renderData(row);
            })
            return data;
        },
        done: function (res, curr, count) {
        	resizeTable();
        	Admin.updateQueryParams({
            ...Admin.getQueryParams(),
            page: curr,
            limit: res.limit
          }, true);
        }
      });
      $('body').on('click', 'a.comment-status[data-status]', function (e) {
        e.preventDefault();
        Admin.updateQueryParams({commentStatus: $(this).data('status')}, false);
        window.dispatchEvent(new PopStateEvent('popstate'));
        return false;
      });
      $('body').on('click', '.comment-action a', function (e) {
          e.preventDefault();
          var that = $(this), op = that.attr('op'), id = that.parent().attr('data-id');
          if (that.hasClass('op-status')) {
              updateStatus({ids:[id], op:op});
          }
          else {
          	var row = layui.table.getData('comments')[that.parents('tr:first').attr('data-index')];
          	switch (op) {
          	case 'edit':
          		layui.layer.open({
                      type: 1,
                      title: '编辑评论',
                      btn: ['提交', '关闭'],
                      yes: function(index, layero) {
                          layero.find('[lay-filter="editComment"]').click();
                      },
                      area: [window.innerWidth > 450 ? '450px' :
                           window.innerWidth - 5 + 'px', '450px'],
                      content: $('#editComment').html(),
                      success: function (layero, layerIndex) {
                          console.log(arguments);
                          $('#editCommentForm [name="id"]').val(row.id);
                          $('#editCommentForm [name="author"]').val(row.author);
                          $('#editCommentForm [name="email"]').val(row.email);
                          $('#editCommentForm [name="url"]').val(row.url);
                          $('#editCommentForm [name="content"]').text(row.content).focus();
                          $('#editCommentForm [name="markdown"]').prop('checked', row.markdown);
                          layui.form.on('submit(editComment)', function (data) {
                              
                              $.each($('#editCommentForm').find('input[type="checkbox"]'), function (i, v) {
                                  v = $(v);
                                  data.field[v.attr('name')] = v.prop('checked');
                              });
                              
                              $.ajax({
                                  url: '/admin/v2/comment/update',
                                  method: 'POST',
                                  data: data.field,
                                  success: function () {
                                      layui.layer.close(layerIndex);
                                      window.dispatchEvent(new PopStateEvent('popstate'));
                                      layer.msg('编辑评论成功', {
                                          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();
                      }
                  });
          		break;
          	case 'reply':
          		layui.layer.open({
                      type: 1,
                      title: '回复评论',
                      btn: ['提交', '关闭'],
                      yes: function(index, layero) {
                          layero.find('[lay-filter="replyComment"]').click();
                      },
                      area: [window.innerWidth > 450 ? '450px' :
                           window.innerWidth - 5 + 'px', '450px'],
                      content: $('#replyComment').html(),
                      success: function (layero, layerIndex) {
                      	$(layero).find('[name="content"]').css('height', '280px');
                      	$(layero).find('[name="id"]').val(row.id);
                          layui.form.on('submit(replyComment)', function (data) {
                              $.each($('#replyComment').find('input[type="checkbox"]'), function (i, v) {
                                  v = $(v);
                                  data.field[v.attr('name')] = v.prop('checked');
                              });
                              
                              $.ajax({
                                  url: '/admin/v2/comment/reply',
                                  method: 'POST',
                                  data: data.field,
                                  success: function (r) {
                                      layui.layer.close(layerIndex);
                                      window.dispatchEvent(new PopStateEvent('popstate'));
                                      layer.msg(r && r.data || '回复成功', {
                                          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();
                      }
                  });
          		break;
          	default:
          		layui.layer.msg(op,{time:1000})
          	}
              
          }
      }).on('click', '.op-ban', function (e){
      	e.preventDefault();
          var that = $(this);
          $.ajax({
              url: '/admin/v2/comment/block',
              method: 'POST',
              data: (function(){
              	var a = {}; return a[that.attr('op')] = that.attr('ban'), a;
              })(),
              success: function (r) {
                  layer.msg(r && r.data || '封禁成功', {
                      offset: '15px',
                      icon: 1,
                      time: 2500
                  })
              },
              error: function (res) {
                  var r = res.responseJSON;
                  layer.msg(r && r.data || '服务器错误', {
                      offset: '15px',
                      icon: 2,
                      time: 2000
                  });
              }
          })
      });
    })
    </script>
</html>