<!--
@name: 部门组件-template写法
@author: 张泽贤
@time: 2022-07-13
@doc:
-->
<template>
  <a-tree-select
    v-model="value"
    show-search
    style="width: 100%"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    :tree-data="treeData"
    :replaceFields="{ key: 'id', title: 'name', value: 'code' }"
    placeholder="请选择部门"
    allow-clear
    :filterTreeNode="filterTreeNode"
    :tree-default-expanded-keys="treeDefaultExpandedKeys"
    :disabled="disabled"
    @change="departmenTreeChange"
  >
    <a-icon slot="suffixIcon" theme="filled" type="folder" />
  </a-tree-select>
</template>

<script>
import { axios } from '@/utils/request'
import { SERVICE_PLATFORM_POWER_BASE } from '@/config/serviceSettings.js'
const PinyinMatch = require('pinyin-match').default

export default {
  props: {
    departmentCode: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    departmentCode(v) {
      this.value = v
    },
  },
  data() {
    return {
      treeData: [],
      treeDefaultExpandedKeys: [],
      value: '',
    }
  },
  mounted() {
    axios.get(SERVICE_PLATFORM_POWER_BASE + '/organization/all').then((res) => {
      this.treeData = this.resultTreeNodes(res.data)
      let item = this.treeData.find((item) => item.parentId == '0')
      this.treeDefaultExpandedKeys = item?[item.id]:[]
      this.value=this.departmentCode

    })
  },
  methods: {
    resultTreeNodes(data, map = {}) {
      if (!data) return []
      data.forEach((item) => {
        delete item.children
        item.scopedSlots = { icon: 'custom' }
        item.isLeaf = !!item.isLeaf

        map[item.id] = item
      })
      let value = []

      data.forEach((item) => {
        var p = map[item.parentId]
        if (p) {
          if (!p.children) {
            p.children = []
          }
          //item.isLeaf = true
          p.children.push(item)
        } else {
          value.push(item)
        }
      })
      return value
    },
    filterTreeNode(inputValue, treeNode) {
      return PinyinMatch.match(treeNode.data.props.title, inputValue).length > 0 && treeNode
    },
    departmenTreeChange(value, label, extra) {
      if (!value) {
        this.$emit('getDepartment', { departmentId: '', departmentCode: '', departmentName: '' })
      } else {
        this.$emit('getDepartment', { departmentId: extra.triggerNode.eventKey, departmentCode: value, departmentName: label[0] })
      }
    },
  },
}
</script>