<template>
  <div class="picTree">
    <el-tree
      ref="tree"
      :data="piclist"
      :props="defaultProps"
      node-key="name"
      accordion
      :default-expanded-keys="defaultExpandedKeys"
      highlight-current
      :current-node-key="currentNodekey"
      :expand-on-click-node="true"
      @node-click="handleNodeClick"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span v-if="node.level === 1">
          <span>{{ node.label }}</span> ({{ data.children.length }})
        </span>
        <span v-else-if="node.level === 2">
          <i v-if="data.marked" class="el-icon-s-flag"></i>
          <span :title="node.label">{{ node.label }}</span>
        </span>
      </span>
    </el-tree>
  </div>
</template>
<script>
import EventBus from "@/utils/event-bus";
import { getTreeApi, getLabelsApi } from "@/utils/api/index";

export default {
  components: {},
  props: [],
  data() {
    return {
      piclist: [],
      currentNodeData: [], //选中的数据
      defaultExpandedKeys: [],
      currentNodekey: "", //选中的节点
      defaultProps: {
        children: "children",
        label: "name",
      },

      pathParams: "",
      labelsPoint: "",
    };
  },
  computed: {},
  created() {
    EventBus.$on("treeHandleNode", this.handleNodeClick);
    EventBus.$on("treelist", this.getTreeList);
  },
  mounted() {
    this.getTreeList();
  },
  methods: {
    //获取linelist 线路内容
    getTreeList() {
      getTreeApi()
        .then((res) => {
          console.log(res);
          this.piclist = res.data;

          console.log(this.piclist);
          console.log(this.defaultExpandedKeys);
          console.log(this.currentNodekey);

          //this.currentNodeData = this.piclist[0].children[0];
          this.currentNodeData = JSON.parse(
            localStorage.getItem("currentData")
          );
          console.log(this.currentNodeData);
          if (
            this.currentNodeData !== null &&
            Object.keys(this.currentNodeData).length !== 0
          ) {
            this.currentNodekey = this.currentNodeData.name;

            //this.defaultExpandedKeys = [this.piclist[0].name];
            console.log("aaaaaaaaaaaaaaaaa");
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.currentNodekey); //一定要加这个选中了否则样式没有出来
              this.handleNodeClick(this.currentNodeData);
              this.scrollView();
            });
          } else {
            console.log("bbbbbbbbbbbbbbbbbbbbb");
            this.defaultExpandedKeys = [this.piclist[0].name];
            this.currentNodekey = this.piclist[0].children[0].name;
            this.currentNodeData = this.piclist[0].children[0];
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.currentNodekey); //一定要加这个选中了否则样式没有出来
              this.handleNodeClick(this.currentNodeData);
              this.scrollView();
            });
          }
        })
        .catch((err) => {});
    },
    handleNodeClick(node, data) {
      //点击父节点收起
      if (node.children?.length) {
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.currentNodeKey);
        });
        return;
      }
      this.currentNodeKey = node.name;
      console.log(node); // 你会看到当前节点的数据
      console.log(data);
      const parentNode = this.findParentNode(data.id, this.piclist);

      if (parentNode) {
        // 找到了父节点，打印父节点的数据
        console.log(parentNode); // 输出父节点的数据对象
      } else {
        // 没找到父节点，处理错误情况
        console.error("未能找到父节点");
      }
      //const parentNode = this.$refs.tree.getNode(node).parent;
      // //const parentNode = this.$refs.tree.getNode(node).parent.data;
      EventBus.$emit("currentNodeData", node);
      EventBus.$emit("perentNode", parentNode);
      this.defaultExpandedKeys = [parentNode.name];
      this.pathParams = parentNode.name + "/" + node.name;
      console.log(this.pathParams);
      this.getlabels();
      localStorage.setItem("currentData", JSON.stringify(node));
    },
    findParentNode(childId, treeData) {
      console.log(childId);
      console.log(treeData);
      // 递归查找父节点
      return treeData.find((parent) => {
        console.log(parent);
        return (
          parent.children &&
          parent.children.find((child) => child.$treeNodeId === childId)
        );
      });
    },
    getlabels() {
      getLabelsApi({
        path: this.pathParams,
      })
        .then((res) => {
          console.log(res);
          this.labelsPoint = res.data;
          EventBus.$emit("labelMark", this.labelsPoint);
        })
        .catch((err) => {});
    },
    scrollView() {
      if (this.currentNodeData) {
        this.$nextTick(() => {
          let treeComponent = this.$refs.tree.$el;
          let node = treeComponent.querySelector(".is-current");
          console.log(node);
          if (node) {
            node.scrollIntoView({ behavior: "smooth" });
          }
        });
      }
    },
  },
  beforeDestroy() {
    // 组件销毁前移除事件监听，避免内存泄漏
    EventBus.$off("treeHandleNode", this.handleNodeClick);
  },
};
</script>
<style lang="less">
.picTree {
  width: 380px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  .el-tree {
    overflow-y: auto;
    height: calc(100% - 0px);
    .el-tree-node__content {
      height: 32px;
      font-size: 14px;
      position: relative;
    }
    .custom-tree-node {
      color: #333;
      overflow: hidden;
      span {
        display: flex;
        display: inline-table;
        overflow: hidden;
        align-items: center;
      }
    }
  }
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    // 设置颜色
    color: #fff;
    background: #169e8c;
    .custom-tree-node {
      color: #fff;
      //overflow: hidden;
      span {
        display: flex;
        //overflow: hidden;
        align-items: center;
      }
    }
  }
  .el-icon-s-flag {
    position: absolute;
    left: 18px;
    top: 10px;
  }
}
</style>
