<template>
  <ul class="mc-tree">
    <li v-for="(item, index) in data" :key="item.key" :class="{'active': selectedKey === item.key}">
      <i :class="item.children && visible[index] ? iconCaretDown : iconCaretRight"
         v-if="item.children && item.children.length > 0"
         @click.stop="showChildrenHandler(item, index)"></i>
      <i v-else>&nbsp;</i>
      <label :class="{'disabled':item.disabled,'open':dataKeyMap[item.key][0]==='open','checked':dataKeyMap[item.key][0]==='checked'}"><input type="checkbox" :index="item.key" v-if="multiple" :value="item.key" :disabled="item.disabled" :checked="dataKeyMap[item.key][0]" @click="onItemChecked(item)"></label>
      <span class="title"
            @click="onItemClick(item)"
            @dblclick="onItemDblclick(item)">
        {{ item.title }}
      </span>
      <span class="tree-edit">
        <i class="mc-icon-delete" v-if="edited && (!item.children || item.children.length <= 0)" @click="itemRemoveHandler(item, index)"></i>
      </span>
      <mc-tree-node
          :data="item.children || []"
          :multiple="multiple"
          :edited="edited"
          :expand="expand"
          :selected-key="selectedKey"
          :data-key-map="dataKeyMap"
          :on-item-checked="onItemChecked"
          :on-item-dblclick="onItemDblclick"
          :on-item-click="onItemClick"
          v-if="item.children && visible[index]"></mc-tree-node>
    </li>
  </ul>
</template>
<script>
  export default {
    props: {
      selectedKey: { type: String, default: '' },
      multiple: { type: Boolean, default: false },
      expand: { type: Boolean, default: false },
      data: { type: Array, required: true }, // [{title: '', key: '', children: ''}]
      dataKeyMap: { type: Object }, 
      // {key: [state, [[key, state]]}
      edited: { type: Boolean, default: false },
      delimiter: { type: String, default: '-' },
      iconCaretRight: { type: String, default: 'mc-icon-triangle-right' },
      iconCaretDown: { type: String, default: 'mc-icon-triangle-down' },
      onItemChecked: { type: Function, default: (item) => {} },
      onItemDblclick: { type: Function, default: (item) => {} },
      onItemClick: { type: Function, default: (item) => {} }
    },
    data () {
      return {
        visible: this.data.map((ele) => this.expand)
      }
    },
    methods: {
      showChildrenHandler (item, index) {
        this.visible.splice(index, 1, !this.visible[index])
      },
      itemRemoveHandler (item, index) {
        this.data.splice(index, 1)
      }
    }
  }
</script>