<!-- 选择部门 -->
<template>
  <treeselect v-model="selected" :options="list" :show-count="true" :disabled="readonly" :placeholder="$t('form.placeholderSelect')" @input="handleChange" />
</template>

<script>
import Treeselect from "@riophae/vue-treeselect"
import { deptTreeSelect } from "@/api/system/user"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
export default {
  name: "SelectDept",
  components: {Treeselect},
  props: {
    value: {
      type: [Number, String , Array],
      default: null,
    },
    readonly: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    value: {
      immediate: true,
      handler(v) {
        this.selected = v ? parseInt(v) : null
      }
    },
  },
  data() {
    return {
      selected: null,
      list: [],
    };
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.list = []
      deptTreeSelect().then(response => {
        this.list = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
      })
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    handleChange(val) {
      this.$emit('input', val || '')
      this.$emit('change', val || '')
    },
  }
};
</script>
