files.ts 25.6 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
import { service as http } from "@/utils/request";
import { fetchOssBlob, uploadFilesToTos } from "@/utils/tosUpload";

export interface FileItem {
  id: string | number;
  name: string;
  type: string;
  size: number;
  parentId?: string | number;
  createdAt?: string;
  updatedAt?: string;
  deletedAt?: string;
  [key: string]: any;
}

export interface FolderItem {
  id: string | number;
  name: string;
  folderName?: string;
  parentId?: string | number;
  children?: FolderItem[];
  files?: FileItem[];
  createdAt?: string;
  updatedAt?: string;
  [key: string]: any;
}

export interface TrashItem {
  id: string | number;
  itemName: string;
  itemType: "file" | "folder";
  size: number;
  deletedAt: string;
  originalPath?: string; // 原始路径 (后端确认将加入)
  [key: string]: any;
}

// 小工具:拼 query params,过滤 undefined
function qp(obj: any = {}) {
  const params: any = {};
  Object.keys(obj).forEach((k) => {
    const v = obj[k];
    if (v !== undefined && v !== null) params[k] = v;
  });
  return params;
}

// ==================== 文件夹 API ====================

// 获取文件夹树(不包含文件,尝试通过 list 接口获取根目录内容)
export const getFolders = async (folderId?: string | number) => {
  try {
    // 直接使用 getFiles 获取根目录内容,不再调用 search 接口以避免 400 错误
    const response = await getFiles();
    
    // 构造默认的根节点,以防接口返回数据结构不符合预期
    const defaultRoot = {
      id: -1,
      name: "我的文档",
      type: "folder",
      level: 0,
      children: [] as any[],
    };

    if (response && response.data) {
      const apiData = response.data;
      const items = Array.isArray(apiData) ? apiData : (apiData.files || apiData.items || []);
      
      // 过滤并映射文件夹项
      const folders = items
        .filter((item: any) => (item.folder || item.isFolder || item.type === 'folder' || item.is_folder))
        .map((item: any) => ({
          ...item,
          id: (item.id === 0 || item.id === "0") ? -1 : item.id,
          parentId: (item.parentId === 0 || item.parentId === "0") ? -1 : item.parentId,
          type: "folder"
        }));

      // 如果 items 为空,仍然返回默认根节点
      if (folders.length === 0 && items.length === 0) {
        response.data = defaultRoot;
      } else {
        // 使用 listToTree 构建树,并确保返回的是 Welcome.vue 期待的单根节点格式
        const tree = listToTree(folders);
        response.data = tree && tree.length > 0 ? tree[0] : defaultRoot;
      }
    } else {
      // 接口响应异常时返回默认根节点
      return { data: defaultRoot };
    }
    return response;
  } catch (error) {
    console.warn("获取文件夹列表失败,返回默认根节点:", error);
    return {
      data: {
        id: -1,
        name: "我的文档",
        type: "folder",
        level: 0,
        children: [],
      }
    };
  }
};

/**
 * 递归转换文件夹树数据格式(保留兼容性)
 */
function transformFolderTree(nodes: any): any {
  if (Array.isArray(nodes)) {
    return nodes.map(transformFolderTree);
  } else if (nodes && typeof nodes === "object") {
    const { id, name, children, folder, isFolder } = nodes;
    return {
      ...nodes,
      id: id === 0 ? -1 : id,
      name: name,
      folderName: name, // 保留兼容性
      type: (folder || isFolder) ? "folder" : "file",
      children: children ? transformFolderTree(children) : [],
    };
  }
  return nodes;
}

/**
 * 将平铺列表转换为树结构,并包裹在虚拟根节点中
 */
function listToTree(items: any[]): any[] {
  const map: Record<string, any> = {};
  const roots: any[] = [];

  // 首先建立映射
  items.forEach((item) => {
    const id = (item.id === 0 || item.id === "0") ? -1 : item.id;
    map[id] = {
      ...item,
      id,
      parentId: (item.parentId === 0 || item.parentId === "0") ? -1 : item.parentId,
      type: (item.folder || item.isFolder || item.type === 'folder') ? "folder" : "file",
      children: [],
    };
  });

  // 构造树
  items.forEach((item) => {
    const id = (item.id === 0 || item.id === "0") ? -1 : item.id;
    const parentId = (item.parentId === 0 || item.parentId === "0") ? -1 : item.parentId;
    
    if (parentId !== undefined && parentId !== null && map[parentId]) {
      map[parentId].children.push(map[id]);
    } else {
      roots.push(map[id]);
    }
  });

  // 包裹在虚拟根节点“我的文档”中,以保持与原有 tree 接口的兼容性
  return [
    {
      id: -1,
      name: "我的文档",
      type: "folder",
      level: 0,
      children: roots,
    },
  ];
}

