<template>
  <el-tree
    ref="selectDeptTree"
    :load="loadChildDeptTree"
    :props="deptTreeProps"
    highlight-current
    :expand-on-click-node="false"
    node-key="deptId"
    :default-expanded-keys="orgTreeDefaultExpandedKeys"
    lazy
    @node-click="handleOrgTreeClick"
  />
</template>
<script>
import { DeptUserService } from './api.js'
const deptUserService = new DeptUserService()
export default {
  name: 'Ff',
  props: {
    deptId: {
      type: String,
      default: ''
    },
    deptName: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean
    }
  },
  data() {
    return {
      deptTreeProps: {
        children: 'children',
        label: 'deptName',
        isLeaf: 'leaf'
      },
      orgTreeDefaultExpandedKeys: []
    }
  },
  methods: {
    // 加载子树数据的方法，仅当 lazy 属性为true 时生效
    loadChildDeptTree(node, resolve) {
      const _self = this
      // level = 0 加载根节点
      let pId = 0
      if (node.level !== 0) {
        pId = node.data.deptId
      }
      deptUserService.loadDeptData(pId).then(res => {
        const { data } = res.data
        // 展开根节点
        if (node.level === 0) {
          _self.orgTreeDefaultExpandedKeys = [data[0].deptId]
        }
        resolve(data)
      })
    },
    // 点击节点触发的事件
    handleOrgTreeClick(data, node, $vm) {
      const _self = this
      _self.$emit('update:deptId', data.deptId)
      _self.$emit('update:deptName', data.deptName)
      _self.$emit('update:visible', false)
    }
  }
}
</script>

