FileTreeNode.vue 38.8 KB
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 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
<template>
  <div class="file-tree-node">
    <el-tooltip
      :content="getDragTooltip(node)"
      :disabled="node.type === 'folder' || node.knowledgeStatus === 'completed'"
      placement="top"
      :show-after="500"
    >
      <div
        class="node-content"
        :class="{
          'is-folder': node.type === 'folder',
          'is-file': node.type === 'file',
          'is-selected': isSelected,
          'is-my-documents-root': isMyDocuments,
          'is-drag-over': isDragOver,
          'is-not-ready': node.type === 'file' && node.knowledgeStatus !== 'completed',
          'is-processing': node.knowledgeStatus === 'processing'
        }"
        :style="{ paddingLeft: Math.max(1, level) * 16 + 'px', paddingRight: '8px' }"
        :data-file-id="node.type === 'file' ? node.id : undefined"
        :data-folder-id="node.type === 'folder' ? node.id : undefined"
        @click="handleClick($event)"
        @dblclick="handleDoubleClick"
        @dragstart="handleDragStart"
        @dragover="handleDragOver"
        @dragleave="handleDragLeave"
        @drop="handleDrop"
        @contextmenu="handleContextMenu"
        :draggable="!isMyDocuments"
      >
      <!-- 文件夹展开/折叠图标 -->
      <template v-if="node.type === 'folder'">
        <el-icon v-if="isLoading" class="expand-icon is-loading"><Loading /></el-icon>
        <i
          v-else
          class="expand-icon fas"
          :class="isExpanded ? 'fa-chevron-down' : 'fa-chevron-right'"
          @click.stop="toggleExpand"
        ></i>
      </template>

      <!-- 文件图标 - 使用 SVG 图标 -->
      <template v-else>
        <el-icon v-if="node.knowledgeStatus === 'processing'" class="file-icon is-loading"><Loading /></el-icon>
        <img
          v-else
          :src="getFileIcon(node.name)"
          class="file-icon"
          :alt="getFileTypeText(node.name)"
        />
      </template>

      <!-- 文件/文件夹名称 -->
      <span 
        class="node-name" 
        :class="{ 'is-my-documents': isMyDocuments }"
        :title="node.name"
      >
        {{ node.name }}
      </span>
      
      <!-- 我的文档搜索框和操作按钮 -->
      <div v-if="isMyDocuments" class="my-documents-actions" @click.stop>
        <!-- 搜索输入框(点击搜索按钮后显示) -->
        <div v-if="showSearchBox" class="search-box-wrapper">
          <button
            class="cancel-search-btn"
            @click="handleCancelSearch"
            title="取消"
          >
            <el-icon><Close /></el-icon>
          </button>
          <input
            v-model="localSearchKeyword"
            type="text"
            class="search-input-field"
            :placeholder="t('KnowledgeBase.fileSearchPlaceholder')"
            @keyup.enter="handlePerformSearch"
            @keyup.esc="handleCancelSearch"
            @click.stop
            ref="searchInputRef"
          />
          <button
            class="search-btn"
            @click="handlePerformSearch"
            title="搜索"
          >
            <el-icon><Search /></el-icon>
          </button>
        </div>
        <!-- 操作按钮组(默认显示,搜索框显示时隐藏) -->
        <div v-else class="action-buttons-group">
          <!-- 新建文件按钮 -->
          <button
            class="action-btn"
            @click="handleNewFileClick"
            title="新建文件"
          >
            <el-icon><DocumentAdd /></el-icon>
          </button>
          <!-- 新建文件夹按钮 -->
          <button
            class="action-btn"
            @click="handleNewFolderClick"
            title="新建文件夹"
          >
            <el-icon><FolderAdd /></el-icon>
          </button>
          <!-- 上传文件按钮 -->
          <button
            class="action-btn"
            @click.stop.prevent="handleUploadFileClick"
            @mousedown.stop
            @mouseup.stop
            title="上传文件"
          >
            <el-icon><Upload /></el-icon>
          </button>
          <!-- 搜索按钮 -->
          <button
            class="action-btn"
            @click="handleSearchButtonClick"
            title="检索文件"
          >
            <el-icon><Search /></el-icon>
          </button>
          <!-- 收起第一层目录按钮 -->
          <button
            v-if="false"
            class="action-btn"
            @click="handleCollapseFirstLevel"
            title="收起第一层目录"
          >
            <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16">
              <path d="M241.472 246.144h6.016V222.08A157.888 157.888 0 0 1 405.248 64h396.992A157.888 157.888 0 0 1 960 222.08V618.88a157.888 157.888 0 0 1-157.76 158.08h-25.728v5.12A177.664 177.664 0 0 1 599.04 960H241.472A177.664 177.664 0 0 1 64 782.144V423.936a177.664 177.664 0 0 1 177.472-177.792z m535.04 177.792v288.64h25.728a93.568 93.568 0 0 0 92.608-93.632V222.08c0-51.392-41.344-93.184-92.608-93.632H405.248a93.376 93.376 0 0 0-93.44 93.632v24.064H599.04a177.664 177.664 0 0 1 177.472 177.792zM128.32 782.144a114.176 114.176 0 0 0 113.152 113.408H599.04a113.28 113.28 0 0 0 113.152-113.408V423.936A114.368 114.368 0 0 0 599.04 307.968H241.472a113.92 113.92 0 0 0-113.152 115.968v358.208z" fill="currentColor"></path>
              <path d="M576 576H256v64h320z" fill="currentColor"></path>
            </svg>
          </button>
        </div>
      </div>
      <!-- 隐藏的文件上传输入框 -->
      <input
        v-if="isMyDocuments"
        ref="fileInputRef"
        type="file"
        multiple
        accept=".pdf,.doc,.docx,.txt,.md,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.gif,.mp3,.mp4,.wav,.m4a,.ogg,.webm,.avi,.mov"
        style="display: none"
        @change="handleFileInputChange"
        @click.stop
      />
    </div>
  </el-tooltip>

    <!-- 子节点(文件夹) -->
    <div
      v-if="node.type === 'folder' && isExpanded && node.children"
      class="node-children"
      :class="{ 'is-root-children': isMyDocuments }"
    >
      <file-tree-node
        v-for="child in node.children"
        :key="child.id"
        :node="child"
        :level="level + 1"
        :current-file-folder-path="currentFileFolderPath"
        :current-file-id="currentFileId"
        :selected-folder-id="selectedFolderId"
        :selected-node-ids="selectedNodeIds"
        @file-drag="(file) => $emit('file-drag', file)"
        @file-double-click="(file) => $emit('file-double-click', file)"
        @folder-context-menu="
          (event, folder) => $emit('folder-context-menu', event, folder)
        "
        @file-context-menu="
          (event, file) => $emit('file-context-menu', event, file)
        "
        @new-folder="() => $emit('new-folder')"
        @create-file="() => $emit('create-file')"
        @search-file="(keyword: string) => $emit('search-file', keyword)"
        @node-click="(node, event) => $emit('node-click', node, event)"
        @file-move="(node, targetFolderId) => $emit('file-move', node, targetFolderId)"
        @load-children="(folderId) => $emit('load-children', folderId)"
      />
    </div>
    <!-- 当"我的文档"被折叠时,添加占位元素以保持容器高度 -->
    <div
      v-if="isMyDocuments && node.type === 'folder' && !isExpanded"
      class="node-children-placeholder"
      style="height: 40px;"
    ></div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, nextTick, onMounted, onBeforeUnmount } from "vue";
