<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="checkStrictly"
      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,
    },
    checkStrictly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      selectedOrgs: [],
      // orgs: [],
      orgs: [],
      leafOrgIds: [],
      defaultProps: {
        label: "name",
      },
    };
  },
  created() {
    this.getList();
  },
  watch: {
    value(val, oldVal) {
      if (val.join() !== oldVal.join()) this.setCheckedNode(val);
    },
  },
  methods: {
    async getList() {
      const orgs = await organizationList();
      this.orgs = orgs || [];

      if (this.orgs.length) {
        this.orgs[0].children.sort((a, b) => {
          if (a.type === "PRINTING_HOUSE") return 1;
          if (b.type === "PRINTING_HOUSE") return -1;

          return 0;
        });
      }

      let leafOrgIds = [];
      const getLeafOrg = (orgs) => {
        orgs.forEach((org) => {
          org.disabled = false;
          if (org["children"] && org["children"].length) {
            getLeafOrg(org.children);
          } else {
            leafOrgIds.push(org.id);
          }
        });
      };
      getLeafOrg(this.orgs);
      this.leafOrgIds = leafOrgIds;

      this.$nextTick(() => {
        this.setCheckedNode(this.value);
      });
    },
    setDisabledOrgs(disabledOrgIds) {
      const updateInfo = (orgs) => {
        orgs.forEach((org) => {
          org.disabled = disabledOrgIds.includes(org.id);
          if (org["children"] && org["children"].length) {
            updateInfo(org.children);
          }
        });
      };
      updateInfo(this.orgs);
    },
    setCheckedNode(selectedIds) {
      if (this.multiple) {
        const leafSelectedIds = selectedIds.filter((id) =>
          this.leafOrgIds.includes(id)
        );
        this.$refs.MenuTree.setCheckedKeys(leafSelectedIds);
        return;
      }
      const selectedOrgs = this.$refs.MenuTree.getCheckedKeys();
      if (selectedOrgs.join() === selectedIds.join()) return;

      this.$refs.MenuTree.setCheckedKeys(selectedIds);
    },
    getCheckedNode() {
      return this.$refs.MenuTree.getCheckedKeys();
    },
    checkChange() {
      if (!this.multiple) return;

      const halfCheckedIds = this.$refs.MenuTree.getHalfCheckedKeys();
      const checkedIds = this.$refs.MenuTree.getCheckedKeys();
      const checkedOrgs = [...halfCheckedIds, ...checkedIds];

      this.emitChange(checkedOrgs);
    },
    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>