// 获取文件夹树
export const getFileTree = (params: {
  folderId?: string | number;
  containFiles: boolean;
}) => {
  return http.get("/files/tree", { params: qp(params) });
};

// 获取完整文件层级结构
export const getFileHierarchy = async () => {
  try {
    // 优先使用 tree 接口获取全量结构
    const res: any = await getFileTree({ containFiles: false });
    
    if (res && res.data) {
      // tree 接口通常直接返回嵌套结构,我们需要适配 listToTree 期待的格式或直接使用
      const items = Array.isArray(res.data) ? res.data : [res.data];
      res.data = {
        hierarchy: listToTree(items),
      };
      return res;
    }
    throw new Error("Invalid tree response");
  } catch (error) {
    console.warn("获取全量文件层级失败,降级到 list 接口:", error);
    // 降级:只返回根目录
    const rootRes = await getFiles();
    if (rootRes && rootRes.data) {
      const items = Array.isArray(rootRes.data) ? rootRes.data : (rootRes.data.files || rootRes.data.items || []);
      rootRes.data = {
        hierarchy: listToTree(items),
      };
    }
    return rootRes;
  }
};

// 列出目录下内容(parentId 可选,缺省表示根目录)
export const getFiles = (parentId?: string | number) => {
  // 如果 parentId 是 "root" 或 -1,则表示根目录,不传 parentId
  let pid = parentId;
  if (pid === "root" || pid === -1 || pid === "-1" || pid === "0" || pid === 0) {
    pid = undefined;
  }
  return http.get("/files/list", { params: qp({ parentId: pid }) });
};

// 创建文件夹
export const createFolder = (data: {
  name: string;
  parentId?: string | number;
}) => {
  // 如果 parentId 是 "root" 或 -1,则表示根目录,不传 parentId
  let parentId = data.parentId;
  if (parentId === "root" || parentId === -1) {
    parentId = undefined;
  }

  // 使用 qp 函数过滤掉 undefined/null 参数
  return http.post(
    "/files/folders",
    qp({
      parentId: parentId,
      name: data.name,
    }),
  );
};

// 重命名文件夹
export const renameFolder = (id: string | number, name: string) => {
  return http.patch(`/files/${id}/rename`, { name });
};

// 删除文件夹(软删除)
export const deleteFolder = (id: string | number) => {
  return http.delete(`/files/${id}`);
};

// 移动文件夹
export const moveFolder = (
  id: string | number,
  targetParentId: string | number | null,
) => {
  let parentId = targetParentId;
  if (parentId === "root" || parentId === -1) {
    parentId = null;
  }
  return http.patch(`/files/${id}/move`, { targetParentId: parentId });
};

// ==================== 文件 API ====================

// 获取文件元信息
export const getFileMeta = (id: string | number, config = {}) => {
  return http.get(`/files/${id}`, config);
};

// 创建文件
export const createFile = (data: {
  name: string;
  folderId?: string | number;
  type?: string;
}) => {
  // 如果 folderId 是 "root" 或 -1,则表示根目录,不传 parentId
  let parentId = data.folderId;
  if (parentId === "root" || parentId === -1) {
    parentId = undefined;
  }

  // 使用 qp 函数过滤掉 undefined/null 参数
  return http.post(
    "/files",
    qp({
      name: data.name,
      parentId: parentId,
      type: data.type || "file",
    }),
  );
};

// 重命名文件
export const renameFile = (id: string | number, name: string) => {
  return http.patch(`/files/${id}/rename`, { name });
};

// 删除文件(软删除)
export const deleteFile = (id: string | number) => {
  return http.delete(`/files/${id}`);
};

// 批量删除文件
export const batchDeleteFiles = (ids: (string | number)[]) => {
  return http.delete("/files", { data: { ids } });
};

// 移动文件
export const moveFile = (
  id: string | number,
  targetParentId: string | number | null,
) => {
  let parentId = targetParentId;
  if (parentId === "root" || parentId === -1) {
    parentId = null;
  }
  return http.patch(`/files/${id}/move`, { targetParentId: parentId });
};

