1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
<template>
  <el-card class="archive-management-card">
    <div class="left">
      <div class="left-content">
        <div class="tree-header">
          <h3>文档管理</h3>
          <el-button icon="Plus" size="small" type="primary" @click="append('')"
            >新增
          </el-button>
        </div>
 
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="filterText"
            clearable
            placeholder="输入关键字进行搜索"
            size="small"
            @input="handleFilter"
          >
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
 
        <div class="tree-container">
          <el-tree
            ref="treeRef"
            :data="treeData"
            :default-expand-all="false"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :props="props"
            :lazy="false"
            :load="undefined"
            :render-after-expand="true"
            :auto-expand-parent="true"
            :indent="20"
            class="custom-tree"
            node-key="id"
            @node-click="handleNodeClick"
            @node-expand="handleNodeExpand"
          >
            <template #default="{ node, data }">
              <div
                class="tree-node-content"
                :data-temp-id="data._tempId"
                :data-node-id="data.id"
                @dblclick="headerDbClick(node, data)"
              >
                <div class="node-icon">
                  <el-icon
                    v-if="!node.isLeaf"
                    :class="{ expanded: node.expanded }"
                  >
                    <Folder />
                  </el-icon>
                  <el-icon v-else>
                    <Document />
                  </el-icon>
                </div>
 
                <div class="node-label">
                  <span v-if="!data.isEdit" class="label-text">{{
                    node.label
                  }}</span>
                  <el-input
                    v-else
                    :ref="(el) => setInputRef(data.id || data._tempId, el)"
                    v-model="newName"
                    autofocus
                    class="tree-input"
                    placeholder="请输入节点名称"
                    size="small"
                    @blur="(event) => handleInputBlur(event, data, node)"
                    @keyup.enter="(event) => handleInputBlur(event, data, node)"
                    @keyup.esc="() => cancelEdit(data, node)"
                  />
                </div>
                <div v-show="!data.isEdit" class="node-actions">
                  <el-button
                    icon="Plus"
                    link
                    size="small"
                    :title="getNodeDepth(data) >= 7 ? '已达到最大嵌套层级(7层)' : '新增子节点'"
                    :disabled="getNodeDepth(data) >= 7"
                    @click.stop="append(data)"
                  ></el-button>
                  <el-button
                    icon="Delete"
                    link
                    size="small"
                    title="删除"
                    @click.stop="remove(node, data)"
                  ></el-button>
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </div>
    <div class="right">
      <el-row :gutter="24">
        <el-col :span="10">
          <div>
            <el-input
              style="float: left; width: 50%"
              v-model="searchText"
              placeholder="请输入关键字查询文件"
              clearable
              @input="handleSearch"
              @clear="handleSearch"
            >
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
              <template #suffix>
                <el-button @click="handleSearch" link style="border: none">
                  <span>搜索</span>
                </el-button>
              </template>
            </el-input>
          </div>
        </el-col>
        <el-col :offset="8" :span="3">
          <el-button :icon="Delete" type="danger" @click="delHandler"
            >删除</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button
            :disabled="!tableSwitch"
            :icon="Plus"
            type="primary"
            @click="add"
            >新增
          </el-button>
        </el-col>
      </el-row>
      <ETable
        :border="true"
        :columns="columns"
        :loading="loading"
        :maxHeight="1200"
        :show-selection="true"
        :table-data="tableData"
        @edit="handleEdit"
        @selection-change="handleSelectionChange"
        style="height: calc(65vh);"
      >
      </ETable>
      <Pagination
        :layout="'total, prev, pager, next, jumper'"
        :limit="queryParams.pageSize"
        :page="queryParams.current"
        :show-total="true"
        :total="total"
        @pagination="handlePageChange"
      ></Pagination>
    </div>
    <archiveDialog
      ref="archiveDialogs"
      v-model:centerDialogVisible="dialogVisible"
      :row="row"
      @centerDialogVisible="centerDialogVisible"
      @submitForm="submitForm"
    >
    </archiveDialog>
  </el-card>
