openWorkspaceAttachment.ts 2.7 KB
import type { Router, RouteLocationNormalizedLoaded } from "vue-router";
import { ElLoading, ElMessage } from "element-plus";
import { getFileTypeFromNameForOpen } from "./attachmentFileMeta";

export interface OpenWorkspaceAttachmentInput {
  fileName: string;
  /** Codex 工作区相对路径,有则与 file-generated-card 相同走 downloadWorkspaceFile */
  filePath?: string;
  /** 标准类型,缺省从文件名推断 */
  fileType?: string;
  /** 知识库文件 id(无 filePath 时) */
  knowledgeFileId?: number;
}

/**
 * 在 Workspace 中打开附件:Codex 路径走 open-codex-file;知识库走路由或自定义事件。
 */
export async function openWorkspaceAttachment(
  router: Router,
  route: RouteLocationNormalizedLoaded,
  input: OpenWorkspaceAttachmentInput,
): Promise<void> {
  const fileName = input.fileName;
  if (!fileName) {
    ElMessage.warning("文件信息不完整,无法打开");
    return;
  }

  const fileType =
    input.fileType && input.fileType.length > 0
      ? input.fileType.toLowerCase()
      : getFileTypeFromNameForOpen(fileName);

  const loading = ElLoading.service({
    lock: true,
    text: "正在打开文件...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  let closeLoading = true;

  try {
    if (input.filePath) {
      if (route.name === "Workspace") {
        loading.close();
        closeLoading = false;
        window.dispatchEvent(
          new CustomEvent("open-codex-file", {
            detail: {
              filePath: input.filePath,
              fileName,
              fileType,
            },
          }),
        );
      } else {
        await router.push({
          name: "Workspace",
          query: {
            fromCodex: "true",
            filePath: input.filePath,
            fileName,
            fileType,
          },
        });
      }
      return;
    }

    const fid = input.knowledgeFileId;
    if (fid != null && !Number.isNaN(Number(fid))) {
      if (route.name === "Workspace") {
        loading.close();
        closeLoading = false;
        window.dispatchEvent(
          new CustomEvent("open-workspace-knowledge-file", {
            detail: {
              fileId: fid,
              fileName,
              fileType,
            },
          }),
        );
      } else {
        await router.push({
          name: "Workspace",
          query: {
            file: String(fid),
            fileName,
            fileType,
          },
        });
      }
      return;
    }

    ElMessage.warning("文件信息不完整,无法打开");
  } catch (e: any) {
    console.error("打开文件失败:", e);
    ElMessage.error(e?.message || "打开文件失败,请重试");
  } finally {
    if (closeLoading) loading.close();
  }
}