// 批量移动文件
export const moveFilesBatch = (
  targetParentId: string | number,
  ids: (string | number)[],
) => {
  return http.patch("/files/move-batch", { targetParentId, ids });
};

// 失败文件重试上传到知识库
export const retryKnowledgeUpload = (id: string | number) => {
  return http.post(`/files/${id}/retry-knowledge-upload`);
};


// 后端返回 downloadUrl 时的类型
export interface DownloadUrlResponse {
  downloadUrl: string;
  fileId?: string | number;
  fileName?: string;
}

// 下载单文件(返回 Blob 或 DownloadUrlResponse,供更底层复用)
export const downloadFileRaw = async (
  id: string | number,
  config: any = {},
): Promise<Blob | DownloadUrlResponse> => {
  // 兼容 axios 拦截器:可能直接返回 data(Blob/对象),也可能返回 AxiosResponse
  const resp: any = await http.get(`/files/${id}/download`, {
    responseType: "blob",
    timeout: 300000,
    ...config,
  });

  const data: any = resp && typeof resp === "object" && "data" in resp ? resp.data : resp;

  // 1) 若已经是 JSON 对象(例如拦截器已解析)
  if (data && typeof data === "object" && !(data instanceof Blob)) {
    if (typeof data.downloadUrl === "string") {
      return data as DownloadUrlResponse;
    }
  }

  // 2) Blob 场景(文件流 or JSON blob)
  if (data instanceof Blob) {
    // application/json 的 blob:解析成对象
    if (data.type && data.type.startsWith("application/json")) {
      const text = await data.text();
      try {
        const obj = JSON.parse(text);
        if (typeof obj?.downloadUrl === "string") {
          return obj as DownloadUrlResponse;
        }
      } catch {
        // ignore
      }
      // 解析失败则仍返回 blob,避免上层崩
      return data;
    }

    // 普通文件 blob
    return data;
  }

  // 3) 兜底:若 data 里带 downloadUrl
  if (data && typeof data?.downloadUrl === "string") {
    return data as DownloadUrlResponse;
  }

  // 兜底返回原值(通常不会到这里)
  return data as any;
};

// 获取单文件内容为 Blob(用于预览:PDF/图片等)
// - 后端直出文件流:直接返回 Blob
// - 后端返回 JSON(downloadUrl):从 OSS/TOS 再拉取为 Blob
export const downloadFile = async (
  id: string | number,
  config: any = {},
): Promise<Blob> => {
  const ret = await downloadFileRaw(id, config);

  // 文件流场景
  if (ret instanceof Blob) {
    return ret;
  }

  // OSS/TOS 链接场景
  const url = (ret as any)?.downloadUrl;
  if (!url) {
    throw new Error("downloadFile: missing downloadUrl in response");
  }

  const fileName = (ret as any)?.fileName || config?.fileName || `file-${id}`;
  return await fetchOssBlob({ downloadUrl: url, fileName });
};

// 打包下载多个文件(夹)为 zip
export const downloadAsZip = (
  ids: (string | number)[],
  keepStructure = true,
) => {
  return http.get("/files/download/zip", {
    params: { ids, keepStructure },
    paramsSerializer: (params) => {
      const usp = new URLSearchParams();
      (params.ids || []).forEach((v: any) => usp.append("ids", v));
      if (params.keepStructure !== undefined)
        usp.append("keepStructure", params.keepStructure);
      return usp.toString();
    },
    responseType: "blob",
    timeout: 600000,
  });
};

// 下载文件夹(打包为 zip)
export const downloadFolder = (folderId: string | number) => {
  const id = Number(folderId);
  if (id === -1) {
    throw new Error("暂不支持根目录下载!");
  }
  return downloadAsZip([id]);
};

// ==================== 上传 API ====================

// 小工具:生成随机 ID(保留备用)
// function genSubId() {
//   return (
//     crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2)
//   ).replace(/-/g, "");
// }

// 创建上传会话
export const createUploadSession = () => {
  return http.post("/files/upload/session");
};

// 上传单文件(带 uploadId)
export const uploadFile = (data: {
  file: File;
  uploadId: string;
  parentId?: string | number;
  fileUploadId?: string;
  onUploadProgress?: (evt: any) => void;
}) => {
  const formData = new FormData();
  formData.append("file", data.file);

  return http.post("/files/upload", formData, {
    params: {
      parentId: data.parentId,
      uploadId: data.uploadId,
      fileUploadId: data.fileUploadId,
    },
    headers: {
      "Content-Type": "multipart/form-data",
    },
    onUploadProgress: data.onUploadProgress,
  });
};