import { useI18n } from "vue-i18n";
import { FolderAdd, Search, DocumentAdd, Upload, Close, Loading } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

const { t } = useI18n();

interface FileNode {
  id: string | number;
  name: string;
  type: "file" | "folder";
  path?: string;
  level: number;
  parentId?: string | number;
  size?: string;
  fileType?: string;
  modified?: string;
  originalName?: string;
  fileCount?: number;
  folderCount?: number;
  totalSize?: number;
  knowledgeStatus?: string;
  isLeaf?: boolean;
  children?: FileNode[];
}

interface Props {
  node: FileNode;
  level: number;
  currentFileFolderPath?: (string | number)[];
  currentFileId?: string | number;
  selectedFolderId?: string | number | null;
  selectedNodeIds?: Set<string>;
}

interface Emits {
  (e: "file-drag", file: FileNode): void;
  (e: "file-double-click", file: FileNode): void;
  (e: "folder-context-menu", event: MouseEvent, folder: FileNode): void;
  (e: "file-context-menu", event: MouseEvent, file: FileNode): void;
  (e: "new-folder"): void;
  (e: "create-file"): void;
  (e: "search-file", keyword: string): void;
  (e: "upload-file"): void;
  (e: "upload-files", files: File[], folderId: string | number | null): void;
  (e: "file-move", node: FileNode, targetFolderId: string | number | null): void;
  (e: "load-children", folderId: string | number): void;
  (e: "node-click", node: FileNode, event: MouseEvent): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const PROCESSING_STATUSES = new Set(["processing", "pending", "queued", "in_progress"]);
const FAILED_STATUSES = new Set(["failed", "error", "parse_failed"]);

const getKnowledgeStatusHint = (status?: string): string => {
  if (!status || status === "completed") return "";
  if (status === "not_supported") {
    return t("KnowledgeBase.statusUnsupportedHint") || "该文件不支持知识库解析";
  }
  if (PROCESSING_STATUSES.has(status)) {
    return t("KnowledgeBase.statusProcessingHint") || "文件正在解析中,请稍后再试";
  }
  if (FAILED_STATUSES.has(status)) {
    return t("KnowledgeBase.statusFailedHint") || "文件解析失败,请重试后再提问";
  }
  if (status === "not_processed") {
    return t("KnowledgeBase.statusNotProcessedHint") || "文件尚未开始解析,请稍后再试";
  }
  return t("KnowledgeBase.statusNotReady") || "文件解析未完成,无法拖拽提问";
};

// 节点加载状态
const isLoading = ref(false);
const isLoaded = computed(() => {
  return props.node.type !== 'folder' || (props.node.children && props.node.children.length > 0) || props.node.isLeaf;
});

// 计算当前节点是否为选中的文件
const isFileSelected = computed(() => {
  if (!props.currentFileId || props.node.type !== "file") {
    return false;
  }
  // 确保 ID 类型匹配(转换为字符串进行比较)
  return String(props.node.id) === String(props.currentFileId);
});

// 计算当前节点是否为选中的文件夹
const isFolderSelected = computed(() => {
  if (!props.selectedFolderId || props.node.type !== "folder") {
    return false;
  }
  // 确保 ID 类型匹配(转换为字符串进行比较)
  return String(props.node.id) === String(props.selectedFolderId);
});

// 计算当前节点是否被选中(文件或文件夹)
const isSelected = computed(() => {
  // 多选优先:有多选集合时,以多选集合为准
  if (props.selectedNodeIds && props.selectedNodeIds.size > 0) {
    return props.selectedNodeIds.has(String(props.node.id));
  }
  return isFileSelected.value || isFolderSelected.value;
});

// 计算当前节点是否为"我的文档"
const isMyDocuments = computed(() => {
  return (
    props.node.id === 0 ||
    props.node.id === -1 ||
    props.node.name === "我的文档"
  );
});

// localStorage 的 key 前缀
const STORAGE_KEY_PREFIX = "workspace_folder_expanded_";

// 获取存储 key
const getStorageKey = (nodeId: string | number): string => {
  return `${STORAGE_KEY_PREFIX}${nodeId}`;
};

// 从 localStorage 读取展开状态
const loadExpandedState = (): boolean => {
  if (props.node.type !== "folder") return false;
  
  try {
    const saved = localStorage.getItem(getStorageKey(props.node.id));
    // 如果 localStorage 中没有保存状态,根据数据结构判断是否默认展开
    if (saved === null) {
      // 判断是否为"我的文档":id为0或-1(前端转换后),或name为"我的文档"
      const isMyDocuments = 
        props.node.id === 0 || 
        props.node.id === -1 || 
        props.node.name === "我的文档";
      
      // 只展开"我的文档",它的直接子节点(第二层)默认折叠
      // 这样第二层节点的children就不会显示
      return isMyDocuments;
    }
    // 如果有保存的状态,使用保存的值
    return saved === "true";
  } catch (error) {
    console.warn("⚠️ 读取文件夹展开状态失败:", error);
    // 出错时,只展开"我的文档"
    const isMyDocuments = 
      props.node.id === 0 || 
      props.node.id === -1 || 
      props.node.name === "我的文档";
    return isMyDocuments;
  }
};

// 保存展开状态到 localStorage
const saveExpandedState = (expanded: boolean) => {
  if (props.node.type !== "folder") return;
  try {
    localStorage.setItem(getStorageKey(props.node.id), String(expanded));
  } catch (error) {
    console.warn("⚠️ 保存文件夹展开状态失败:", error);
  }
};

// 初始化展开状态(从 localStorage 读取或使用默认值 false)
const isExpanded = ref(loadExpandedState());

// 监听展开状态变化并保存
watch(
  isExpanded,
  (newValue) => {
    if (newValue && props.node.type === "folder" && !props.node.children && !props.node.isLeaf) {
      isLoading.value = true;
      emit("load-children", props.node.id);
    }
    saveExpandedState(newValue);
  },
  { immediate: false }
);

// 处理收起第一层目录事件
const handleCollapseFirstLevelEvent = () => {
  // 只处理第一层(level === 1)的文件夹节点
  if (props.level === 1 && props.node.type === "folder" && isExpanded.value) {
    isExpanded.value = false;
  }
};

// 处理展开路径中的文件夹事件
const handleExpandPathEvent = (event: CustomEvent) => {
  const path = event.detail?.path || [];
  if (path.length === 0) return;
  
  // 检查当前节点是否在路径中
  const nodeIdStr = String(props.node.id);
  const isInPath = path.some((id: string | number) => String(id) === nodeIdStr);
  
  // 如果当前节点是文件夹且在路径中,展开它
  if (isInPath && props.node.type === "folder" && !isExpanded.value) {
    isExpanded.value = true;
    console.log("展开文件夹:", props.node.name, props.node.id);
  }
};

// 添加事件监听器
onMounted(() => {
  // 初始化时确保"我的文档"默认展开(仅在首次加载时,允许用户后续手动折叠)
  if (isMyDocuments.value && props.node.type === "folder" && !isExpanded.value) {
    // 只在 localStorage 中没有保存状态时才默认展开
    const saved = localStorage.getItem(getStorageKey(props.node.id));
    if (saved === null) {
      isExpanded.value = true;
    }
  }
  
  // 如果初始状态是展开的但尚未加载子节点,触发加载
  if (isExpanded.value && props.node.type === "folder" && !props.node.children && !props.node.isLeaf) {
    isLoading.value = true;
    emit("load-children", props.node.id);
  }
  
  window.addEventListener("collapse-first-level-folders", handleCollapseFirstLevelEvent);
  window.addEventListener("expand-folders-in-path", handleExpandPathEvent as EventListener);
});

// 移除事件监听器
onBeforeUnmount(() => {
  window.removeEventListener("collapse-first-level-folders", handleCollapseFirstLevelEvent);
  window.removeEventListener("expand-folders-in-path", handleExpandPathEvent as EventListener);
});

// 展开/折叠文件夹
const toggleExpand = async (event?: MouseEvent) => {
  if (event) event.stopPropagation();
  
  if (props.node.type === "folder") {
    // 如果即将展开且尚未加载子节点,则触发加载
    if (!isExpanded.value && props.node.type === "folder" && !props.node.children && !props.node.isLeaf) {
      isLoading.value = true;
      emit("load-children", props.node.id);
    }
    isExpanded.value = !isExpanded.value;
  }
};

// 监听 node.children 变化,一旦 children 被赋值(含空数组)就停止加载状态
watch(() => props.node.children, (newChildren) => {
  if (Array.isArray(newChildren)) {
    isLoading.value = false;
  }
}, { deep: true });

const handleClick = (event: MouseEvent) => {
  // "我的文档"节点不响应点击
  if (isMyDocuments.value) {
    return;
  }

  // 文件夹:普通点击才切换展开/折叠(Ctrl/Shift 时只做选中,不折叠)
  if (
    props.node.type === "folder" &&
    !event.ctrlKey &&
    !event.metaKey &&
    !event.shiftKey
  ) {
    toggleExpand();
  }

  // 将点击事件上报给父组件处理选中逻辑(导航 + 多选)
  emit("node-click", props.node, event);
};

const handleDoubleClick = () => {
  if (props.node.type === "file") {
    emit("file-double-click", props.node);
    // 触发文件双击事件,用于清除上传文件的选中状态
    window.dispatchEvent(new CustomEvent("file-double-click", { 
      detail: { fileId: props.node.id } 
    }));
  }
};

const handleContextMenu = (event: MouseEvent) => {
  event.preventDefault();
  event.stopPropagation();

  if (props.node.type === "folder") {
    emit("folder-context-menu", event, props.node);
  } else if (props.node.type === "file") {
    emit("file-context-menu", event, props.node);
  }
};

const handleDragStart = (event: DragEvent) => {
  if (isMyDocuments.value) {
    event.preventDefault();
    return;
  }

  // 检查文件是否支持(解析中的文件允许拖拽,以便支持拖拽预览)
  if (
    props.node.type === "file" &&
    props.node.knowledgeStatus !== "completed" &&
    props.node.knowledgeStatus !== "processing"
  ) {
    event.preventDefault();
    ElMessage.warning(getKnowledgeStatusHint(props.node.knowledgeStatus));
    return;
  }

  try {
    // 设置拖拽数据
    const payload = {
      from: "FileTree",
      type: props.node.type,
      node: JSON.parse(JSON.stringify(props.node)), // 确保是纯对象
    };

    // 兼容之前的 AgentChat 逻辑(如果它是文件)
    if (props.node.type === "file") {
      Object.assign(payload, {
        from: "FileList", // 兼容 AgentChat
        files: [
          {
            id: props.node.id,
            name: props.node.name,
            type: getFileTypeFromName(props.node.name),
            size: parseFileSize(props.node.size || "0B"),
            knowledgeStatus: props.node.knowledgeStatus,
          },
        ],
      });
    }

    const jsonStr = JSON.stringify(payload);
    event.dataTransfer!.setData("application/json", jsonStr);
    event.dataTransfer!.setData("text/plain", jsonStr); // 备用格式
    event.dataTransfer!.effectAllowed = "copyMove";

    // 触发事件通知父组件
    if (props.node.type === "file") {
      emit("file-drag", props.node);
    }
  } catch (e) {
    console.error("❌ 设置拖拽数据失败:", e);
  }
};

// 获取拖拽提示文本
const getDragTooltip = (node: FileNode) => {
  if (node.type === "folder") return "";
  return getKnowledgeStatusHint(node.knowledgeStatus);
};

// 拖拽进入状态
const isDragOver = ref(false);

const handleDragOver = (event: DragEvent) => {
  // 只有文件夹才可以作为放置目标
  if (props.node.type !== "folder") return;
  
  // 阻止默认行为以允许放置
  event.preventDefault();
  
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = "move";
  }
  
