<template>
  <div
    :class="[
      'select-orgs part-box part-box-pad part-box-border',
      { 'select-orgs-disabled': disabled }
    ]"
  >
    <el-tree
      :data="orgs"
      show-checkbox
      default-expand-all
      node-key="id"
      ref="MenuTree"
      :props="defaultProps"
      check-strictly
      check-on-click-node
      :expand-on-click-node="false"
      @check="checkClick"
      @check-change="checkChange"
    >
    </el-tree>
  </div>
</template>

<script>
import { organizationList } from "../api";

export default {
  name: "select-orgs",
  props: {
    value: {
      type: Array,
      default() {
        return [];
      }
    },
    multiple: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectedOrgs: [],
      // orgs: [],
      orgs: [],
      defaultProps: {
        label: "name"
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    value(val, oldVal) {
      if (val.join() !== oldVal.join()) this.setCheckedNode(val);
    }
  },
  methods: {
    async getList() {
      this.orgs = await organizationList();

      this.$nextTick(() => {
        this.setCheckedNode(this.value);
      });
    },
    setCheckedNode(selectedIds) {
      const selectedOrgs = this.$refs.MenuTree.getCheckedKeys();
      if (selectedOrgs.join() === selectedIds.join()) return;

      this.$refs.MenuTree.setCheckedKeys(selectedIds);
    },
    checkChange() {
      if (!this.multiple) return;
      const selectedOrgs = this.$refs.MenuTree.getCheckedKeys();
      this.emitChange(selectedOrgs);
    },
    checkClick(data) {
      if (this.multiple) return;

      const checkedIds = this.$refs.MenuTree.getCheckedKeys();
      console.log(checkedIds);
      console.log(data.id);
      if (!checkedIds.includes(data.id)) {
        this.emitChange([]);
        return;
      }
      const selectedOrgs = [data.id];
      this.$refs.MenuTree.setCheckedKeys([data.id]);
      this.emitChange(selectedOrgs);
    },
    emitChange(vals) {
      this.$emit("input", vals);
      this.$emit("change", vals);
    }
  }
};
</script>