</template>
<script setup>
import { computed, nextTick, onMounted, reactive, ref } from "vue";
import ETable from "@/components/Table/ETable.vue";
import {
  ElButton,
  ElIcon,
  ElInput,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import archiveDialog from "./mould/archiveDialog.vue";
import Pagination from "@/components/Pagination/index.vue";
import {
  Delete,
  Document,
  Folder,
  Plus,
  Search,
} from "@element-plus/icons-vue";
import {
  addOrEditTree,
  delArchive,
  delTree,
  getArchiveList,
  getTree,
} from "@/api/archiveManagement";
 
// ===== 响应式状态管理 =====
const searchText = ref("");
const dialogVisible = ref(false);
const loading = ref(false);
const tableData = ref([]);
const treeData = ref([]);
const newName = ref("");
const inputRefs = ref(new Map());
const filterText = ref("");
const treeRef = ref();
const total = ref(0);
const row = ref({});
const selectedRows = reactive([]);
const rowClickData = ref({});
const tableSwitch = ref(false);
const archiveDialogs = ref(null);
 
// ===== 配置常量 =====
const columns = [
  { prop: "name", label: "名称", minWidth: 180 },
  { prop: "type", label: "类型", minWidth: 120 },
  { prop: "status", label: "状态", minWidth: 100 },
];
 
const queryParams = reactive({
  searchAll: "",
  current: 1,
  pageSize: 10,
  treeId: null,
});
 
const props = {
  label: "name",
  children: "children",
  isLeaf: "leaf",
};
 
// ===== 计算属性 =====
// 计算总节点数
const totalNodeCount = computed(() => {
  const countNodes = (nodes) => {
    let count = 0;
    for (const node of nodes || []) {
      count += 1;
      if (node.children) {
        count += countNodes(node.children);
      }
    }
    return count;
  };
  return countNodes(treeData.value);
});
 
// 检查是否为大量节点(超过1000个节点时提示性能优化)
const isLargeTree = computed(() => totalNodeCount.value > 1000);
 
// 获取节点深度的函数
const getNodeDepth = (nodeData) => {
  if (!nodeData || !nodeData.id) return 0;
  
  let depth = 1;
  const node = treeRef.value?.getNode(nodeData.id);
  let parentNode = node?.parent;
  
  while (parentNode && parentNode.data && parentNode.data.id) {
    depth++;
    parentNode = parentNode.parent;
  }
  
  return depth;
};
 
// ===== 工具函数 =====
const handleError = (error, defaultMsg = "操作失败,请稍后重试") => {
  console.error(error);
  ElMessage.error(defaultMsg);
};
 
const showSuccess = (msg = "操作成功") => {
  ElMessage.success(msg);
};
 
// 搜索查询函数
const handleSearch = () => {
  queryParams.searchAll = searchText.value;
  queryParams.current = 1; // 重置到第一页
  getArchiveListData();
};
 
const showConfirm = (message, title = "确认操作") => {
  return ElMessageBox.confirm(message, title, {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
};
 
// ===== 基础功能函数 =====
const handleSelectionChange = (selection) => {
  selectedRows.splice(0, selectedRows.length, ...selection);
};
 
const handleFilter = () => {
  treeRef.value?.filter(filterText.value);
};
 
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name?.toLowerCase().includes(value.toLowerCase());
};
 
const centerDialogVisible = (val) => {
  dialogVisible.value = val;
};
// ===== 数据获取函数 =====
const getList = async () => {
  try {
    const res = await getTree();
    treeData.value =
      res.code === 200 ? res.data?.records || res.data || [] : [];
  } catch (error) {
    handleError(error, "获取树结构数据失败");
    treeData.value = [];
  }
};
 
const getArchiveListData = async () => {
  try {
    loading.value = true;
    const res = await getArchiveList({
      treeId: queryParams.treeId,
      current: queryParams.current,
      size: queryParams.pageSize,
      searchAll: queryParams.searchAll,
    });
 
    if (res.code !== 200) {
      ElMessage.error("获取数据失败: " + res.message);
      tableData.value = [];
      total.value = 0;
      return;
    }
 
    tableData.value = res.data?.records || res.data || [];
    total.value = res.data?.total || 0;
 
    if (res.data?.current) {
      queryParams.current = res.data.current;
    }
  } catch (error) {
    handleError(error, "获取归档数据失败");
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};
 
// ===== 表单提交处理 =====
const submitForm = async (res) => {
  try {
    if (res?.code === 200) {
      showSuccess();
      dialogVisible.value = false;
      await getArchiveListData();
    } else {
      ElMessage.error("操作失败: " + (res?.message || res?.msg || "未知错误"));
    }
  } catch (error) {
    handleError(error, "提交表单失败");
  }
};
// ===== 节点操作函数 =====
const handleNodeClick = (data) => {
  rowClickData.value = data;
  tableSwitch.value = true;
  queryParams.current = 1;
  queryParams.treeId = data.id;
  getArchiveListData();
};
 
// 节点展开事件处理
const handleNodeExpand = (data, node, instance) => {
  // 展开后稍微延迟,确保子节点渲染完成
  setTimeout(() => {
    // 如果有新添加的编辑状态节点,聚焦到它
    if (data.children && data.children.length > 0) {
      const editingChild = data.children.find(child => child.isEdit && child._tempId);
      if (editingChild) {
        focusInput(editingChild._tempId, 200);
      }
    }
  }, 100);
};
 
const handlePageChange = (pagination) => {
  try {
    const { page, limit } = pagination;
    queryParams.current = page;
    if (limit) queryParams.pageSize = limit;
    getArchiveListData();
  } catch (error) {
    handleError(error, "分页操作失败");
  }
};
 
// ===== 弹窗操作函数 =====
const openDialog = (isEdit = false, rowData = {}) => {
  try {
    row.value = isEdit ? { ...rowData } : {};
    newName.value = "";
    dialogVisible.value = true;
 
    nextTick(() => {
      if (archiveDialogs.value) {
        const method = isEdit ? "editForm" : "initForm";
        if (typeof archiveDialogs.value[method] === "function") {
          archiveDialogs.value[method](isEdit ? rowData : rowClickData.value);
        }
      }
    });
  } catch (error) {
    handleError(error, `打开${isEdit ? "编辑" : "新增"}界面失败`);
  }
};
 
const add = () => openDialog(false);
const handleEdit = (rows) => openDialog(true, rows);
 
// ===== 删除操作函数 =====
const delHandler = async () => {
  if (selectedRows.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }
 
  try {
    await showConfirm(
      `确定要删除选中的 ${selectedRows.length} 条记录吗?`,
      "删除确认"
    );
 
    const ids = selectedRows.map((row) => row.id);
    const { code, msg } = await delArchive(ids);
 
    if (code !== 200) {
      ElMessage.error("删除失败: " + msg);
      return;
    }
 
    showSuccess("删除成功");
    await getArchiveListData();
    selectedRows.splice(0, selectedRows.length);
  } catch (error) {
    if (error !== "cancel") {
      handleError(error, "删除操作失败");
    }
  }
};
 
const remove = async (node, data) => {
  if (!data?.id) {
    ElMessage.warning("无法删除此节点");
    return;
  }
 
  try {
    await showConfirm(`确定要删除节点 "${data.name}" 吗?`, "删除确认");
 
    const { code, msg } = await delTree([data.id]);
 
    if (code !== 200) {
      ElMessage.error("删除失败: " + msg);
      return;
    }
 
    showSuccess("删除成功");
    await getList();
  } catch (error) {
    if (error !== "cancel") {
      handleError(error, "删除节点失败");
    }
  }
};
// ===== 树节点编辑函数 =====
const setInputRef = (key, el) => {
  if (el && key) {
    inputRefs.value.set(key, el);
  }
};
 
const headerDbClick = (node, data) => {
  try {
    data.isEdit = true;
    newName.value = data.name;
    
    nextTick(() => {
      const key = data._tempId || data.id;
      if (key) {
        focusInput(key, 50);
      }
    });
  } catch (error) {
    console.error('进入编辑模式失败:', error);
    ElMessage.error('进入编辑模式失败');
  }
};
 
// 取消编辑功能
const cancelEdit = (data, node) => {
  try {
    data.isEdit = false;
    
    // 如果是新创建的临时节点,删除它
    if (data._tempId && !data.id) {
      if (node.parent) {
        const parent = node.parent.data;
        const index = parent.children?.indexOf(data);
        if (index > -1) {
          parent.children.splice(index, 1);
        }
      } else {
        // 根节点
        const index = treeData.value.indexOf(data);
        if (index > -1) {
          treeData.value.splice(index, 1);
        }
      }
      
      // 清理输入框引用
      const key = data._tempId;
      if (inputRefs.value.has(key)) {
        inputRefs.value.delete(key);
      }
    }
    
    // 重置名称
    newName.value = "";
  } catch (error) {
    console.error('取消编辑失败:', error);
  }
};
 
const expandParentNodes = (node) => {
  if (node?.parent?.data) {
    node.parent.expanded = true;
    expandParentNodes(node.parent);
  }
};
 
const handleInputBlur = async (event, comeTreeData, node) => {
  try {
    if (!comeTreeData.isEdit || event.relatedTarget?.tagName === "BUTTON")
      return;
 
    comeTreeData.isEdit = false;
    const newValue = newName.value.trim();
 
    // 如果名称为空,处理空名称情况
    if (!newValue) {
      // 如果是新创建的临时节点,删除它
      if (comeTreeData._tempId && !comeTreeData.id) {
        cancelEdit(comeTreeData, node);
      } else {
        // 已存在的节点,恢复原名称
        newName.value = comeTreeData.name || "新节点";
      }
      ElMessage.warning("节点名称不能为空");
      return;
    }
 
    // 如果名称没有改变,直接返回
    if (comeTreeData.name === newValue) {
      return;
    }
 
    const parentId = node?.parent?.data?.id || null;
 
    const result = await addOrEditTree({
      name: newValue,
      parentId,
      id: comeTreeData.id || null,
    });
 
    if (result.code === 200) {
      comeTreeData.name = newValue;
      if (!comeTreeData.id && result.data) {
        comeTreeData.id = result.data.id || result.data;
        // 清理临时ID
        if (comeTreeData._tempId) {
          const tempKey = comeTreeData._tempId;
          delete comeTreeData._tempId;
          
          // 更新引用映射
          if (inputRefs.value.has(tempKey)) {
            const inputEl = inputRefs.value.get(tempKey);
            inputRefs.value.delete(tempKey);
            if (comeTreeData.id && inputEl) {
              inputRefs.value.set(comeTreeData.id, inputEl);
            }
          }
        }
      }
      showSuccess("保存成功");
 
      const currentNodeId = comeTreeData.id;
      await getList();
 
      nextTick(() => {
        if (currentNodeId && treeRef.value) {
          const targetNode = treeRef.value.getNode(currentNodeId);
          if (targetNode) {
            // 展开当前节点
            targetNode.expanded = true;
            
            // 展开所有父节点
            expandParentNodes(targetNode);
            
            // 滚动到节点位置
            setTimeout(() => {
              const nodeElement = document.querySelector(`[data-node-id="${currentNodeId}"]`);
              if (nodeElement) {
                nodeElement.scrollIntoView({
                  behavior: 'smooth',
                  block: 'center'
                });
              }
            }, 300);
          }
        }
      });
    } else {
      // 保存失败,恢复原名称或删除临时节点
      if (comeTreeData._tempId && !comeTreeData.id) {
        cancelEdit(comeTreeData, node);
      } else {
        comeTreeData.name = comeTreeData.name || "新节点";
      }
      ElMessage.error("保存失败: " + (result.msg || "未知错误"));
    }
  } catch (error) {
    handleError(error, "保存节点失败");
    // 出错时处理临时节点
    if (comeTreeData._tempId && !comeTreeData.id) {
      cancelEdit(comeTreeData, node);
    } else {
      comeTreeData.name = comeTreeData.name || "新节点";
    }
  }
};
 
// ===== 节点新增函数 =====
const createNewNode = (name, isEdit = true) => ({
  name,
  isEdit,
  _tempId: Date.now() + Math.random(), // 添加临时ID
});
 
const focusInput = (nodeKey, delay = 100) => {
  setTimeout(() => {
    const inputEl = inputRefs.value.get(nodeKey);
    if (inputEl) {
      try {
        // 先滚动到可视区域
        inputEl.$el?.scrollIntoView?.({
          behavior: "smooth",
          block: "center",
        });
        
        // 聚焦并选中所有文本,确保可以直接编辑
        setTimeout(() => {
          inputEl.focus();
          inputEl.select();
          
          // 确保光标在输入框末尾(如果select失败的话)
          const inputElement = inputEl.ref || inputEl.input || inputEl.$el?.querySelector('input');
          if (inputElement) {
            inputElement.setSelectionRange(0, inputElement.value.length);
            
            // 确保输入框在视口中央
            setTimeout(() => {
              inputElement.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
              });
            }, 100);
          }
        }, 100);
      } catch (error) {
        console.warn('聚焦输入框失败:', error);
        // 备用方案:直接聚焦
        try {
          inputEl.focus();
          // 尝试选中文本
          setTimeout(() => {
            const inputElement = inputEl.ref || inputEl.input || inputEl.$el?.querySelector('input');
            if (inputElement) {
              inputElement.select();
            }
          }, 200);
        } catch (e) {
          console.warn('备用聚焦方案也失败:', e);
        }
      }
    } else {
      console.warn('未找到输入框元素,key:', nodeKey);
    }
  }, delay);
};
 
const append = async (data) => {
  try {
    // 检查嵌套层级限制
    const getNodeDepth = (nodeData, currentDepth = 1) => {
      if (!nodeData || data === "") return 0; // 根节点不算层级
      
      let depth = currentDepth;
      let current = nodeData;
      
      // 通过树组件获取父节点来计算深度
      if (current.id) {
        const node = treeRef.value?.getNode(current.id);
        let parentNode = node?.parent;
        
        while (parentNode && parentNode.data && parentNode.data.id) {
          depth++;
          parentNode = parentNode.parent;
        }
      }
      
      return depth;
    };
 
    const currentDepth = getNodeDepth(data);
    
    // 限制最多7层嵌套
    if (currentDepth >= 7) {
      ElMessage.warning('最多只能嵌套7层节点,当前已达到最大层级限制');
      return;
    }
 
    // 在大量节点时提示性能注意事项
    if (isLargeTree.value && totalNodeCount.value > 2000) {
      const confirmed = await ElMessageBox.confirm(
        `当前树结构包含 ${totalNodeCount.value} 个节点,节点较多可能影响性能。建议考虑分层管理。是否继续添加?`,
        '性能提示',
        {
          confirmButtonText: '继续添加',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => false);
      
      if (!confirmed) return;
    }
 
    if (data === "") {
      // 新增根节点
      const newNode = createNewNode("新节点");
      treeData.value.push(newNode);
      newName.value = "新节点";
 
      await nextTick();
      focusInput(newNode._tempId, 200);
    } else {
      const hasChildren = data.children && data.children.length > 0;
      const nodeKey = data.id || data;
      const node = treeRef.value?.getNode(nodeKey);
 
      // 创建新子节点
      const newNode = createNewNode("新子节点");
 
      if (!data.children) {
        data.children = [];
      }
      data.children.push(newNode);
      newName.value = "新子节点";
 
      // 强制更新树结构
      await nextTick();
      
      // 确保父节点展开以显示新节点
      if (node) {
        node.expanded = true;
        
        // 如果是第一次添加子节点,等待展开动画并确保可见
        if (!hasChildren) {
          await new Promise(resolve => setTimeout(resolve, 300));
          
          // 展开后滚动到新节点位置
          setTimeout(() => {
            const newNodeElement = document.querySelector(`[data-temp-id="${newNode._tempId}"]`);
            if (newNodeElement) {
              newNodeElement.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
              });
            }
          }, 100);
        }
        
        // 展开所有父节点确保完全可见
        let parentNode = node.parent;
        while (parentNode && parentNode.data && parentNode.data.id) {
          parentNode.expanded = true;
          parentNode = parentNode.parent;
        }
      }
      
      // 聚焦到新创建的输入框
      const delay = hasChildren ? 150 : 500; // 如果之前没有子节点,延迟更长时间等展开
      focusInput(newNode._tempId, delay);
    }
  } catch (error) {
    console.error('新增节点失败:', error);
    ElMessage.error('新增节点失败,请重试');
  }
};
 