  isDragOver.value = true;
};

const handleDragLeave = () => {
  isDragOver.value = false;
};

const handleDrop = (event: DragEvent) => {
  // 只有文件夹才可以作为放置目标
  if (props.node.type !== "folder") return;
  
  event.preventDefault();
  event.stopPropagation();
  isDragOver.value = false;
  
  try {
    // 尝试从多种格式获取数据
    let dataStr = event.dataTransfer?.getData("application/json");
    if (!dataStr) {
      dataStr = event.dataTransfer?.getData("text/plain");
    }
    
    if (!dataStr) {
      console.warn("⚠️ 未获取到拖拽数据");
      return;
    }
    
    const data = JSON.parse(dataStr);
    console.log("📥 放置数据:", data);
    
    // 检查是否是从文件树内部拖拽的
    // 兼容 FileList:当拖拽文件时,from 会被覆盖为 FileList 以兼容 AgentChat
    if ((data.from === "FileTree" || data.from === "FileList") && data.node) {
      const draggedNode = data.node as FileNode;
      
      const draggedId = String(draggedNode.id);
      const targetId = String(props.node.id);
      const draggedParentId = String(draggedNode.parentId);

      // 不能移动到自己
      if (draggedId === targetId) {
        console.log("🚫 不能移动到自己");
        return;
      }
      
      // 不能移动到当前的直接父节点(无意义操作)
      // 特殊处理:如果是根目录移动
      if (draggedParentId === targetId || (draggedNode.parentId === undefined && isMyDocuments.value)) {
        console.log("🚫 已经在目标目录下");
        return;
      }
      
      // 如果是"我的文档"根节点,targetFolderId 为 null (后端接口规范)
      const moveTargetId = isMyDocuments.value ? null : props.node.id;
      
      console.log(`执行移动: ${draggedNode.name}(${draggedId}) -> ${props.node.name}(${moveTargetId})`);
      emit("file-move", draggedNode, moveTargetId);
    }
  } catch (e) {
    console.error("❌ 处理放置数据失败:", e);
  }
};

