<template>
  <div id="project-section-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"
      :props="treeProps"
      :filter-node-method="filterTree"
      :load="loadTreeNode"
      :highlight-current="true"
      lazy
      @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 === 2" size="mini" type="success">标段</el-tag>
        <el-tag v-if="node.level === 3" size="mini" type="danger">工区</el-tag>
        <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 projectApi from '@/api/backbone/project'
import * as sectionApi from '@/api/backbone/section'
import * as areaApi from '@/api/backbone/section-area'

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