| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import { getFilePathApi } from '@/core/api/sys/login';
- import { resolveDownloadErrorMessage } from '@/core/utils/file/download';
- import { isDesktopDialogAvailable, openLocalPath } from '@/core/utils/desktop/openFile';
- const normalizeOfficeFileKey = (value: string) =>
- value
- .trim()
- .toLowerCase()
- .replace(/[_\-\s]/g, '');
- const OFFICE_FILE_ID_KEY_SET = new Set(['fileid']);
- export const normalizeOfficeFileId = (value: unknown) => {
- const text = String(value ?? '').trim();
- if (!text || text === '-' || text === 'null' || text === 'undefined') return undefined;
- return text;
- };
- const readOfficeFileIdFromRecord = (record: Record<string, any>) => {
- for (const [key, value] of Object.entries(record)) {
- if (OFFICE_FILE_ID_KEY_SET.has(normalizeOfficeFileKey(key))) {
- const fileId = normalizeOfficeFileId(value);
- if (fileId) return fileId;
- }
- }
- return undefined;
- };
- export const resolveOfficeFileId = (source: unknown): string | undefined => {
- if (!source || typeof source !== 'object') return undefined;
- const queue: Array<Record<string, any>> = [source as Record<string, any>];
- const visited = new Set<Record<string, any>>();
- while (queue.length) {
- const current = queue.shift();
- if (!current || visited.has(current)) continue;
- visited.add(current);
- const directFileId = readOfficeFileIdFromRecord(current);
- if (directFileId) return directFileId;
- ['raw', 'record', 'source', 'data'].forEach((key) => {
- const nested = current[key];
- if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
- queue.push(nested as Record<string, any>);
- }
- });
- }
- return undefined;
- };
- /**
- * 按文件ID打开文件:后端查库解析出本机绝对路径,再交给系统默认关联程序打开。
- *
- * <p>只传文件ID,服务端路径由后端定位(工作表行没有 filePath 时后端自动回退到所属文件根)。
- * 非桌面端直接抛「请在桌面客户端内打开」,不做浏览器另存回退。
- *
- * @param fileId 文件/工作表ID(file_info.id)
- */
- export const openOfficeFileById = async (fileId: string | number) => {
- if (!isDesktopDialogAvailable()) {
- throw new Error('当前环境不可用:请在桌面客户端内打开');
- }
- try {
- const { path } = await getFilePathApi(fileId);
- await openLocalPath(path);
- } catch (error: any) {
- // 后端以 JSON 报错时(如文件不存在),把原始 message 提取出来
- throw new Error(await resolveDownloadErrorMessage(error, '文件打开失败'));
- }
- };
- export const getOpenOfficeFileErrorMessage = (error: any, fallback = '文件打开失败') =>
- error?.response?.data?.message || error?.message || fallback;
|