// 处理我的文档操作按钮点击
const handleNewFolderClick = () => {
  emit("new-folder");
};

const handleNewFileClick = () => {
  emit("create-file");
};

// 本地搜索关键词
const localSearchKeyword = ref("");
// 是否显示搜索框
const showSearchBox = ref(false);
// 搜索输入框引用
const searchInputRef = ref<HTMLInputElement | null>(null);
// 文件上传输入框引用
const fileInputRef = ref<HTMLInputElement | null>(null);

// 点击搜索按钮
const handleSearchButtonClick = () => {
  showSearchBox.value = true;
  localSearchKeyword.value = "";
  // 聚焦到搜索输入框
  nextTick(() => {
    if (searchInputRef.value) {
      searchInputRef.value.focus();
    }
  });
};

// 取消搜索
const handleCancelSearch = () => {
  showSearchBox.value = false;
  localSearchKeyword.value = "";
  emit("search-file", "");
};

// 执行搜索(实时过滤,不需要单独执行,但保留函数以支持 Enter 键)
const handlePerformSearch = () => {
  // 搜索关键词通过 v-model 绑定到 localSearchKeyword
  // 当值改变时会通过 watch 传递给父组件
  emit("search-file", localSearchKeyword.value?.trim() || "");
};

// 监听搜索关键词变化,实时传递给父组件
watch(localSearchKeyword, (newVal) => {
  emit("search-file", newVal?.trim() || "");
});