// 批量上传文件
export const uploadBatch = (data: {
  files: File[];
  uploadId: string;
  parentId?: string | number;
  fileUploadIds?: string[];
  onUploadProgress?: (evt: any) => void;
}) => {
  const formData = new FormData();
  data.files.forEach((f) => formData.append("files", f));

  return http.post("/files/upload/batch", formData, {
    params: {
      parentId: data.parentId,
      uploadId: data.uploadId,
    },
    headers: {
      "Content-Type": "multipart/form-data",
    },
    onUploadProgress: data.onUploadProgress,
  });
};

// SSE 订阅上传/知识库进度
export const subscribeProgress = (
  uploadId: string,
  onMessage: (evt: MessageEvent) => void,
  onError?: (err: Event) => void,
) => {
  // 构造完整的 SSE URL
  const base = http.defaults.baseURL || "/api";
  const origin = base.startsWith("http") ? "" : window.location.origin;
  const url = `${origin}${base}/files/upload/progress/${encodeURIComponent(uploadId)}`;

  const es = new EventSource(url, { withCredentials: false });
  es.onmessage = (evt) => onMessage && onMessage(evt);
  es.onerror = (err) => {
    onError && onError(err);
  };
  return es;
};

// 归一化单文件进度数据(保留备用)
// function normalizeSingleFile(payload: any) {
//   const { uploadId, data = {} } = payload;
//   const file =
//     Array.isArray(data.files) && data.files.length ? data.files[0] : null;

//   // 进度优先取 file.fileOverallPercent,其次 knowledge/local
//   const percentage =
//     (file &&
//       (file.fileOverallPercent ??
//         file.knowledgePercent ??
//         file.localPercent)) ??
//     data.batchOverallPercent ??
//     0;

//   // 阶段 & 文案
//   let stage = "LOCAL_UPLOADING";
//   let message = "正在上传...";
//   if (file && file.knowledgePercent != null) {
//     stage = "KNOWLEDGE_PROCESSING";
//     message = "知识库处理中...";
//   }
//   if (
//     percentage >= 100 ||
//     (data.finishedFiles >= data.expectedFiles && data.expectedFiles > 0)
//   ) {
//     stage = "UPLOAD_COMPLETED";
//     message = "上传完成";
//   }

//   return {
//     uploadId,
//     percentage,
//     stage,
//     message,
//     totalBytes: file?.totalBytes || data.totalBytes,
//     uploadedBytes: file?.uploadedBytes || data.uploadedBytes,
//     fileId: file?.fileId,
//   };
// }

// 归一化批量上传进度数据
function normalizeBatch(payload: any) {
  const { data = {} } = payload;
  const fileProgresses: Record<string, any> = {};

  let totalLocalPercent = 0;
  let fileCount = 0;

  if (Array.isArray(data.files)) {
    data.files.forEach((f: any) => {
      fileCount++;
      const uid = f.uploadId || f.fileId || f.fileName;
      // 仅使用本地上传进度,不关联知识库处理进度
      const pct = f.localPercent ?? 0;
      totalLocalPercent += pct;

      fileProgresses[uid] = {
        percentage: pct,
        stage: f.localPercent >= 100 ? "UPLOAD_COMPLETED" : "LOCAL_UPLOADING",
        status: pct >= 100 ? "COMPLETED" : "UPLOADING",
        message: pct >= 100 ? "上传完成" : "正在上传...",
        totalBytes: f.totalBytes,
        uploadedBytes: f.uploadedBytes,
        fileId: f.fileId,
        knowledgeStage: f.knowledgeStage,
        knowledgePercent: f.knowledgePercent, // 保留知识库进度,以防后续其他地方需要
        totalChunks: f.totalChunks,
        uploadedChunks: f.uploadedChunks,
      };
    });
  }

  // 整体进度也改为基于本地上传进度计算
  const overallPercentage =
    fileCount > 0 ? Math.floor(totalLocalPercent / fileCount) : 0;
  const totalFiles = data.expectedFiles ?? 0;
  const completedFiles = data.finishedFiles ?? 0;

  return {
    overallPercentage,
    totalFiles,
    completedFiles,
    fileProgresses,
  };
}

