<template>
  <div v-if="!treeData.length">
    <section class="section">
      <div class="content has-text-grey has-text-centered">
        <p>
          <b-icon
            icon="frown"
            size="is-large"
          />
        </p>
        <p>데이터가 없습니다.</p>
      </div>
    </section>
  </div>
  <div v-else>
    <l-tree
      v-if="!loading"
      :data="nestedData"
      @node:selected="onNodeSelected"
    />
    <b-loading
      :is-full-page="false"
      :active.sync="loading"
      :can-cancel="false"
    />
  </div>
</template>

<script>
import LiquorTree from 'liquor-tree';

export default {
  components: {
    lTree: LiquorTree,
  },
  props: {
    treeData: Array,
    treeSetting: Object,
    expanded: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      nestedData: {},
    };
  },
  watch: {
    treeData(newVal) {
      this.loading = true;
      this.nestedData = this.getNestedData(newVal);
      this.loading = false;
    },
  },
  methods: {
    getNestedData(dataList) {
      const tree = [];
      const mappedArr = {};
      let mappedElem = {};
      const temp = {};
      dataList.forEach((row) => {
        temp.data = row;
        temp[this._props.treeSetting.key] = row[this._props.treeSetting.key];
        temp[this._props.treeSetting.parent] = row[this._props.treeSetting.parent];
        temp.text = row[this._props.treeSetting.text];
        temp.state = { expanded: this._props.expanded };
        temp.children = [];
        mappedArr[row[this._props.treeSetting.key]] = JSON.parse(JSON.stringify(temp));
      });

      for (const key in mappedArr) {
        if (mappedArr.hasOwnProperty(key)) {
          mappedElem = mappedArr[key];

          if (mappedElem[this._props.treeSetting.parent]) {
            mappedArr[mappedElem[this._props.treeSetting.parent]].children.push(mappedElem);
          } else {
            tree.push(mappedElem);
          }
        }
      }
      return tree;
    },
    onNodeSelected(node) {
      if (node.states.expanded === false) {
        node.states.expanded = true;
      }
      this.$emit('select', node.data);
    },
  },
};
</script>