// 收起第一层目录
const handleCollapseFirstLevel = () => {
  if (!isMyDocuments.value || !props.node.children) {
    return;
  }
  
  // 遍历"我的文档"的直接子节点
  props.node.children.forEach((child) => {
    // 只处理文件夹节点
    if (child.type === "folder") {
      // 将展开状态保存为 false
      const storageKey = getStorageKey(child.id);
      try {
        localStorage.setItem(storageKey, "false");
      } catch (error) {
        console.warn("⚠️ 保存文件夹展开状态失败:", error);
      }
    }
  });
  
  // 触发全局事件,通知所有第一层节点收起
  // 使用 CustomEvent 来通知其他组件
  window.dispatchEvent(new CustomEvent('collapse-first-level-folders'));
};

// 处理上传文件按钮点击
const handleUploadFileClick = (event: MouseEvent) => {
  // 阻止事件冒泡到父节点,避免触发 handleClick 导致折叠
  event.stopPropagation();
  // 不阻止默认行为,让文件选择对话框正常打开
  if (fileInputRef.value) {
    // 使用 setTimeout 确保在事件处理完成后再触发文件选择
    setTimeout(() => {
      if (fileInputRef.value) {
        fileInputRef.value.click();
      }
    }, 0);
  }
};

// 处理文件选择变化
const handleFileInputChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const files = target.files;
  if (!files || files.length === 0) {
    return;
  }

  // 支持的文件扩展名列表(与 accept 属性保持一致)
  const supportedExtensions = [
    "pdf", "doc", "docx", "txt", "md", 
    "xls", "xlsx", "ppt", "pptx", 
    "jpg", "jpeg", "png", "gif", "webp", "bmp", "svg",
    "mp3", "mp4", "wav", "m4a", "ogg", "webm", "avi", "mov"
  ];

  // 验证文件类型和大小
  const validFiles: File[] = [];
  const invalidFiles: { file: File; reason: string }[] = [];
  const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB

  Array.from(files).forEach((file) => {
    // 检查文件大小
    if (file.size > MAX_FILE_SIZE) {
      invalidFiles.push({
        file,
        reason: t("KnowledgeBase.fileSizeExceeded"),
      });
      return;
    }
    
    // 获取文件扩展名
    const fileName = file.name || "";
    const lastDotIndex = fileName.lastIndexOf(".");
    const extension = lastDotIndex >= 0 
      ? fileName.substring(lastDotIndex + 1).toLowerCase() 
      : "";

    // 检查扩展名是否在支持列表中
    if (extension && supportedExtensions.includes(extension)) {
      validFiles.push(file);
    } else {
      invalidFiles.push({
        file,
        reason: extension 
          ? `${t("KnowledgeBase.unsupportedFileType")}: .${extension}` 
          : t("KnowledgeBase.fileHasNoExtension"),
      });
    }
  });

  // 如果有无效文件,显示错误提示
  if (invalidFiles.length > 0) {
    const errorMessages = invalidFiles.map(
      (item) => `${item.file.name}: ${item.reason}`
    );
    ElMessage.warning(
      errorMessages.join("\n")
    );
  }

  // 如果没有有效文件,直接返回
  if (validFiles.length === 0) {
    // 清空文件输入框
    if (target) {
      target.value = "";
    }
    return;
  }

  // 上传前,确保"我的文档"是展开状态并保存
  if (isMyDocuments.value && !isExpanded.value) {
    isExpanded.value = true;
  }

  // 确定上传的目标文件夹:如果有选中的文件夹,上传到该文件夹;否则上传到根目录
  let targetFolderId: string | number | null = null;
  if (props.selectedFolderId) {
    // 如果选中的文件夹 ID 是 -1("我的文档"的前端表示),则使用 null 表示根目录
    targetFolderId = props.selectedFolderId === -1 ? null : props.selectedFolderId;
  } else {
    // 没有选中文件夹,上传到根目录("我的文档")
    targetFolderId = null;
  }
  
  // 将有效文件信息传递给父组件,由父组件统一处理上传和进度显示
  console.log("FileTreeNode: 触发 upload-files 事件", validFiles.length, "个文件,folderId:", targetFolderId);
  emit("upload-files", validFiles, targetFolderId);
  
  // 清空文件输入框,以便下次可以选择相同文件
  if (target) {
    target.value = "";
  }
};

