<template>
  <div class="lanaya-tree-view-item">
    <div class="lanaya-tree-view-item__text-box" :style="itemStyle">
      <div style="display: flex;">
        <div class="lanaya-tree-view-item__text-box__icon"
             @click="handleClickIcon"
             :class="{'is-leaf':!hasChildren(option), 'is-expand': option._expand}"></div>
        <p class="lanaya-tree-view-item__text-box__text">{{itemLabel}}</p>
      </div>
      <div class="lanaya-tree-view-item__text-box__btn-group" v-if="option.buttons">
        <l-button size="small" @click="handleClickButton(button)" v-for="(button, index) in option.buttons"
                  :key="index">
          {{button.label}}
        </l-button>
      </div>
    </div>
    <l-tree-view-item v-for="(item, index) in option.children"
                      v-if="hasChildren(option)"
                      v-show="option._expand"
                      :tree-entity="treeEntity"
                      :level="level + 1"
                      :key="index"
                      :format="format"
                      :option="item">
    </l-tree-view-item>
  </div>
</template>
<script>
import LButton from './../button/Button';

export default {
  name: 'LTreeViewItem',
  components: {
    LButton
  },
  props: {
    treeEntity: null,
    level: Number,
    option: Object,
    format: Object
  },
  methods: {
    handleClickButton (button) {
      button.click && typeof button.click === 'function' && button.click.call(this.treeEntity, this.option);
    },
    handleClickIcon () {
      if (this.option.children && this.option.children.length > 0) {
        this.option._expand = !this.option._expand;
      }
    }
  },
  computed: {
    itemLabel () {
      return this.option[this.format.label];
    },
    itemStyle () {
      return {
        'padding-left': `${10 * this.level}px`,
        'margin-left': `-${10 * this.level}px`
      };
    },
    hasChildren () {
      return function (item) {
        return item.children && item.children.length > 0;
      };
    }
  }
};
</script>
