<template>
  <li class="cursor">
    <div
      :class="{
        'tree-container flex align-center': true,
        selected: node.dept_code === selectedId,
      }"
      @click="handleClick"
    >
      <p>
        <svg-icon
          type="mdi"
          :width="18"
          :height="18"
          :path="arrowPath"
        ></svg-icon>
      </p>
      <p>
        <svg-icon
          type="mdi"
          :width="18"
          :height="18"
          :path="notePath"
          :color="'#fbbe28'"
        ></svg-icon>
      </p>
      <p class="node-text">{{ node.dept_nm }}</p>
    </div>
    <ul
      v-if="node.children && node.children.length > 0"
      class="children-node"
      :style="{ height: toggleSelect === node.dept_code ? 'auto' : '0' }"
    >
      <DepartmentTree
        v-for="(child, index) in node.children"
        :node="child"
        :key="index"
        @selectedNode="parentSelectedNode"
      />
    </ul>
  </li>
</template>

<script>
import axios from "axios";
import SvgIcon from "@jamescoyle/vue-icon";
import {
  mdiNote,
  mdiChevronRight,
  mdiChevronDown,
  mdiNoteOutline,
} from "@mdi/js";

export default {
  name: "DepartmentTree",
  props: {
    node: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      toggleSelect: null,
      notePath: mdiNote,
      arrowPath: mdiChevronRight,
      selectedId: null,
    };
  },
  methods: {
    handleClick: function () {
      const vm = this;

      // 마지막으로 선택한 노드만 강조되도록
      const nodeList = document.querySelectorAll(".tree-container");
      nodeList.forEach((node) => {
        node.classList.remove("selected");
      });

      // 노드 선택 시 하위 노드 표시 및 가리기
      vm.$emit("selectedNode", vm.node);
      if (vm.toggleSelect === vm.node.dept_code) {
        vm.toggleSelect = null;
        vm.selectedId = null;
        vm.arrowPath = mdiChevronRight;
        vm.notePath = mdiNote;
      } else {
        if (!vm.node.children || vm.node.children.length === 0) {
          vm.getChildDepartment();
        }
        vm.toggleSelect = vm.node.dept_code;
        vm.selectedId = vm.node.dept_code;
        vm.arrowPath = mdiChevronDown;
        vm.notePath = mdiNoteOutline;
      }
    },
    parentSelectedNode(node) {
      this.$emit("selectedNode", node);
    },
    // 깊이 2 이상일 때 자식 노드 불러오기
    getChildDepartment: function () {
      axios
        .get(`/department/tree/${this.node.dept_code}`)
        .then((response) => {
          this.node.children.push(...response.data.resultData.childDepartments);
        })
        .catch((error) => {
          this.$showAlert(
            "오류",
            "목록 불러오기 오류, 관리자에게 문의바랍니다."
          );
        });
    },
  },
  components: {
    SvgIcon: SvgIcon,
  },
};
</script>

<style scoped>
.tree-container {
  padding: 5px 10px;
}
.children-node {
  padding: 0 0 0 10px;
  overflow: hidden;
  transition: max-height 0.5s ease-in-out;
}
.node-text {
  font-size: 1.4rem;
  margin-left: 5px;
}
</style>