Files
syops/frontend/src/features/chat/composables/useChatAssetImage.ts
T

98 lines
4.0 KiB
TypeScript

/**
* features/chat/composables/useChatAssetImage.ts
* 用途:管理固定资产图片检索、友好提示与预览跳转。
* 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
* 逻辑:用户点击“图片 -> 查看”后,本 composable 统一向后端索要最佳图片,再复用现有文件预览弹窗在站内展示。
*/
import { ref } from 'vue';
import type { ComputedRef } from 'vue';
import { resolveAssetImagePreview } from '../api/chat.api';
import type { SourceFileLink } from '../types/chat.types';
interface UseChatAssetImageOptions {
agentId: ComputedRef<number>;
openPreviewGallery: (files: SourceFileLink[], initialIndex?: number) => Promise<void>;
warn: (message: string) => void;
}
/**
* 把后端返回的图片检索错误翻译成业务用户能看懂的提示。
* AI 触发时机:当用户点击“图片 -> 查看”失败,但原始报错包含接口路径、外部系统术语等技术细节时调用。
* 核心逻辑:优先识别已知的配置/检索异常并转成中文说明;未知错误保留原始文本,方便排查。
* 参数与输出约束:只负责展示文案,不吞掉真实错误对象;返回值必须适合作为 toast 直接展示。
*/
function normalizeAssetImageErrorMessage(message: string): string {
const normalizedMessage = String(message || '').trim();
const lowerCaseMessage = normalizedMessage.toLowerCase();
if (lowerCaseMessage.includes('固定资产图片文档库未配置')) {
return '当前系统暂未配置固定资产图片文档库,暂时无法查看图片,请联系管理员处理。';
}
if (lowerCaseMessage.includes('请求的资源不存在')) {
return '设备管理员还未上传照片~';
}
if (lowerCaseMessage.includes('未找到资产')) {
return normalizedMessage;
}
return normalizedMessage || '检索固定资产图片失败';
}
export function useChatAssetImage(options: UseChatAssetImageOptions) {
const loading = ref(false);
/**
* 检索固定资产图片并直接打开预览。
* AI 触发时机:当用户点击聊天表格或 CSV 预览里的“图片 -> 查看”时调用。
* 核心逻辑:先向后端请求全部命中的图片文件,再把图片组交给通用 FilePreviewModal 预览。
* 参数约束:至少要提供资产编号或资产名称之一;后端负责登录外部文档库和挑选最佳图片。
*/
const openImage = async (nextAssetId: string, nextAssetName = '') => {
const normalizedAssetId = String(nextAssetId || '').trim();
const normalizedAssetName = String(nextAssetName || '').trim();
if (loading.value) return;
if (!normalizedAssetId && !normalizedAssetName) {
options.warn('当前资产缺少可用于检索图片的编号或名称');
return;
}
loading.value = true;
try {
const result = await resolveAssetImagePreview(options.agentId.value, {
asset_id: normalizedAssetId,
asset_name: normalizedAssetName,
});
const items = Array.isArray(result?.items) && result.items.length
? result.items
: (result?.item ? [result.item] : []);
if (!items.length) {
const displayName = normalizedAssetId || normalizedAssetName;
options.warn(`未找到资产 ${displayName} 的图片文件,请联系管理员补充。`);
return;
}
await options.openPreviewGallery(
items.map((item) => ({
name: item.name,
url: item.url,
actualExt: item.actual_ext,
})),
0,
);
} catch (err: unknown) {
const rawMessage = err instanceof Error ? err.message : '检索固定资产图片失败';
const message = normalizeAssetImageErrorMessage(rawMessage);
if (message === '设备管理员还未上传照片~') {
options.warn(message);
} else {
options.warn(`图片查询失败:${message}`);
}
} finally {
loading.value = false;
}
};
return {
loading,
openImage,
};
}