<template>
  <!--表单组件-->
  <el-dialog class="sort-dialog" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body title="排序" :visible.sync="sortVisible" @opened="opened">
    <div class="setting-dialog">
      <i class="drag-tip">提示：使用鼠标拖动调整顺序</i>
      <el-table :data="sortTableData" :tree-props="{children: 'childrens'}" class="category-sort" style="width: 100%;" :max-height="tableHeight" row-key="id">
        <el-table-column type="index" label="序号" width="100" align="center" />
        <el-table-column prop="cnName" label="门类名称" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="sortVisible = false">取消</el-button>
        <el-button type="primary" @click.native="handleSort">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import Sortable from 'sortablejs'
import { sort } from '@/api/system/fileLibrary/fileLibrary'

export default {
  data() {
    return {
      sortVisible: false,
      sortTableData: [],
      tableHeight: 0
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight * 0.6
    })
  },
  methods: {
    // 行拖拽
    rowDrop(className, targetName) {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.' + className + ' .el-table__body-wrapper tbody')
      const that = this
      Sortable.create(tbody, {
        // 指定父元素下可被拖拽的子元素
        draggable: '.el-table__row',
        onEnd({ newIndex, oldIndex }) {
          if (newIndex === oldIndex) return
          that[targetName].splice(newIndex, 0, that[targetName].splice(oldIndex, 1)[0])
        }
      })
    },
    opened() {
      this.rowDrop('category-sort', 'sortTableData')
    },
    handleSort() {
      const data = this.sortTableData.map((value, index) => {
        return { id: value.id, categorySeq: index + 1 }
      })
      this.sortTableData.forEach((item, index) => {
        item.categorySeq = index + 1
      })
      sort(data).then(() => {
        this.sortVisible = false
        this.$message({
          message: '保存成功',
          type: 'success',
          duration: 2500
        })
        this.$emit('treeNodeSort', this.sortTableData)
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