// 监听批量上传进度
export const listenBatchProgress = (
  batchId: string,
  onProgress: (progress: any, eventType: string) => void,
  onComplete: (progress: any) => void,
  onError: (error: any) => void,
) => {
  let closed = false;
  const es = subscribeProgress(
    batchId,
    (evt) => {
      if (closed) return;
      try {
        const payload = JSON.parse(evt.data);
        const { type, data = {} } = payload;

        // 转发单文件错误事件(用于上传阶段失败;解析阶段错误由前端决定是否忽略)
        if (type === "error") {
          onProgress &&
            onProgress(
              {
                fileId: data.fileId,
                status: "FAILED",
                message: data.message,
              },
              "file-error",
            );
        }

        const norm = normalizeBatch(payload);
        onProgress && onProgress(norm, "batch-progress");

        const overall = norm.overallPercentage ?? 0;
        const allDone =
          overall >= 100 ||
          (data.finishedFiles >= data.expectedFiles && data.expectedFiles > 0);

        if (allDone) {
          onComplete &&
            onComplete({
              ...norm,
              status: "COMPLETED",
              totalFiles: norm.totalFiles,
              completedFiles: norm.totalFiles,
              failedFiles: 0,
            });
          es.close();
          closed = true;
          return;
        }
      } catch (error) {
        console.error("解析进度数据失败:", error);
      }
    },
    (err) => {
      if (!closed) {
        onError &&
          onError({
            status: "ERROR",
            message: "进度监听出错",
            detail: err,
          });
        es.close();
        closed = true;
      }
    },
  );

  return {
    close: () => {
      closed = true;
      es.close();
    },
  };
};

// 批量上传文件(包装方法,处理会话创建)
export const uploadBatchFiles = async (
  files: File[],
  parentId?: string | number,
  options?: {
    // 一拿到 uploadId 就回调(在真正开始 /files/upload/batch 前)
    onUploadId?: (uploadId: string) => void;
    // 上传请求本身(浏览器 -> 后端)的进度,用于在 SSE 首包前也有进度展示
    onRequestUploadProgress?: (info: {
      percent: number; // 0-100
      loaded: number;
      total?: number;
    }) => void;
  },
) => {
  // 转换 parentId
  let folderId = parentId;
  if (typeof folderId === "string" && folderId === "root") {
    folderId = undefined;
  } else if (typeof folderId === "number" && folderId === -1) {
    folderId = undefined;
  }

  // 1. 创建上传会话
  const session = await createUploadSession();
  const uploadId = (session as any).data.uploadId;

  console.log("创建上传会话,uploadId:", uploadId);

  // 提前暴露 uploadId,便于前端在上传请求期间就开始订阅 SSE 进度,避免进度跳变
  try {
    options?.onUploadId?.(uploadId);
  } catch (e) {
    console.warn("onUploadId 回调执行失败,但不影响上传流程", e);
  }

  // 2. 开始批量上传
  const response = await uploadBatch({
    files,
    uploadId,
    parentId: folderId,
    onUploadProgress: (evt: any) => {
      try {
        const loaded = Number(evt?.loaded ?? 0);
        const totalRaw = evt?.total;
        const total =
          typeof totalRaw === "number" && Number.isFinite(totalRaw) && totalRaw > 0
            ? totalRaw
            : undefined;
        const percent = total ? Math.floor((loaded / total) * 100) : 0;
        options?.onRequestUploadProgress?.({ percent, loaded, total });
      } catch (e) {
        // ignore
      }
    },
  });

  console.log("批量上传响应:", response);

  return {
    ...response,
    code: 200,
    uploadId, // 返回 uploadId 用于进度监听
  };
};

// ==================== TOS 直传 API ====================

// 获取 TOS STS 临时凭证
export const getTosCredential = (sessionName: string) => {
  return http.get("/files/tos-credential", { params: { sessionName } });
};

// 注册直传完成的文件
export const registerUploadedFile = (data: {
  id?: number | null;
  parentId?: number | null;
  originalFileName: string;
  storageKey: string;
  storageUrl: string;
  fileSize: number;
  mimeType: string;
}) => {
  return http.post("/files/register-upload", data);
};

// ==================== 回收站 API ====================

// 获取回收站列表
export const listTrash = () => {
  return http.get("/files/trash");
};

