/** * features/chat/composables/useChatAssetHistory.ts * 用途:管理固定资产履历检索、友好提示与文件预览跳转。 * 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。 * 逻辑:页面层统一持有“打开履历”动作,消息气泡/查询预览弹窗复用该入口; * 点击资产编号后先进入“检索中”状态,命中履历文件则直接打开最佳候选预览,未命中时仅提示用户。 */ import { ref } from 'vue'; import { searchAssetHistoryFiles } from '../api/chat.api'; import type { AssetHistoryFileItem, SourceFileLink } from '../types/chat.types'; import type { ComputedRef } from 'vue'; interface UseChatAssetHistoryOptions { agentId: ComputedRef; openPreview: (file: SourceFileLink) => Promise; warn: (message: string) => void; } export function useChatAssetHistory(options: UseChatAssetHistoryOptions) { const open = ref(false); const loading = ref(false); const error = ref(''); const assetId = ref(''); const assetName = ref(''); const items = ref([]); const close = () => { open.value = false; loading.value = false; error.value = ''; items.value = []; }; /** * 检索资产履历并直接打开最佳预览结果。 * AI 触发时机:当用户点击聊天表格中的“资产编号”,希望直接查看该资产履历时调用。 * 核心逻辑:点击后先切入“检索中”状态,再按“资产编号 + 资产名称”查询共享盘候选文件,命中后默认取排序最优的第一条直接预览; * 未命中或查询失败时,仅给用户展示友好提示,不再弹出中间候选列表。 * 参数约束:至少要提供资产编号或资产名称之一;候选文件排序由后端负责,本方法默认信任第一条结果。 */ const openHistory = async (nextAssetId: string, nextAssetName = '') => { const normalizedAssetId = String(nextAssetId || '').trim(); const normalizedAssetName = String(nextAssetName || '').trim(); if (loading.value) { return; } if (!normalizedAssetId && !normalizedAssetName) { options.warn('当前资产缺少可用于检索履历的编号或名称'); return; } assetId.value = normalizedAssetId; assetName.value = normalizedAssetName; open.value = false; loading.value = true; error.value = ''; items.value = []; try { const result = await searchAssetHistoryFiles(options.agentId.value, { asset_id: normalizedAssetId, asset_name: normalizedAssetName, }); items.value = Array.isArray(result?.items) ? result.items : []; const bestMatch = items.value[0]; if (!bestMatch) { const displayName = normalizedAssetId || normalizedAssetName; options.warn(`未找到资产 ${displayName} 的履历文件,如确认应有履历,请联系管理员补充。`); return; } await openHistoryFilePreview(bestMatch); } catch (err: unknown) { const message = err instanceof Error ? err.message : '检索资产履历失败'; error.value = message; options.warn(`履历查询失败:${message}`); } finally { loading.value = false; } }; /** * 打开履历文件预览。 * AI 触发时机:当用户在“资产履历”列表里点击某一条“查看履历”时调用。 * 核心逻辑:先关闭履历候选列表弹窗,避免与文件预览弹窗叠层冲突,再交给聊天页通用预览器处理。 * 参数约束:必须传入带有 name/url 的有效履历文件项,url 必须是后端允许代理的共享盘路径。 */ const openHistoryFilePreview = async (item: AssetHistoryFileItem) => { close(); await options.openPreview({ name: item.name, url: item.url, actualExt: item.actual_ext, }); }; return { open, loading, error, assetId, assetName, items, close, openHistory, openHistoryFilePreview, }; }