// ===== 生命周期 =====
onMounted(()=>{
  getList();
  getArchiveListData();
});
</script>
<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
 
// 树形菜单样式
.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
 
  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}
 
.search-box {
  margin-bottom: 16px;
 
  .el-input {
    border-radius: 6px;
 
    :deep(.el-input__wrapper) {
      border-radius: 6px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
 
      &:hover {
        box-shadow: 0 1px 6px rgba(0, 0, 0, 0.15);
      }
 
      &.is-focus {
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
  }
}
 
.tree-container {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  max-height: calc(100vh - 240px); // 限制最大高度,启用滚动
 
  .custom-tree {
    padding: 8px;
    background: transparent;
    // 使用GPU加速提升滚动性能
    transform: translateZ(0);
    will-change: scroll-position;
 
    :deep(.el-tree-node) {
      // 减少不必要的重绘
      contain: layout style;
      
      .el-tree-node__content {
        height: 36px;
        padding: 0 8px;
        border-radius: 6px;
        margin: 2px 0;
        transition: all 0.2s ease;
        // 优化渲染性能
        will-change: background-color;
 
        &:hover {
          background-color: #f0f9ff;
        }
 
        &.is-current {
          background-color: #e6f7ff;
          border: 1px solid #91d5ff;
        }
      }
 
      .el-tree-node__expand-icon {
        color: #606266;
        font-size: 14px;
        padding: 6px;
 
        &.expanded {
          transform: rotate(90deg);
        }
 
        &.is-leaf {
          color: transparent;
        }
      }
    }
  }
}
 
.tree-node-content {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 4px 0;
 
  .node-icon {
    margin-right: 8px;
    color: #faad14;
    display: flex;
    align-items: center;
 
    .el-icon {
      font-size: 16px;
 
      &.expanded {
        color: #1890ff;
      }
    }
  }
 
  .node-label {
    flex: 1;
    min-width: 0;
 
    .label-text {
      font-size: 14px;
      color: #303133;
      cursor: pointer;
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
 
      &:hover {
        color: #1890ff;
      }
    }
  }
 
  .node-actions {
    opacity: 0;
    transition: opacity 0.2s ease;
    display: flex;
 
    .el-button {
      padding: 4px;
      margin-left: 4px;
      color: #909399;
      min-height: auto;
 
      &:hover:not(:disabled) {
        color: #1890ff;
        background-color: #f0f9ff;
      }
 
      &.el-button--text:hover:not(:disabled) {
        background-color: #f0f9ff;
      }
      
      &:disabled {
        color: #c0c4cc;
        cursor: not-allowed;
        background-color: transparent;
      }
    }
  }
 
  &:hover .node-actions {
    opacity: 1;
  }
}
 
// 输入框样式美化
.tree-input {
  flex: 1;
 
  :deep(.el-input__wrapper) {
    border-radius: 4px;
    border: 1px solid #40a9ff;
    transition: all 0.2s ease;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
 
    &:hover {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.15);
    }
 
    &.is-focus {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
    }
  }
 
  :deep(.el-input__inner) {
    padding: 4px 8px;
    font-size: 14px;
    color: #303133;
    background-color: #fff;
 
    &::placeholder {
      color: #bfbfbf;
    }
    
    &:focus {
      background-color: #f8fcff;
    }
  }
}
 
.el-card {
  width: calc(100% - 40px);
  height: calc(100vh - 130px);
  margin: 20px;
  box-sizing: border-box;
 
  .left {
    width: 30%;
    height: calc(100vh - 160px);
    background-color: #fafafa;
    padding: 16px;
    float: left;
    box-sizing: border-box;
    border-radius: 8px;
 
    .left-content {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
    }
  }
 
  .right {
    width: 70%;
    height: calc(100vh - 160px);
    padding: 0 10px;
    float: left;
  }
}
 
.archive-management-card {
  margin: 0;
}
</style>