// 获取文件图标 (返回SVG路径)
const getFileIcon = (fileName: string): string => {
  if (!fileName || !fileName.includes(".")) {
    return "/TXT_icon.svg";
  }

  const extension = fileName.split(".").pop()?.toLowerCase();
  const iconMap: Record<string, string> = {
    md: "/md_icon.svg",
    pdf: "/pdf_icon.svg",
    doc: "/word_icon.svg",
    docx: "/word_icon.svg",
    xls: "/excel_icon.svg",
    xlsx: "/excel_icon.svg",
    ppt: "/PPT_icon.svg",
    pptx: "/PPT_icon.svg",
    txt: "/TXT_icon.svg",
    jpg: "/jpg_icon.svg",
    jpeg: "/jpg_icon.svg",
    png: "/png_icon.svg",
    gif: "/gif_icon.svg",
    webp: "/jpg_icon.svg",
    bmp: "/jpg_icon.svg",
    svg: "/jpg_icon.svg",
  };

  return iconMap[extension || ""] || "/TXT_icon.svg";
};

// 获取文件类型文本
const getFileTypeText = (fileName: string): string => {
  const extension = fileName.split(".").pop()?.toLowerCase();
  const typeMap: Record<string, string> = {
    pdf: "PDF",
    doc: "DOC",
    docx: "DOC",
    xls: "XLS",
    xlsx: "XLS",
    ppt: "PPT",
    pptx: "PPT",
    md: "MD",
    txt: "TXT",
    jpg: "JPG",
    jpeg: "JPG",
    png: "PNG",
    gif: "GIF",
  };
  return typeMap[extension || ""] || "FILE";
};

// 从文件名获取文件类型(用于拖拽数据)
const getFileTypeFromName = (fileName: string): string => {
  if (!fileName || !fileName.includes(".")) {
    return "other";
  }

  const ext = fileName.split(".").pop()?.toLowerCase();
  const typeMap: Record<string, string> = {
    doc: "doc",
    docx: "doc",
    xls: "xls",
    xlsx: "xls",
    ppt: "ppt",
    pptx: "ppt",
    pdf: "pdf",
    md: "md",
  };
  return typeMap[ext || ""] || "other";
};

