<template>
  <view
    class="w-tree-node"
    v-for="data of innerTreeData"
    :key="data[propsConfig.value]"
  >
    <!-- 节点内容 -->
    <view
      class="w-tree-node__content"
      :class="{ 'is-current': data._isCurrent }"
      @tap.stop="handleNodeClick(data)"
    >
      <!-- 展开/收起图标 -->
      <view
        v-if="data.children?.length"
        class="w-tree-node__expand-icon"
        :class="{ expanded: data._isOpen }"
        @tap.stop="handleIconClick(data)"
      >
      </view>
      <!-- 节点文本 -->
      <view class="textdot1" style="padding-left: 5px">{{
        data[propsConfig.label]
      }}</view>
    </view>
    <!-- 子节点 -->
    <view
      v-if="data.children && data.children.length && data._isOpen"
      class="w-tree-node__children"
    >
      <w-tree-item
        v-model:treeData="data.children"
        :propsConfig="propsConfig"
        @clickNode="handleSubNodeClick"
      ></w-tree-item>
    </view>
  </view>
</template>
<script lang="ts" setup>
import { watch, ref, defineEmits, defineProps } from "vue";

// 定义树节点的类型
interface TreeNode {
  [key: string]: any;
  children?: TreeNode[];
  _isOpen?: boolean;
  _isCurrent?: boolean;
}

// 定义组件的 Props
interface Props {
  treeData: TreeNode[];
  propsConfig: {
    children: string;
    label: string;
    value: string;
  };
}

const props = defineProps<Props>();

// 定义 Emits 事件
const emit = defineEmits<{
  (event: "clickNode", item: TreeNode): void;
  (event: "update:treeData", value: TreeNode[]): void; // 新增事件
}>();

const innerTreeData = ref<TreeNode[]>([...props.treeData]);

watch(
  () => props.treeData,
  (newVal) => {
    innerTreeData.value = [...newVal];
    emit("update:treeData", newVal); // 触发父组件更新
  },
  { deep: true }
);

// 处理节点点击事件
function handleNodeClick(item: TreeNode) {
  emit("clickNode", item); // 触发点击事件
}

// 处理展开/收起图标点击事件
function handleIconClick(item: TreeNode) {
  if (item.children && item.children.length) {
    item._isOpen = !item._isOpen; // 切换展开/收起状态
  }
}

// 处理子节点点击事件
function handleSubNodeClick(item: TreeNode) {
  emit("clickNode", item); // 触发点击事件
}
</script>
<style lang="scss" scoped></style>
