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

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

export default {
  name: "DeptTreeSelect",
  components: { Treeselect },
  props: {
    value: {
      type: String,
      default: null,
    },
    placeholder: {
      type: String,
      default: '选择运营商'
    }
  },
  data() {
    return {
      deptOptions: [],
    }
  },
  computed: {
    computedValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
        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) {
      console.log('data', data)
      this.$emit('select', data)
    }
  }
}

</script>
