<template>
  <TreeSelect
    v-model="deptId"
    style="width: 230px;"
    :data="treeData"
    :show-checkbox="!!multi"
    :includeNonLeaf="1"
    :placeholder="'请选择地区' || placeholder"
    size="small"
    :formatter="[(x) => multi ? x.join(',') : x, (x) => multi ? x.split(',') : x]"
    :is-leaf="(data) => !data.children"
    value-name="id"
    treeKey="id"
    :filterNodeMethod="FilterSubject"
    :clearable="true"
  >
  </TreeSelect>
</template>

<script>
import TreeSelect from "@/components/common/TreeSelect";
import {deptTreeSelect} from "@/api/system/user";

export default {
  name: "DeptInput",
  props: ['options', 'value', 'placeholder', 'multi' ],
  components: {TreeSelect, },
  data() {
    return {
      treeData: [],
      deptId: this.value,
    };
  },
  methods: {
    OnSelected(node) {
      if(node.disabled)
      {
        this.$nextTick(() => {
          this.deptId = null;
        });
      }
      else
        this.$emit('select', node);
    },
    GetRemoteData() {
      this.GetDeptTree();
    },
    GetDeptTree() {
      deptTreeSelect().then((res) => {
        this.treeData = res.data;
      });
    },
    InitData() {
      if(this.options)
        this.treeData = this.options;
      else
        this.GetRemoteData();
    },
    FilterSubject(x, data) {
      if(!x)
        return true;
      return data.label.indexOf(x) !== -1;
    },
  },
  created() {
    this.InitData(this.options);
  },
  watch: {
    options: function(newVal) {
      this.InitData();
    },
    deptId: function(newVal) {
      if(this.value != newVal)
        this.$emit('input', newVal);
    },
    value: function(newVal) {
      if(this.subjectId != newVal)
        this.deptId = newVal;
    },
  },
}
</script>

<style scoped lang="scss">
.fieldInput {
  ::v-deep .vue-treeselect__menu-container {
    width: 320px;
  }
}
</style>
