<template>
  <div class="ipub-tree">
    <slot>
      <draggable v-if="draggable && deep===1"
                 v-model="dragData"
                 @update="drag"
                 handle=".ipub-draggable-icon">
        <ipub-tree-item :deep="deep"
                        @edit="edit"
                        @delete="del"
                        @drag="drag"
                        :actions="actions"
                        :border="border"
                        :draggable="draggable"
                        v-for="item in tree"
                        :key="item.id || item.name"
                        :item="item" />
      </draggable>
      <template v-else>
        <ipub-tree-item :deep="deep"
                        @edit="edit"
                        @delete="del"
                        @drag="drag"
                        :actions="actions"
                        :border="border"
                        :draggable="draggable"
                        v-for="item in tree"
                        :key="item.id || item.name"
                        :item="item" />
      </template>
    </slot>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import IpubTreeItem from './item'
export default {
  name: 'IpubTree',
  components: {
    IpubTreeItem, draggable
  },
  props: {
    tree: {
      type: Array,
      default () {
        return []
      },
    },
    deep: {
      type: Number,
      default: 0
    },
    draggable: {
      type: Boolean,
      default: true
    },
    border: Boolean,
    actions: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    tree: {
      handler (val) {
        this.dragData = JSON.parse(JSON.stringify(val))
      },
      immediate: true
    }
  },
  methods: {
    edit (e) {
      this.$emit('edit', e)
    },
    del (e) {
      this.$emit('delete', e)
    },
    add (e) {
      this.$emit('add', e)
    },
    drag (e) {
      if (this.deep === 1) {
        this.$emit('drag', this.dragData)
      } else {
        this.$emit('drag', e)
      }

    }
  }
}
</script>
