<template>
  <ul class="n-sort-list">
    <li class="n-sort-item" v-for="data in dataList" :key="data[idKey]" :data-id="data[idKey]"><slot v-bind="data"></slot></li>
  </ul>
</template>
<script>
import {prop, loadSortable, toString} from '@uif/next/lib/utils/tools'

export default {
  name: 'n-sort-list',
  props: {
    // 是否启用拖拽
    value: prop.boolean(true),
    // 数据列表
    dataList: prop.array(),
    // 指定数据id
    idKey: prop.string('id'),
    // 指定拖拽节点
    handle: prop.string(null),
    // Sortable参数
    options: prop.object()
  },
  watch: {
    value () {
      this.updateSortable()
    },
    dataList () {
      this.updateSortable()
    }
  },
  mounted () {
    this.updateSortable()
  },
  beforeDestroy () {
    this.destroy()
  },
  methods: {
    // 切换
    updateSortable () {
      this.value ? this.update() : this.destroy()
    },
    // 排序 创建
    update () {
      this.destroy()
      loadSortable().then(Sortable => {
        this.sortable = new Sortable(this.$el, Object.assign({
          animation: 150,
          handle: this.handle,
          onEnd: (event) => this.$emit('u-change', {event, instance: this})
        }, this.options))
      })
    },
    // 排序 销毁
    destroy () {
      if (this.sortable) {
        this.sortable.destroy()
      }
      this.sortable = null
    },
    // 完成
    done () {
      return this.sortable.toArray().map(id => this.dataList.find(data => toString(data[this.idKey]) === id))
    }
  }
}
</script>
