<!-- 组织树选择器 -->
<!-- change方法输出对象 { deptId, deptName } -->
<!--
<DeptSelect v-model="searchParams.deptId" search-mode />
<DeptSelect v-model.trim="formData.deptName" @change="Object.assign(formData, $event)" />
-->
<template>
  <el-select
    ref="deptSelector"
    v-bind="$attrs"
    filterable
    :value="value"
    :filter-method="filterCloud"
    @input="$emit('input', $event)"
    @focus="filterCloud()"
    @change="handleSelectChange"
  >
    <el-option value="" hidden />
    <el-option v-if="searchMode" value="" label="全部" />
    <el-option v-if="!searchMode && dept" label="作为一级组织" value="0" />
    <el-tree
      ref="tree"
      :data="deptList"
      :props="{ children: 'children', label: 'name' }"
      :expand-on-click-node="false"
      :check-on-click-node="true"
      :filter-node-method="filterNode"
      accordion
      node-key="id"
      placeholder="请选择组织"
      empty-text="暂无数据"
      filterable
      @node-click="handleNodeClick"
    />
  </el-select>
</template>
<script>
import { getDeptTree } from '@/apiV2/dept'

export default {
  name: 'DeptSelect',
  props: {
    value: {
      type: String,
      default: ''
    },
    searchMode: {
      type: Boolean,
      default: false
    },
    dept: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      deptList: []
    }
  },
  mounted() {
    this.getOptions()
  },
  methods: {
    filterNode(value, data) {
      if (!value) {
        return true
      }
      return data.name.indexOf(value) !== -1
    },
    filterCloud(e) {
      this.$refs.tree.filter(e)
    },
    handleSelectChange(e) {
      if (e === '0') {
        this.handleNodeClick({ id: 0, name: '作为一级组织' })
      }
      if (e === '' && this.searchMode) {
        this.handleNodeClick({ id: '', name: '' })
      }
    },
    handleNodeClick(e) {
      this.$emit('change', { deptId: e.id, deptName: e.name })
      this.$emit('input', e.name)
      this.$forceUpdate()
      this.$refs.deptSelector.blur()
    },
    async getOptions() {
      const res = await getDeptTree()
      if (res.success) {
        this.deptList = res.data.filter(item => item.status === 1)
      }
    }
  }
}
</script>
<style lang="scss">

</style>
