<template>
  <div class="wrapper">
    <p class="no-data" v-if="data.length === 0">暂无数据</p>
    <div v-else>
      <p class="title" @click="handleTitleClick">{{nodes[props.label]}}</p>
      <ul class="first-stage">
        <time-tree-node :node="node" :props="props" :first="true" :active="active" v-for="node in nodes" :key="node[props.key]"></time-tree-node>
      </ul>
    </div>
  </div>
</template>

<script>
import TimeTreeNode from './TimeTreeNode.vue'

export default {
  name: 'TimeTree',
  componentName: 'TimeTree',
  components: {
    'time-tree-node': TimeTreeNode
  },
  props: {
    data: {
      type: Array,
      required: false
    },
    props: {
      type: Object,
      default: function () {
        return {
          children: 'children',
          label: 'name',
          key: 'ID'
        }
      }
    },
    nodeActive: {
      type: [String, Number],
      default: ''
    },
    lazy: {
      type: Function
    }
  },
  data () {
    return {
      active: this.nodeActive
    }
  },
  created () {
    if (!this.data) {
      this.data = []
    }
    if (this.currid) {

    }
    this.$on('node-click', node => {
      const key = node[this.props.key]
      this.active = key
      this.$emit('current-change', node)
    })
  },
  computed: {
    nodes () {
      if (this.data.length) {
        return this.data
      }
      return {}
    }
  },
  watch: {
    nodeActive(val) {
      if (val) {
        this.active = val
      }
    }
  },
  methods: {
    setCurrentNode (id) {
      this.active = id
    },
    handleTitleClick () {
      this.active = this.nodes[this.props.key]
      this.$emit('current-change', this.nodes)
    },
    async handleLazy (parentNode) {
      if (!this.lazy) {
        return []
      }

      const childNodes = await this.lazy(parentNode)

      parentNode[this.props.children] = childNodes

      return true
    }
  }

}
</script>

<style scoped>
  .wrapper {
    padding: 0 10px;
    font-size: 16px;
  }
  .wrapper ul {
    list-style: none;
    padding-left: 22px;
  }
  .wrapper ul.first-stage {
    padding-left: 0;
  }
  .wrapper .no-data {
    text-align: center;
    color: #ccc;
    font-size: 14px;
    line-height: 40px;
  }
  .wrapper .title {
    font-size: 16px;
    font-weight: 700;
    line-height: 50px;
    color: #424242;
    cursor: pointer;

  }
</style>
