<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"
      v-loading="loading"
      style="margin-top:5px;"
      class="filter-tree"
      :props="treeProps"
      :filter-node-method="filterTree"
      :data="treeData"
      :highlight-current="true"
      @node-click="nodeClick"
    >
      <span slot-scope="{ data }" class="custom-tree-node">
        <el-tag v-show="data.isProject" size="mini">项目</el-tag>
        <el-tag v-show="data.isCategory" type="success" size="mini">流程</el-tag>
        <el-tooltip :content="data.name" placement="right" effect="light" transition>
          <span>{{ data.name }}</span>
        </el-tooltip>
      </span>
    </el-tree>
    <!-- </el-scrollbar> -->
  </div>
</template>

<script>
import * as projectApi from '@/api/backbone/project'
import { getAuditFlowTypes } from '@/api/dict-entry'

export default {
  props: {
    height: {
      type: String,
      default: 'calc(100vh - 220px)'
    }
  },
  data() {
    return {
      loading: false,
      treeFilterText: '',
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'isCategory'
      }
    }
  },
  watch: {
    treeFilterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    filterTree(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    loadData() {
      this.loading = true
      getAuditFlowTypes().then(types => {
        projectApi.lookupAll().then(projects => {
          projects.forEach(t => {
            t.isProject = true
            t.name = t.shortName || t.name
            var children = types.map(af => {
              return { id: af.code, name: af.name }
            })
            children.forEach(r => {
              r.isCategory = true
              r.projectId = t.id
            })
            t.children = children
          })
          this.treeData = projects
          this.loading = false
        })
      })
    },
    nodeClick(data, node) {
      this.$emit('node-click', data, node)
    }
  }
}
</script>