// 解析文件大小字符串为字节数
const parseFileSize = (sizeStr: string): number => {
  if (!sizeStr || sizeStr === "0B") return 0;

  const units: Record<string, number> = {
    B: 1,
    KB: 1024,
    MB: 1024 * 1024,
    GB: 1024 * 1024 * 1024,
  };

  // 匹配数字和单位,例如 "1.5MB" 或 "10KB"
  const match = sizeStr.match(/^([\d.]+)\s*([A-Z]+)$/i);
  if (!match || !match[1] || !match[2]) return 0;

  const value = parseFloat(match[1]);
  const unit = match[2].toUpperCase();

  return Math.floor(value * (units[unit] || 1));
};
</script>

<style scoped lang="scss">
.file-tree-node {
  width: 100%;
  overflow: visible; // 改为 visible,允许背景色溢出显示
  position: relative;
  
  // 包含"我的文档"的节点,允许 overflow 以显示操作按钮,并确保有最小高度
  &:has(.is-my-documents-root) {
    overflow-y: auto; // 让整个节点成为滚动容器
    overflow-x: hidden;
    scrollbar-gutter: stable; // 预留滚动条空间,防止内容跳动
    min-height: 40px; // 确保即使折叠时也有最小高度
    display: flex;
    flex-direction: column;
    flex: 1;
    height: 100%; // 占满父容器高度
    min-height: 0; // 允许 flex 子元素收缩
    scrollbar-width: thin;
    scrollbar-color: var(--color-border, #333) transparent;

    // 滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #333);
      border-radius: 3px;

      &:hover {
        background: var(--color-text-secondary, #666);
      }
    }
  }
  
  .node-content {
    display: flex;
    align-items: center;
    gap: 4px;
    padding-top: 6px;
    padding-bottom: 6px;
    padding-right: 8px;
    margin: 0 -8px;
    margin-right: -8px;
    margin-left: -8px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s ease;
    user-select: none;
    position: relative;
    width: calc(100% + 16px);
    box-sizing: border-box;
    // 确保背景色填满整个区域(包括负边距部分)
    background-clip: border-box;

    &:hover {
      background-color: rgba(51, 153, 255, 0.2);
    }

    &.is-selected {
      background-color: rgba(51, 153, 255, 0.3);
      
      &:hover {
        background-color: rgba(51, 153, 255, 0.3);
      }
    }

    &.is-drag-over {
      background-color: rgba(51, 153, 255, 0.4) !important;
      outline: 2px dashed var(--color-primary);
      outline-offset: -2px;
    }

    &.is-not-ready {
      opacity: 0.6;
      cursor: not-allowed;
      filter: grayscale(0.8);

      .node-name {
        color: var(--color-text);
      }

      &:hover {
        background-color: transparent !important;
      }
    }

    &.is-processing {
      opacity: 1;
      filter: none;
      background: linear-gradient(
        90deg,
        rgba(30, 112, 255, 0.03) 25%,
        rgba(30, 112, 255, 0.08) 37%,
        rgba(30, 112, 255, 0.03) 63%
      );
      background-size: 400% 100%;
      animation: processing-shimmer 2s infinite ease-out;

      .node-name {
        color: var(--color-text);
      }

      .processing-text {
        font-size: 10px;
        color: var(--color-primary);
        opacity: 0.8;
      }
    }

    // "我的文档"根目录不需要 hover 和选中效果
    &.is-my-documents-root {
      background-color: var(--color-card);
      overflow: visible;
      padding-left: 16px !important; // 添加左内边距,与其他节点对齐
      position: sticky; // 固定在顶部
      top: 0;
      z-index: 2;
      &:hover {
        background-color: var(--color-card) !important;
      }

      &.is-selected {
        background-color: var(--color-card) !important;
        
        &:hover {
          background-color: var(--color-card) !important;
        }
      }
    }

    .expand-icon {
      width: 12px;
      font-size: 10px;
      color: var(--color-text-secondary);
      transition: all 0.2s ease;
      flex-shrink: 0;
    }

    .file-icon {
      width: 16px;
      height: 16px;
      flex-shrink: 0;
      object-fit: contain;
      transition: all 0.2s ease;
      opacity: 0.8;
    }

    .node-name {
      flex: 1;
      font-size: 13px;
      color: var(--color-text);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      transition: all 0.2s ease;
      min-width: 0;

      &.is-my-documents {
        color: var(--color-text-secondary);
        flex: 0 0 auto;
        flex-shrink: 0;
        margin-right: 8px;
        max-width: fit-content;
      }
    }

    .my-documents-actions {
      display: flex;
      align-items: center;
      gap: 4px;
      padding-right: 4px;
      flex: 1 1 auto;
      flex-shrink: 1;
      margin-left: 4px;
      position: relative;
      z-index: 11;
      min-width: 0;
      max-width: 100%;
      height: 28px; // 显式设置高度,防止内容切换时抖动

      .search-box-wrapper {
        display: flex;
        align-items: center;
        gap: 2px;
        flex: 1 1 auto;
        min-width: 0;
        max-width: 100%;

        .search-input-field {
          flex: 1 1 auto;
          min-width: 0;
          padding: 4px 8px;
          height: 28px;
          line-height: 20px;
          border: 1px solid #87CEEB;
          border-radius: 4px;
          font-size: 12px;
          color: var(--color-text, #333);
          background: #fff;
          outline: none;
          transition: all 0.2s;
          box-sizing: border-box;

          &::placeholder {
            color: #999;
            font-size: 12px;
          }

          &:focus {
            border-color: #5CB3FF;
            box-shadow: 0 0 0 2px rgba(135, 206, 235, 0.2);
          }
        }

        .search-btn {
          flex-shrink: 0;
          background: none;
          border: none;
          cursor: pointer;
          padding: 6px;
          width: 28px;
          height: 28px;
          border-radius: 4px;
          transition: all 0.2s;
          display: flex;
          align-items: center;
          justify-content: center;
          color: var(--color-secondary);

          &:hover {
            background: rgba(0, 0, 0, 0.05);
          }

          &:active {
            transform: scale(0.95);
          }

          .el-icon {
            font-size: 16px;
          }
        }

        .cancel-search-btn {
          flex-shrink: 0;
          width: 28px;
          height: 28px;
          padding: 0;
          border: none;
          border-radius: 4px;
          background: transparent;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.2s;
          box-sizing: border-box;
          color: var(--color-secondary);

          .el-icon {
            font-size: 16px;
          }

          &:hover {
            background: rgba(0, 0, 0, 0.05);
          }

          &:active {
            transform: scale(0.95);
          }
        }
      }

      .action-buttons-group {
        display: flex;
        align-items: center;
        gap: 0px;
        margin-left: auto;
        flex-shrink: 0;
      }

      .action-btn {
        background: none;
        border: none;
        cursor: pointer;
        padding: 6px;
        border-radius: 4px;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--color-secondary);

        &:hover {
          background: rgba(0, 0, 0, 0.05);
        }

        &:active {
          transform: scale(0.95);
        }

        .el-icon {
          font-size: 16px;
        }

        svg.icon {
          width: 16px;
          height: 16px;
          flex-shrink: 0;
        }
      }
    }
  }

  .node-children {
    margin-left: 0;
    min-height: 0; // 允许折叠时高度为 0
    overflow: visible; // 移除滚动,由父容器处理

    // 只有根节点(我的文档)的直接子节点容器才填充空间
    &.is-root-children {
      flex: 1;
      overflow: visible; // 移除滚动,由父容器处理
      min-height: 0; // 防止 flex 子元素溢出
    }

    // 滚动条样式
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #333);
      border-radius: 3px;

      &:hover {
        background: var(--color-text-secondary, #666);
      }
    }
  }
  
  // 当"我的文档"被折叠时,确保父容器仍有高度
  &:has(.is-my-documents-root) {
    // 即使子节点被折叠,也保持最小高度
    min-height: 40px;
  }

  .node-content {
    &.is-file[draggable="true"] {
      cursor: grab;
      transition: opacity 0.2s;

      &:active {
        cursor: grabbing;
        opacity: 0.7;
      }
    }
  }
}

@keyframes processing-shimmer {
  0% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0 50%;
  }
}

