<template>
  <treeselect
    :value="value"
    :options="treeData"
    :normalizer="normalizerTreeNode"
    :load-options="loadTreeOptions"
    :allow-selecting-disabled-descendants="true"
    :disable-branch-nodes="true"
    loading-text="加载中..."
    no-options-text="没有选项"
    no-children-text="没有子项"
    no-results-text="没有搜索到结果"
    :placeholder="placeholder"
    @input="$emit('input', $event)"
    @select="selectTreeNode"
  >
    <label slot="option-label" slot-scope="{ node }">
      <el-tag
        v-show="node.raw.isProject"
        size="mini"
        type="primary"
      >项目</el-tag>
      <el-tag
        v-show="node.raw.isSection"
        size="mini"
        type="success"
      >标段</el-tag>
      {{ node.label }}
    </label>
  </treeselect>
</template>

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

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// LOAD_ROOT_OPTIONS
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

export default {
  components: { Treeselect },
  props: {
    value: {
      type: String,
      default: null
    },
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  data() {
    return {
      treeData: []
    }
  },
  created() {
    projectApi.lookupAll().then(projects => {
      projects.forEach(t => {
        t.isProject = true
        t.children = null
        t.name = t.shortName || t.name
      })
      this.$emit('project-loaded', projects)
      this.treeData = projects
    })
  },
  methods: {
    selectTreeNode(node) {
      this.$emit('select', node)
    },
    normalizerTreeNode(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    loadTreeOptions({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        if (parentNode.isProject) {
          // sectionApi.lookupAllByProject(parentNode.id).then(res => {
          sectionApi.lookupConstructions(parentNode.id).then(res => {
            res.forEach(t => {
              t.isSection = true
              t.parent = parentNode
            })
            parentNode.children = res
            callback()
          })
        }
      }
    }
  }
}
</script>
