<template>
  <div id="dict-tree">
    <el-input
      v-model="treeFilterText"
      placeholder="输入关键字进行过滤"
      clearable
    />
    <!-- <el-scrollbar wrap-class="scrollbar-wrapper" :style="{ height: height }"> -->
    <el-tree
      ref="tree"
      style="margin-top: 5px"
      class="filter-tree"
      default-expand-all
      :props="treeProps"
      :filter-node-method="filterTree"
      :load="loadTreeNode"
      :highlight-current="true"
      :expand-on-click-node="false"
      lazy
      @node-click="nodeClick"
    >
      <span slot-scope="{ data }" class="custom-tree-node">
        <el-tooltip
          :content="data.name"
          placement="right"
          effect="light"
          transition
        >
          <span>{{ data.name.substring(0, 10) }}</span>
        </el-tooltip>
      </span>
    </el-tree>
    <!-- </el-scrollbar> -->
  </div>
</template>

<script>
import * as dictApi from '@/api/dict'

export default {
  props: {
    height: {
      type: String,
      default: 'calc(100vh - 220px)'
    }
  },
  data() {
    return {
      treeFilterText: '',
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'hasChildren'
      }
    }
  },
  watch: {
    treeFilterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    filterTree(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    loadTreeNode(node, resolve) {
      if (node.level === 0) {
        dictApi.getList().then(res => {
          // 构建树型结构
          var roots = res.filter(t => t.parentCode === null)
          roots.forEach(t => this.makeTree(res, t))
          return resolve(roots)
        })
      } else {
        return resolve(node.data.children || [])
      }
    },
    makeTree(list, parent) {
      var prentCode = parent ? parent.code : null
      var children = list.filter(t => t.parentCode === prentCode)
      parent.hasChildren = children.length
      parent.children = children
      parent.children.forEach(t => {
        this.makeTree(list, t)
      })
    },
    nodeClick(data, node) {
      this.$emit('node-click', data, node)
    }
  }
}
</script>
