<template>
  <treeselect
    v-model="computedValue"
    :options="deptOptions"
    :normalizer="normalizer"
    :placeholder="placeholder"
    :disabled="disabled"
    @select="onSelect"
    :style="{
      width: width
    }"
    :editable="false"
  />
</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
    },
    width: {
      type: String,
      default: '215px'
    }
  },
  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>
