import { computed, defineComponent, nextTick, onBeforeUnmount, ref } from "vue";
import "./collapseTreeStyle.scss";
import { emitter } from "@/utils/mitt";

export default defineComponent({
  name: "CollapseTreeItem",
  props: {
    info: {
      type: undefined,
      default: []
    }
  },

  setup(props) {
    const currentTreeNodeId = ref(""); // 树节点id
    const nodeLatestInfo = computed(() => {
      //实时的树节点数据
      return { ...props.info };
    });

    // 选择树节点
    function selectTreeNode() {
      emitter.emit(
        "changCollapseTreeNodeId",
        nodeLatestInfo.value.id as unknown as string
      );
      console.log("selectTreeNode", nodeLatestInfo.value.id);
    }

    nextTick(() => {
      emitter.on("changCollapseTreeNodeId", data => {
        currentTreeNodeId.value = data;
      });
    });

    onBeforeUnmount(() => {
      // 解绑`changCollapseTreeNodeId`公共事件，防止多次触发
      emitter.off("changCollapseTreeNodeId");
    });

    return () => {
      return (
        <div class={["collapseTreeItem_wrap"]}>
          <div
            class={[
              "collapseTreeItem_info flex",
              currentTreeNodeId.value === nodeLatestInfo.value.id
                ? "theme-color"
                : "text-web-font2"
            ]}
            onClick={() => {
              selectTreeNode();
            }}
          >
            <span class={["collapseTreeItem_line"]}></span>
            <div class={["collapseTreeItem_main_info"]}>
              <i class="iconfont icon-zishebeizu tree_item_icon"></i>
              <span>{nodeLatestInfo.value.name}</span>
            </div>
          </div>
          {Array.isArray(nodeLatestInfo.value?.childList) &&
            nodeLatestInfo.value.childList.length && (
              <ul class="collapseTreeItem_child_info_box">
                {nodeLatestInfo.value.childList?.map((item, index) => {
                  return (
                    <li key={index}>
                      <CollapseTreeItem info={item}></CollapseTreeItem>
                    </li>
                  );
                })}
              </ul>
            )}
        </div>
      );
    };
  }
});
