<script setup>
// import { KSTree } from '@ksconsole/components'
import { reactive, ref, nextTick } from "vue";
// import { getTreeData } from "../../mock/index.js";
// 模拟tree数据如下
const data = [
  {
    label: "燃气采购项目",
    key: "1",
    children: [
      {
        label: "燃气采购项目-1期",
        key: "1-1",
        isDisabled: true,
        children: [
          {
            label: "燃气采购项目-1-1期",
            key: "1-1-1",
          },
        ],
      },
    ],
  },
  {
    label: "水务采购项目",
    key: "2",
    children: [
      {
        label: "水务采购项目-1",
        key: "2-1",
        children: [
          {
            label: "水务采购项目1-1",
            key: "2-1-1",
          },
          {
            label: "水务采购项目1-2",
            key: "2-1-2",
            // disabled: true,
          },
        ],
      },
      {
        label: "水务统管项目",
        disabled: true,
        key: "2-2",
        children: [
          {
            label: "水务统管项目1",
            key: "2-2-1",
          },
        ],
      },
    ],
  },
];
/* 
const treeData = ref([]);
// 获取tree数据
async function getTreeDataApi() {
  treeData.value = await getTreeData();
}
getTreeDataApi(); */

const treeData = ref(data);
const treeRef = ref(null);
const uniqueId = ref(100);
let selectedKeys = ref([])
selectedKeys.value=[treeData.value[1].key]

// 异步展开子节点，在子组件渲染后调用
function expandNode(key) {
  nextTick(() => {
    // 在这里，你可以调用子组件的展开方法
    treeRef.value.tree.expand(key);
  });
}
// 添加子节点
function appendNode({ data, node, index }) {
  console.log("父组件监听到appendNode事件", data, node, index);
  data.children = data.children || [];
  uniqueId.value++;
  data.children.push({
    key: `${uniqueId.value}`,
    label: "子节点" + `${uniqueId.value}`,
  });
  expandNode(data.key);
}
// 添加一级节点
function rootAppendNode() {
  console.log("父组件监听到rootAppendNode事件");
  uniqueId.value++;
  treeData.value.push({
    key: `${uniqueId.value}`,
    label: "子节点" + `${uniqueId.value}`,
  });
}
// 删除节点
function removeNode({ data, node, index }) {
  console.log("父组件监听到removeNode事件", data, node, index);
  const children = node.parent ? node.parent.data.children : treeData.value;
  children.splice(index, 1);
}
// 编辑节点
function editNode({ data, node, index }) {
  console.log("父组件监听到editNode事件", data, node, index);
}
// 拖拽节点
function dragend(data) {
  console.log("父组件监听到dragend事件", data);
}
// 搜索节点
function searchNode(keywords) {
  console.log("父组件监听到searchNode事件", keywords);
}
// 节点选中变化
function changeSelectedKeys(data) {
  console.log("父组件监听到changeSelectedKeys事件", data);
}
</script>

<template>
  <div class="main-content">
    <KSTree
      ref="treeRef"
      :data="treeData"
      @append="appendNode"
      @rootAppend="rootAppendNode"
      @remove="removeNode"
      @edit="editNode"
      @dragend="dragend"
      @search="searchNode"
      :showRootAppend="true"
      titleAlign="left"
      :selectedKeys="selectedKeys"
      @changeSelectedKeys="changeSelectedKeys"
      >组织</KSTree
    >
  </div>
</template>
