<template>
  <treeselect
    v-model="computedValue"
    :options="deptOptions"
    :normalizer="normalizer"
    :placeholder="placeholder"
    :disabled="disabled"
    @select="onSelect"
  />
</template>

<script>
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { isDeepEqual } from '@/utils'

export default {
  name: "DeptTreeSelect",
  components: { Treeselect },
  props: {
    value: {
      type: String,
      default: null,
    },
    placeholder: {
      type: String,
      default: '选择运营商'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      deptOptions: [],
    }
  },
  computed: {
    computedValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
        if (!isDeepEqual(val, this.value)) {
          this.$emit('change', val);
        }
      }
    }
  },
  created() {
    this.getDeptTree();
  },
  methods: {
    getDeptTree() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 转换运营商数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    onSelect(data) {
      this.$emit('select', data)
    }
  }
}

</script>
