<template>
  <ul class="uif-sort">
    <li class="uif-sort-item" v-for="data in dataList" :key="data[idKey]" :data-id="data[idKey]"><slot v-bind="data"></slot></li>
  </ul>
</template>
<script>
import {loadSortable} from '@uif/admin/lib/utils/load'
import {map} from '@uif/hq/lib/utils/array'
import {toString} from '@uif/hq/lib/utils/format'

export default {
  name: 'u-sort-list',
  props: {
    value: {
      type: Boolean,
      default: true
    },
    dataList: {
      type: Array,
      default () {
        return []
      }
    },
    idKey: {
      type: String,
      default: 'value'
    },
    handle: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      sortable: null
    }
  },
  computed: {
  },
  watch: {
    value () {
      this.handleChange()
    },
    dataList () {
      this.handleChange()
    }
  },
  mounted () {
    this.handleChange()
  },
  methods: {
    // 切换
    handleChange () {
      this.value ? this.update() : this.destroy()
    },
    // 排序 创建
    update () {
      this.destroy()
      loadSortable().then(Sortable => {
        this.sortable = new Sortable(this.$el, {
          animation: 150,
          handle: this.handle,
          onEnd: (evt) => {
            this.$emit('change', evt)
          }
        })
      })
    },
    // 排序 销毁
    destroy () {
      if (this.sortable) {
        this.sortable.destroy()
      }
      this.sortable = null
    },
    // 完成
    done () {
      const array = this.sortable.toArray()
      return map(array, id => this.dataList.find(data => toString(data[this.idKey]) === id))
    }
  },
  beforeDestroy () {
    this.destroy()
  }
}
</script>