@keyframes icon-pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(0.92);
    opacity: 0.8;
  }
}
</style>

<style lang="scss">
// 针对不同主题的 hover 背景色(比选中效果更淡)
.theme-light .file-tree-node .node-content:hover {
  background-color: rgba(30, 112, 255, 0.12) !important;
}

.theme-dark .file-tree-node .node-content:hover {
  background-color: rgba(51, 153, 255, 0.2) !important;
}

// 我的文档操作按钮暗黑模式下的 hover 背景色,与 workspace-toggle 保持一致
.theme-dark .file-tree-node .my-documents-actions .action-btn:hover,
.theme-dark .file-tree-node .my-documents-actions .search-btn:hover,
.theme-dark .file-tree-node .my-documents-actions .cancel-search-btn:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

// "我的文档"根目录在所有主题下都不显示 hover 效果
.theme-light .file-tree-node .node-content.is-my-documents-root:hover,
.theme-dark .file-tree-node .node-content.is-my-documents-root:hover {
  background-color: var(--color-card) !important;
}

// 针对不同主题的选中状态背景色
.theme-light .file-tree-node .node-content.is-selected {
  background-color: rgba(30, 112, 255, 0.2) !important;
  
  &:hover {
    background-color: rgba(30, 112, 255, 0.2) !important;
  }
}

.theme-dark .file-tree-node .node-content.is-selected {
  background-color: rgba(51, 153, 255, 0.3) !important;
  
  &:hover {
    background-color: rgba(51, 153, 255, 0.3) !important;
  }
}

// "我的文档"根目录在所有主题下都不显示 hover 和选中效果
.theme-light .file-tree-node .node-content.is-my-documents-root,
.theme-dark .file-tree-node .node-content.is-my-documents-root {
  &:hover {
    background-color: var(--color-card) !important;
  }

  &.is-selected {
    background-color: var(--color-card) !important;
    
    &:hover {
      background-color: var(--color-card) !important;
    }
  }
}
</style>