<template>
  <table class="n-tbody">
    <n-table-colgroup :columns="columns"></n-table-colgroup>
    <tbody>
      <template v-for="(data, index) in dataList">
        <n-table-line :key="index" :columns="columns" :data="data" :data-id="sortableKey && data[sortableKey]" :index="index" :class-index="classIndex"
                      @on-line-click="onLineClick" @on-cell-click="onCellClick"></n-table-line>
      </template>
    </tbody>
  </table>
</template>

<script>
import NTableColgroup from './colgroup'
import NTableLine from './line'
import {loadSortable, toString} from '@uif/next/lib/utils/tools'
export default {
  name: 'n-table-body',
  components: {
    NTableColgroup,
    NTableLine
  },
  props: {
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    dataList: {
      type: Array,
      default () {
        return []
      }
    },
    // 列表样式（下标）
    classIndex: {
      type: Object,
      default () {
        return {}
      }
    },
    sortable: {
      type: Boolean,
      default: false
    },
    sortableOptions: {
      type: Object,
      default: null
    },
    sortableKey: {
      type: String,
      default: 'id'
    }
  },
  data () {
    return {
    }
  },
  mounted () {
    this.updateSortable()
  },
  beforeDestroy () {
    this.destroySortable()
  },
  methods: {
    onLineClick (event, data, index) {
      this.$emit('on-line-click', event, data, index)
    },
    onCellClick (event, data, index, column) {
      this.$emit('on-cell-click', event, data, index, column)
    },
    /**
     * 拖拽排序
     * **/
    updateSortable () {
      if (this.sortable) {
        this.destroySortable()
        loadSortable().then(Sortable => {
          this.$sortable = new Sortable(this.$el.querySelector('tbody'),
            Object.assign({
              animation: 150,
              onEnd: (event) => this.$emit('u-sortable', {event, instance: this})
            }, this.sortableOptions))
        })
      }
    },
    // 销毁
    destroySortable () {
      if (this.sortable && this.$sortable) {
        this.$sortable.destroy()
        this.$sortable = null
      }
    },
    // 完成
    doneSortable () {
      return this.$sortable.toArray().map(id => this.dataList.find(data => toString(data[this.sortableKey]) === id))
    }
  }
}
</script>
