<template>
  <div id="project-section-tree">
    <el-input v-model="treeFilterText" placeholder="输入关键字进行过滤" clearable />
    <el-tree
      ref="tree"
      :value="value"
      style="margin-top:5px;"
      class="filter-tree"
      :props="treeProps"
      :filter-node-method="filterTree"
      :load="loadTreeNode"
      :highlight-current="true"
      lazy
      @input="$emit('input', $event)"
      @node-click="nodeClick"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <el-tag v-if="node.level === 1" size="mini">项目</el-tag>
        <el-tag v-if="node.level > 1" size="mini" type="success">标段</el-tag>
        <el-tooltip :content="data.name" placement="right" effect="light" transition>
          <span>{{ data.name }}</span>
        </el-tooltip>
      </span>
    </el-tree>
  </div>
</template>

<script>
import * as projectApi from '@/api/backbone/project'
import * as sectionApi from '@/api/backbone/section'

export default {
  props: {
    value: {
      type: String,
      default: null
    },
    height: {
      type: String,
      default: 'calc(100vh - 220px)'
    }
  },
  data() {
    return {
      treeFilterText: '',
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'isSection'
      }
    }
  },
  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) {
        projectApi.lookupAll().then(projects => {
          projects.forEach(t => {
            t.isProject = true
            t.name = t.shortName || t.name
          })
          return resolve(projects)
        })
      } else {
        if (node.data.isProject) {
          sectionApi.lookupConstructions(node.data.id).then(res => {
            res.forEach(t => {
              t.isSection = true
            })
            return resolve(res)
          })
        } else {
          return resolve([])
        }
      }
    },
    nodeClick(data, node) {
      this.$emit('node-click', data, node)
    }
  }
}
</script>
