<template>

  <el-row :gutter="20">
    <el-col :span="4" :xs="24">
      <DeptTree
        width="100%"
        :defaultKeys="defaultDeptId || []"
        v-model="internalDeptId"
        :showCheckbox="!!multiSelect"
        :includeNonLeaf="0"
        @input="handleQuery"
        @rawDataChanged="handleSelect"
      />
    </el-col>

    <el-col :span="20" :xs="24">
      <slot></slot>
    </el-col>
  </el-row>
</template>

<script>
import DeptTree from "@/components/common/DeptTree";
export default {
  name: "DeptTreeLayout",
  components: {DeptTree},
  props: ['value', 'defaultDeptId', 'multiSelect', 'deptName',],
  data() {
    return {
      internalDeptId: this.value,
    }
  },
  methods: {
    handleQuery() {
      this.$nextTick(() => {
        this.$emit('deptSelected', this.internalDeptId);
      })
    },
    handleSelect(unused, data) {
      this.$nextTick(() => {
        this.$emit('update:deptName', data.label);
        this.$emit('selected', data);
      })
    },
    compareValue(a, b) {
      if(Array.isArray(a) && Array.isArray(b))
      {
        return JSON.stringify(a) === JSON.stringify(b);
      }
      else if(!Array.isArray(a) && !Array.isArray(b))
        return a == b;
      else
        return false;
    },
  },
  watch: {
    internalDeptId: function(newVal, oldVal) {
      if(!this.compareValue(this.value, newVal))
        this.$emit('input', newVal);
    },
    value: function(newVal, oldVal) {
      if(!this.compareValue(this.internalDeptId, newVal))
        this.internalDeptId = newVal;
    }
  },
}
</script>

<style scoped>

</style>
