<!-- 选择部门 -->
<template>
  <treeselect v-model="selected" :options="list" :show-count="true" :disabled="readonly" :multiple="multiple" :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
    },
    multiple: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    value: {
      immediate: true,
      handler(v) {
        if (!this.multiple) {
          this.selected = v ? parseInt(v) : null
        } else {
          if (v) {
            //默认传的,分割的字符串，有传数组再改造
            debugger
            let arr = (v+'').split(',')
            let s = []
            _.forEach(arr, a => {
              s.push(parseInt(a))
            })
            this.selected = s
          } else {
            this.selected = []
          }
        }
      }
    },
  },
  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', this.multiple ? (val && val.length > 0 ? val.join(',') : '') : (val || ''))
      this.$emit('change', this.multiple ? (val && val.length > 0 ? val.join(',') : '') : (val || ''))
    },
  }
};
</script>
