<template>
  <div>
    <a-input-search style="margin-bottom: 8px" placeholder="输入关键字搜索" @change="filterNode" />
    <a-tree
      show-line
      :expanded-keys="expandedKeys"
      :auto-expand-parent="autoExpandParent"
      :tree-data="orgNodes"
      :replaceFields="replaceFields"
      @select="handleNodeClick"
      @expand="onExpand"
    />
  </div>
</template>
<script>
import { treeselect } from '@/api/system/org'

const getParentKey = (value, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some((item) => item.value === value)) {
        parentKey = node.value
      } else if (getParentKey(value, node.children)) {
        parentKey = getParentKey(value, node.children)
      }
    }
  }
  return parentKey
}
export default {
  name: 'OrgTree',
  props: {
    orgOptions: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      replaceFields: { children: 'children', title: 'label', key: 'value', value: 'value' },
      orgNodes: [],
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
    }
  },
  methods: {
    // 筛选节点
    filterNode(e) {
      const searchValue = e.target.value
      if (searchValue) {
        const params = {
          orgName: searchValue,
        }
        treeselect(params).then((res) => {
          this.orgNodes = res.result
        })
      } else {
        this.orgNodes = [...this.orgOptions]
      }
      this.searchValue = searchValue
      this.autoExpandParent = true
    },
    // 节点单击事件
    handleNodeClick(keys, event) {
      this.$emit('select', keys[0])
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
  },
  watch: {
    orgOptions(newVal) {
      this.orgNodes = [...newVal]
    },
  },
}
</script>