// 清空回收站
export const emptyTrash = () => {
  return http.delete("/files/trash");
};

// 还原单个文件(夹)
export const restore = (id: string | number) => {
  return http.post(`/files/${id}/restore`);
};

// 批量还原
export const restoreBatch = (ids: (string | number)[]) => {
  return http.post("/files/restore-batch", { ids });
};

// 批量删除回收站文件(永久删除)
export const trashDeleteBatch = (ids: (string | number)[]) => {
  return http.delete("/files/trash-delete-batch", { data: { ids } });
};

// ==================== 文件内容 API ====================

// 获取文件内容
export const getFileContent = (fileId: string | number) => {
  return http.get(`/files/${fileId}/content`);
};

// 通过 TOS 直传更新文件(上传到 TOS 后调用 register-upload 更新元数据)
const replaceFileViaTos = async (fileId: string | number, file: File) => {
  const results = await uploadFilesToTos([file]);
  const r = results[0];
  if (!r) throw new Error("TOS 上传失败:无返回结果");

  return registerUploadedFile({
    id: Number(fileId),
    originalFileName: r.originalFileName,
    storageKey: r.storageKey,
    storageUrl: r.storageUrl,
    fileSize: r.fileSize,
    mimeType: r.mimeType,
  });
};

// 替换文件(上传新文件覆盖原文件)
// storageType: 传入文件的存储类型,非 "LOCAL" 则走 TOS 直传路径
export const replaceFile = (
  fileId: string | number,
  file: File,
  storageType?: string,
) => {
  // 非 LOCAL 存储的文件走 TOS 直传
  if (storageType && storageType !== "LOCAL") {
    return replaceFileViaTos(fileId, file);
  }

  const formData = new FormData();
  formData.append("file", file);
  return http.put(`/files/${fileId}/replace`, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
};

// 保存文件内容(将内容转换为 File 对象并替换文件)
// storageType: 传入文件的存储类型,非 "LOCAL" 则走 TOS 直传路径
export const saveFileContent = async (
  fileId: string | number,
  data: { content: string; fileName: string },
  storageType?: string,
) => {
  try {
    // 根据文件扩展名推断 MIME 类型
    const ext = (data.fileName || "").split(".").pop()?.toLowerCase() || "";
    const mimeMap: Record<string, string> = {
      md: "text/markdown",
      json: "application/json",
      js: "application/javascript",
      jsx: "application/javascript",
      ts: "application/typescript",
      tsx: "application/typescript",
      html: "text/html",
      htm: "text/html",
      css: "text/css",
      xml: "application/xml",
      py: "text/x-python",
      sql: "text/x-sql",
      txt: "text/plain",
    };
    const mimeType = mimeMap[ext] || "text/plain";

    // 创建一个包含文本内容的 File 对象
    const blob = new Blob([data.content], { type: mimeType });
    const file = new File([blob], data.fileName || "document.md", {
      type: mimeType,
    });

    // 使用 replaceFile 方法替换文件
    return await replaceFile(fileId, file, storageType);
  } catch (error) {
    console.error("保存文件内容失败:", error);
    throw error;
  }
};

// ==================== 搜索 API ====================

// 搜索文件
export const searchFiles = (params: {
  keyword: string;
  page?: number;
  size?: number;
  fileTypes?: string[];
  folderOnly?: boolean;
  timeFilter?: string;
  customStartTime?: string;
  customEndTime?: string;
}) => {
  // 如果 keyword 为空且不是仅搜索文件夹模式,部分后端可能会返回 400
  // 这里做一个基础保护,如果 keyword 为空则赋予一个空值避免请求失败
  const safeParams = {
    ...params,
    keyword: params.keyword || "",
    page: params.page || 1,
    size: params.size || 20
  };
  return http.post("/files/search", safeParams);
};

// ==================== 辅助函数 ====================

// 文件列表转换(用于回收站)
export const transformFileList = (files: any[]): TrashItem[] => {
  if (!Array.isArray(files)) return [];
  return files.map((file) => {
    // 统一路径字段,尝试从后端可能的多个字段中提取
    const originalPath = file.originalPath || file.parentPath || file.path;
    return {
      ...file,
      id: file.id,
      itemName: file.name || file.fileName || "",
      itemType: file.type === "folder" || file.isFolder ? "folder" : "file",
      size: file.size || 0,
      deletedAt: file.deletedAt || file.deleteTime || "",
      originalPath,
    };
  });
};