Files
syops/frontend/src/features/chat/components/messages/ChatMessageBubble.vue
T

1073 lines
41 KiB
Vue

/**
* features/chat/components/messages/ChatMessageBubble.vue
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
* 依赖:Vue computed、lucide 图标、Leave/Shipping 子消息组件、chat.types 与页面级 handlers。
* 逻辑:由 ChatMessageList 按消息逐条挂载;正文渲染与特殊交互委托 useChatPageMarkdown 等页面编排层提供的 handlers。
*/
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
import TrainingExamQuestionMessage, { type TrainingHandlers } from './TrainingExamQuestionMessage.vue';
import TrainingVideoMessage from './TrainingVideoMessage.vue';
import TrainingSummaryMessage from './TrainingSummaryMessage.vue';
import TrainingResultCard from './TrainingResultCard.vue';
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
export interface ChatMessageBubbleHandlers {
renderMarkdown: (text: string) => string;
onMarkdownClick: (event: MouseEvent) => void;
getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] };
downloadInlineFile: (file: InlineDownloadFile) => void;
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
canOpenQueryPreview: (msg: ChatMessage) => boolean;
getQueryPreviewSummary: (msg: ChatMessage) => string;
openQueryPreviewDialog: (msg: ChatMessage) => void;
shippingActionButtonClass: (variant?: string) => string;
onShippingActionClick: (msg: ChatMessage, action: NonNullable<ChatMessage['shipping_actions']>[number]) => void;
getDisplayRetrieverResources: (msg: ChatMessage) => Array<Record<string, unknown>>;
getSourceLinks: (resources: Array<Record<string, unknown>>) => SourceFileLink[];
shouldExpandSourceDetails: (msg: ChatMessage) => boolean;
getSourceTitle: (doc: Record<string, unknown>) => string;
getSourceMeta: (doc: Record<string, unknown>) => string;
getSourceBrief: (doc: Record<string, unknown>) => string;
openPreview: (file: SourceFileLink) => void;
}
const {
message,
index,
messageCount,
isThinking,
showChatRating,
copiedIndex,
isShippingNoticeAgent,
handlers,
leaveHandlers,
shippingHandlers,
} = defineProps<{
message: ChatMessage;
index: number;
messageCount: number;
isThinking: boolean;
showChatRating: boolean;
copiedIndex: number | null;
isShippingNoticeAgent: boolean;
handlers: ChatMessageBubbleHandlers;
leaveHandlers: LeaveMessageHandlers;
shippingHandlers: ShippingMappingHandlers;
trainingHandlers: TrainingHandlers;
}>();
const emit = defineEmits<{
copy: [];
edit: [content: string];
resend: [content: string];
regenerate: [];
'open-feedback': [];
}>();
const isLeaveMessage = computed(() =>
message.type === 'leave-form'
|| message.type === 'leave-confirmation'
|| message.type === 'leave-result',
);
const isTrainingExamMessage = computed(() => {
if (message.role !== 'assistant') return false;
// 必须是最后一条助手消息,且包含题目特征文字(确保只在当前正在进行的题目上显示交互组件)
if (!isLastMessage.value) return false;
const content = message.content || '';
return content.includes('正在进行新人培训考试')
|| (content.includes('第') && content.includes('题') && (content.includes('共') || content.includes('/')));
});
const isTrainingVideoMessage = computed(() => {
if (message.role !== 'assistant') return false;
// 只要包含特定引导文案,就显示视频占位符,不限于最后一条消息
const content = message.content || '';
return content.includes('专属入职培训助手') || (content.includes('看视频') && content.includes('已看完'));
});
const isTrainingSummaryMessage = computed(() => {
if (message.role !== 'assistant') return false;
const content = message.content || '';
return content.includes('完成视频学习') || content.includes('复盘重点知识') || content.includes('复盘知识点') || content.includes('总结重点知识');
});
const isTrainingResultMessage = computed(() => {
if (message.role !== 'assistant') return false;
// 只要是结果文案,就显示结算卡片,不限于最后一条消息
const content = message.content || '';
return content.includes('考试结束') || content.includes('顺利通过新人考核');
});
const retrieverResources = computed(() => handlers.getDisplayRetrieverResources(message));
const sourceLinks = computed(() => handlers.getSourceLinks(retrieverResources.value));
const showSourceSection = computed(() => {
if (message.role !== 'assistant' || isLeaveMessage.value) return false;
return retrieverResources.value.length > 0
|| (message.attribution_parts?.length ?? 0) > 0
|| sourceLinks.value.length > 0;
});
const showActions = computed(() => message.type !== 'leave-form');
const showShippingActionsPanel = computed(() =>
isShippingNoticeAgent
&& !!message.shipping_actions?.length
&& message.type !== 'shipping-match-result',
);
const isLastMessage = computed(() => index === messageCount - 1);
const isCopied = computed(() => copiedIndex === index);
const renderedMarkdown = computed(() => (
message.role === 'assistant' ? handlers.renderMarkdown(message.content) : ''
));
const inlineDownloadFiles = computed(() => (
message.role === 'assistant' ? handlers.getInlineDownloadFiles(message.content).files : []
));
const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() => ({
getPayload: shippingHandlers.getParseReviewPayload,
updateHeader: shippingHandlers.updateHeader,
updateLine: shippingHandlers.updateLine,
addLine: shippingHandlers.addLine,
removeLine: shippingHandlers.removeLine,
}));
interface InlinePreviewTable {
rawHeaders: string[];
headers: string[];
allRows: string[][];
totalRows: number;
isCsv: boolean;
}
interface InlineFileEntry {
file: InlineDownloadFile;
fileIndex: number;
table: InlinePreviewTable;
}
const FIXED_ASSET_HEADER_LABELS: Record<string, string> = {
id: '序号',
asset_id: '资产编号',
asset_no: '资产编号',
asset_name: '资产名称',
currency_amount: '本币金额(元)',
specification: '规格型号',
account_period: '账套',
operating_center_code: '账套',
custodian_person: '保管人',
custodian_name: '保管人',
custodian_dept: '保管部门',
department_name: '保管部门',
storage_location: '存放位置名称',
location_name: '存放位置名称',
asset_status: '资产状态',
reserved_field: '预留残值',
residual_value: '预留残值',
supplier: '供应商',
vendor_name: '供应商',
asset_nature: '资产性质',
nature: '资产性质',
amount_local: '本币金额(元)',
unit_price: '本币金额(元)',
quantity: '数量',
unit: '计量单位',
unit_of_measurement: '计量单位',
acquisition_date: '取得时间',
acquired_date: '取得时间',
accounting_date: '入账日期',
recorded_date: '入账日期',
created_at: '创建时间',
created_time: '创建时间',
updated_at: '更新时间',
snapshot_time: '快照时间',
};
const FIXED_ASSET_CANONICAL_COLUMNS = [
{ key: 'id', label: '序号', aliases: ['id'] },
{ key: 'asset_id', label: '资产编号', aliases: ['asset_id', 'asset_no'] },
{ key: 'asset_name', label: '资产名称', aliases: ['asset_name'] },
{ key: 'custodian_person', label: '保管人', aliases: ['custodian_person', 'custodian_name'] },
{ key: 'custodian_dept', label: '保管部门', aliases: ['custodian_dept', 'department_name'] },
{ key: 'account_period', label: '账套', aliases: ['account_period', 'operating_center_code'] },
{ key: 'supplier', label: '供应商', aliases: ['supplier', 'vendor_name'] },
{ key: 'asset_status', label: '资产状态', aliases: ['asset_status'] },
{ key: 'quantity', label: '数量', aliases: ['quantity'] },
{ key: 'acquisition_date', label: '取得时间', aliases: ['acquisition_date', 'acquired_date'] },
] as const;
const INLINE_DIALOG_PAGE_SIZE = 15;
/**
* 解析 CSV 行,支持双引号包裹字段与转义双引号。
* 核心逻辑:逐字符扫描,避免简单 split(',') 破坏包含逗号的单元格。
* @param line - 单行 CSV 文本。
* @returns 当前行拆分后的列值数组。
*/
function parseCsvLine(line: string): string[] {
const cells: string[] = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i += 1) {
const char = line[i];
const nextChar = line[i + 1];
if (char === '"') {
if (inQuotes && nextChar === '"') {
current += '"';
i += 1;
} else {
inQuotes = !inQuotes;
}
continue;
}
if (char === ',' && !inQuotes) {
cells.push(current);
current = '';
continue;
}
current += char;
}
cells.push(current);
return cells;
}
/**
* 将固定资产 CSV 的英文列名转换成面向业务展示的中文列名。
* 核心逻辑:优先命中已知字段映射;未知字段保留原值,避免误伤其他 Agent 的文件。
* @param header - CSV 原始表头。
* @returns 中文表头或原始表头。
*/
function localizeInlineTableHeader(header: string): string {
const normalizedHeader = String(header || '').trim().toLowerCase();
return FIXED_ASSET_HEADER_LABELS[normalizedHeader] || header || '-';
}
/**
* 将固定资产时间字段统一裁剪为“年月日”。
* 核心逻辑:优先提取 `YYYY-MM-DD` 或 `YYYY/MM/DD` 形式;若无法识别标准日期,则保留原始值避免误改内容。
* @param value - 原始时间文本。
* @returns 仅保留年月日的展示值。
*/
function formatInlineDateOnly(value: string): string {
const normalized = String(value ?? '').trim();
if (!normalized) return '';
const dateMatch = normalized.match(/(\d{4})[-/](\d{1,2})[-/](\d{1,2})/);
if (!dateMatch) return normalized;
const year = dateMatch[1] || '';
const month = dateMatch[2] || '';
const day = dateMatch[3] || '';
if (!year || !month || !day) return normalized;
return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
}
/**
* 统一表格中的空值展示。
* 核心逻辑:对空串、短横线、null/none 等占位值统一显示“无”,但保留数字 0 与正常文本。
* @param value - 原始单元格值。
* @returns 归一化后的展示值。
*/
function normalizeInlineTableCell(value: string): string {
const normalized = String(value ?? '').trim();
if (!normalized) return '无';
if (['-', '--', 'null', 'none', 'n/a', 'na'].includes(normalized.toLowerCase())) return '无';
return normalized;
}
/**
* 兼容一批固定资产字段别名,定位筛选栏对应的列索引。
* 核心逻辑:同一业务字段可能出现多种英文命名,命中任一别名即可。
* @param headers - CSV 原始表头。
* @param aliases - 候选字段名列表。
* @returns 命中的列索引;未找到时返回 -1。
*/
function findInlineTableHeaderIndex(headers: string[], aliases: string[]): number {
const normalizedAliases = aliases.map((item) => item.trim().toLowerCase());
return headers.findIndex((header) => normalizedAliases.includes(String(header || '').trim().toLowerCase()));
}
/**
* 判断当前 CSV 是否为固定资产明细导出结构。
* 核心逻辑:按业务关键列做命中检测,只有命中固定资产列集时才收敛为指定 10 列,避免影响其他 Agent 的 CSV 预览。
* @param headers - CSV 原始表头。
* @returns 是否按固定资产明细规则处理。
*/
function isFixedAssetInlineTable(headers: string[]): boolean {
return FIXED_ASSET_CANONICAL_COLUMNS
.filter((column) => column.key !== 'id')
.filter((column) => findInlineTableHeaderIndex(headers, [...column.aliases]) >= 0)
.length >= 5;
}
/**
* 将用户输入与单元格内容统一成可搜索的文本。
* 核心逻辑:统一 trim + lowerCase,避免筛选时受大小写和首尾空白干扰。
* @param value - 原始值。
* @returns 可用于 includes 的归一化字符串。
*/
function normalizeInlineFilterKeyword(value: string): string {
return String(value ?? '').trim().toLowerCase();
}
/**
* 将二维表格重新序列化为 CSV 文本,并自动处理逗号、换行、双引号转义。
* 核心逻辑:展示层与下载层共用这一序列化逻辑,保证用户看到的列头与下载文件完全一致。
* @param rows - 需要写回 CSV 的二维数组,首行为表头。
* @returns 可直接下载的 CSV 文本。
*/
function serializeCsvRows(rows: string[][]): string {
return rows.map((row) => row.map((cell) => {
const value = String(cell ?? '');
if (/[",\r\n]/.test(value)) {
return `"${value.replace(/"/g, '""')}"`;
}
return value;
}).join(',')).join('\r\n');
}
/**
* 按固定资产业务要求抽取并重排列顺序。
* 核心逻辑:只输出指定的 10 个业务字段;若某列缺失则补“无”,并把取得时间统一裁剪为年月日。
* @param rawHeaders - CSV 原始表头。
* @param dataRows - 原始数据行。
* @returns 规范化后的表头与数据行。
*/
function buildFixedAssetInlineTable(rawHeaders: string[], dataRows: string[][]): InlinePreviewTable {
const headers = FIXED_ASSET_CANONICAL_COLUMNS.map((column) => column.label);
const canonicalHeaders = FIXED_ASSET_CANONICAL_COLUMNS.map((column) => column.key);
const allRows = dataRows.map((row, rowIndex) => FIXED_ASSET_CANONICAL_COLUMNS.map((column) => {
if (column.key === 'id') return String(rowIndex + 1);
const columnIndex = findInlineTableHeaderIndex(rawHeaders, [...column.aliases]);
const rawValue = columnIndex >= 0 ? row[columnIndex] ?? '' : '';
const normalizedValue = column.key === 'acquisition_date'
? formatInlineDateOnly(rawValue)
: rawValue;
return normalizeInlineTableCell(normalizedValue);
}));
return {
rawHeaders: canonicalHeaders,
headers,
allRows,
totalRows: dataRows.length,
isCsv: true,
};
}
/**
* 将 CSV 文本转成结构化表格,供聊天文件弹窗展示全部数据。
* 核心逻辑:固定资产明细优先收敛为指定业务列与日期格式;其他 CSV 保持原表头映射,避免误伤通用附件预览。
* @param file - 当前预览文件。
* @returns 表头、完整数据行和总行数。
*/
function buildInlinePreviewTable(file: InlineDownloadFile): InlinePreviewTable {
const isCsv = (file.mime_type || '').includes('csv') || /\.csv$/i.test(file.name);
if (!isCsv || !file.data) {
return { rawHeaders: [], headers: [], allRows: [], totalRows: 0, isCsv: false };
}
const lines = file.data
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
.split('\n')
.filter((line) => line.length > 0);
if (lines.length === 0) {
return { rawHeaders: [], headers: [], allRows: [], totalRows: 0, isCsv: true };
}
const headerLine = lines[0] || '';
const rawHeaders = parseCsvLine(headerLine);
const dataRows = lines.slice(1).map((line) => parseCsvLine(line));
if (isFixedAssetInlineTable(rawHeaders)) {
return buildFixedAssetInlineTable(rawHeaders, dataRows);
}
const idColumnIndex = rawHeaders.findIndex((header) => String(header || '').trim().toLowerCase() === 'id');
const headers = rawHeaders.map((header) => localizeInlineTableHeader(header));
const allRows = dataRows.map((row, rowIndex) => rawHeaders.map((_, columnIndex) => {
if (columnIndex === idColumnIndex) {
return String(rowIndex + 1);
}
return normalizeInlineTableCell(row[columnIndex] ?? '');
}));
return {
rawHeaders,
headers,
allRows,
totalRows: dataRows.length,
isCsv: true,
};
}
/**
* 组装当前消息内嵌文件的展示模型。
* 核心逻辑:为每个文件预先计算 CSV 行数与表格内容,供按钮显示条件和弹窗直接复用。
* @returns 当前消息可操作的文件条目列表。
*/
const inlineFileEntries = computed<InlineFileEntry[]>(() => inlineDownloadFiles.value.map((file, fileIndex) => ({
file,
fileIndex,
table: buildInlinePreviewTable(file),
})));
/**
* 仅当数据量大于 5 行时展示“查看全部数据”入口。
* 核心逻辑:小结果集直接依赖聊天正文里的预览表格,不再额外重复提供 CSV 附件按钮。
*/
const actionableInlineFileEntries = computed(() => inlineFileEntries.value.filter((entry) => (
entry.table.totalRows === 0 || entry.table.totalRows > 5
)));
const activeInlineDialogEntry = ref<InlineFileEntry | null>(null);
const inlineDialogAssetIdKeyword = ref('');
const inlineDialogCustodianKeyword = ref('');
const inlineDialogDeptKeyword = ref('');
const inlineDialogPage = ref(1);
const activeInlineFilterIndexes = computed(() => {
const table = activeInlineDialogEntry.value?.table;
if (!table) {
return { assetId: -1, custodianPerson: -1, custodianDept: -1 };
}
return {
assetId: findInlineTableHeaderIndex(table.rawHeaders, ['asset_id', 'asset_no']),
custodianPerson: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_person', 'custodian_name']),
custodianDept: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_dept', 'department_name']),
};
});
const activeInlineFilteredRows = computed(() => {
const entry = activeInlineDialogEntry.value;
if (!entry) return [];
const filters = {
assetId: normalizeInlineFilterKeyword(inlineDialogAssetIdKeyword.value),
custodianPerson: normalizeInlineFilterKeyword(inlineDialogCustodianKeyword.value),
custodianDept: normalizeInlineFilterKeyword(inlineDialogDeptKeyword.value),
};
const indexes = activeInlineFilterIndexes.value;
return entry.table.allRows.filter((row) => {
const assetIdValue = indexes.assetId >= 0 ? normalizeInlineFilterKeyword(row[indexes.assetId] ?? '') : '';
const custodianValue = indexes.custodianPerson >= 0 ? normalizeInlineFilterKeyword(row[indexes.custodianPerson] ?? '') : '';
const deptValue = indexes.custodianDept >= 0 ? normalizeInlineFilterKeyword(row[indexes.custodianDept] ?? '') : '';
return (!filters.assetId || assetIdValue.includes(filters.assetId))
&& (!filters.custodianPerson || custodianValue.includes(filters.custodianPerson))
&& (!filters.custodianDept || deptValue.includes(filters.custodianDept));
});
});
const activeInlineTotalPages = computed(() => Math.max(1, Math.ceil(activeInlineFilteredRows.value.length / INLINE_DIALOG_PAGE_SIZE)));
const activeInlinePageRows = computed(() => {
const startIndex = (inlineDialogPage.value - 1) * INLINE_DIALOG_PAGE_SIZE;
return activeInlineFilteredRows.value.slice(startIndex, startIndex + INLINE_DIALOG_PAGE_SIZE);
});
const activeInlineRangeStart = computed(() => (activeInlineFilteredRows.value.length === 0 ? 0 : (inlineDialogPage.value - 1) * INLINE_DIALOG_PAGE_SIZE + 1));
const activeInlineRangeEnd = computed(() => Math.min(inlineDialogPage.value * INLINE_DIALOG_PAGE_SIZE, activeInlineFilteredRows.value.length));
watch(activeInlineTotalPages, (totalPages) => {
if (inlineDialogPage.value > totalPages) {
inlineDialogPage.value = totalPages;
}
});
watch(
[inlineDialogAssetIdKeyword, inlineDialogCustodianKeyword, inlineDialogDeptKeyword],
() => {
inlineDialogPage.value = 1;
},
);
/**
* 打开聊天文件全量预览弹窗。
* 核心逻辑:点击按钮后把目标文件条目写入弹窗状态,在独立弹层中展示全部数据,避免聊天正文只保留 5 行。
* @param entry - 当前消息中的可预览文件条目。
*/
function openInlinePreviewDialog(entry: InlineFileEntry): void {
activeInlineDialogEntry.value = entry;
inlineDialogAssetIdKeyword.value = '';
inlineDialogCustodianKeyword.value = '';
inlineDialogDeptKeyword.value = '';
inlineDialogPage.value = 1;
}
/**
* 关闭聊天文件全量预览弹窗。
*/
function closeInlinePreviewDialog(): void {
activeInlineDialogEntry.value = null;
}
/**
* 重置弹窗顶部筛选条件。
*/
function resetInlineDialogFilters(): void {
inlineDialogAssetIdKeyword.value = '';
inlineDialogCustodianKeyword.value = '';
inlineDialogDeptKeyword.value = '';
inlineDialogPage.value = 1;
}
/**
* 切换弹窗分页页码。
* 核心逻辑:统一做边界保护,防止筛选后页码越界。
* @param nextPage - 目标页码。
*/
function changeInlineDialogPage(nextPage: number): void {
inlineDialogPage.value = Math.min(Math.max(1, nextPage), activeInlineTotalPages.value);
}
/**
* 响应聊天消息里的内嵌文件下载按钮点击。
* 核心逻辑:复用页面层 handlers 生成 Blob 下载,组件层只负责把当前文件对象回传出去。
* @param file - 从当前消息内容解析出的单个可下载文件。
*/
function handleInlineDownload(file: InlineDownloadFile): void {
const table = buildInlinePreviewTable(file);
if (!table.isCsv || table.headers.length === 0) {
handlers.downloadInlineFile(file);
return;
}
const exportRows = activeInlineDialogEntry.value?.file === file ? activeInlineFilteredRows.value : table.allRows;
const transformedCsv = serializeCsvRows([table.headers, ...exportRows]);
handlers.downloadInlineFile({
...file,
data: `\uFEFF${transformedCsv}`,
mime_type: 'text/csv;charset=utf-8',
});
}
</script>
<template>
<div
:data-msg-index="index"
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
:class="message.role === 'user' ? 'justify-end' : 'justify-start'"
>
<div
class="flex flex-col"
:class="message.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
>
<div
class="text-[15px] leading-relaxed"
:class="message.role === 'user'
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
: 'chat-msg-assistant'"
>
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
<div v-else>
<LeaveMessageBlock
v-if="isLeaveMessage"
:message="message"
:index="index"
:handlers="leaveHandlers"
/>
<ShippingInventoryMappingMessage
v-else-if="message.type === 'shipping-inventory-mapping' && handlers.getShippingInventoryMappingPayload(message)"
:message="message"
:handlers="shippingHandlers"
/>
<ShippingParseReviewMessage
v-else-if="message.type === 'shipping-parse-review' && shippingHandlers.getParseReviewPayload(message)"
:message="message"
:handlers="shippingParseReviewHandlers"
/>
<ShippingMatchResultCard
v-else-if="message.type === 'shipping-match-result' && handlers.getShippingMatchResultPayload(message)"
:task-id="handlers.getShippingMatchResultPayload(message)!.taskId"
:match-status="handlers.getShippingMatchResultPayload(message)!.match_status"
:line-results="handlers.getShippingMatchResultPayload(message)!.line_results"
:shortage-lines="handlers.getShippingMatchResultPayload(message)!.shortage_lines"
:action-buttons="handlers.getShippingMatchResultPayload(message)!.action_buttons"
:action-busy="isThinking || message.shipping_actions_used"
:action-button-class="handlers.shippingActionButtonClass"
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
/>
<TrainingExamQuestionMessage
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
:question="trainingHandlers.getQuestion()!"
:current-question-index="trainingHandlers.getCurrentQuestionIndex()"
:answered-count="trainingHandlers.getAnsweredCount()"
:total-count="trainingHandlers.getTotalCount()"
:score="trainingHandlers.getScore()"
:selected-option-id="trainingHandlers.getSelectedOptionId()"
:answer-locked="trainingHandlers.getAnswerLocked()"
:feedback-correct="trainingHandlers.getFeedbackCorrect()"
:answer-label="trainingHandlers.getAnswerLabel()"
:is-thinking="isThinking"
@select="trainingHandlers.onSelect"
@next="trainingHandlers.onNext"
/>
<TrainingResultCard
v-else-if="isTrainingResultMessage"
:score="trainingHandlers.getScore()"
:is-passed="trainingHandlers.getScore() >= 90"
:correct-count="trainingHandlers.getCorrectCount()"
:wrong-count="trainingHandlers.getWrongCount()"
:is-thinking="isThinking"
@restart="trainingHandlers.onRestartExam"
/>
<div
v-else-if="renderedMarkdown"
ref="markdownContainer"
class="markdown-body chat-markdown min-w-0 break-words text-sm leading-relaxed"
v-html="renderedMarkdown"
/>
<TrainingVideoMessage
v-if="isTrainingVideoMessage"
:is-thinking="isThinking"
@play="trainingHandlers.onPlayVideo"
/>
<TrainingSummaryMessage
v-if="isTrainingSummaryMessage"
:summary-points="trainingHandlers.getSummaryPoints()"
:summary-checklist="trainingHandlers.getSummaryChecklist()"
:is-thinking="isThinking"
@start-exam="trainingHandlers.onStartExam"
/>
<div v-if="actionableInlineFileEntries.length > 0" class="mt-4">
<div class="flex flex-wrap gap-2">
<button
v-for="entry in actionableInlineFileEntries"
:key="`${message.local_id || index}-inline-file-${entry.file.name}-${entry.fileIndex}`"
type="button"
class="inline-flex max-w-full items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
:title="$t('chat.inlineFile.preview')"
@click="openInlinePreviewDialog(entry)"
>
<Eye class="h-3.5 w-3.5 shrink-0" />
<span class="truncate">{{ entry.file.name }}</span>
</button>
</div>
</div>
<div
v-if="message.role === 'assistant' && handlers.canOpenQueryPreview(message)"
class="mt-4"
>
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
@click="handlers.openQueryPreviewDialog(message)"
>
<LayoutGrid class="h-3.5 w-3.5" />
{{ handlers.getQueryPreviewSummary(message) }}
</button>
</div>
<div
v-if="showShippingActionsPanel"
class="mt-4 space-y-2 border-t border-default pt-4"
>
<div class="text-xs font-medium text-muted">{{ $t('chat.shippingNoticeActionsHint') }}</div>
<div class="flex flex-wrap gap-2">
<button
v-for="(action, actionIndex) in message.shipping_actions"
:key="`${message.local_id || index}-shipping-action-${action.id}-${actionIndex}`"
type="button"
:class="handlers.shippingActionButtonClass(action.variant)"
:disabled="isThinking || message.shipping_actions_used"
@click="handlers.onShippingActionClick(message, action)"
>
{{ action.label }}
</button>
</div>
</div>
</div>
</div>
<div v-if="showSourceSection" class="mt-2 space-y-2">
<div v-if="sourceLinks.length > 0" class="flex flex-wrap gap-2">
<button
v-for="(file, linkIndex) in sourceLinks"
:key="`src-link-top-${linkIndex}-${file.url}`"
type="button"
class="break-all rounded-lg border border-brand-200 bg-brand-50 px-2.5 py-1.5 text-xs text-brand-700 transition-colors hover:bg-brand-100"
@click="handlers.openPreview(file)"
>
{{ file.name }}
</button>
</div>
<details
v-if="retrieverResources.length > 0"
class="rounded-xl border border-default bg-surface-soft/90 px-4 py-3"
:open="handlers.shouldExpandSourceDetails(message)"
>
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-secondary">
{{ $t('chat.sourceDocs') }} ({{ retrieverResources.length }})
</summary>
<div class="mt-3 space-y-2">
<div
v-for="(doc, docIndex) in retrieverResources"
:key="`${doc.document_name || 'doc'}-${doc.segment_id || docIndex}`"
class="rounded-lg border border-default bg-surface p-3"
>
<div class="break-all text-sm font-semibold text-primary">{{ handlers.getSourceTitle(doc) }}</div>
<div v-if="handlers.getSourceMeta(doc)" class="mt-1 text-xs text-muted">{{ handlers.getSourceMeta(doc) }}</div>
<div v-if="handlers.getSourceBrief(doc)" class="mt-2 whitespace-pre-wrap break-all text-xs text-secondary">
{{ handlers.getSourceBrief(doc) }}
</div>
</div>
</div>
</details>
<details
v-if="message.attribution_parts && message.attribution_parts.length > 0"
class="rounded-xl border border-default bg-surface-soft/90 px-4 py-3"
open
>
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-secondary">
{{ $t('chat.attributionParts') }}
</summary>
<ul class="mt-3 space-y-2">
<li
v-for="(part, partIndex) in message.attribution_parts"
:key="`attr-${partIndex}`"
class="rounded-lg border border-default bg-surface p-3 text-xs text-secondary"
>
{{ part }}
</li>
</ul>
</details>
</div>
<div
v-if="showActions"
class="mt-1 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100"
:class="message.role === 'user' ? 'justify-end text-muted' : 'justify-start text-muted'"
>
<button
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.copy')"
@click.stop="emit('copy')"
>
<Check v-if="isCopied" class="h-3.5 w-3.5 text-emerald-500" />
<Copy v-else class="h-3.5 w-3.5" />
</button>
<template v-if="message.role === 'user'">
<button
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.edit')"
@click.stop="emit('edit', message.content)"
>
<Edit2 class="h-3.5 w-3.5" />
</button>
<button
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.resend')"
@click.stop="emit('resend', message.content)"
>
<RotateCw class="h-3.5 w-3.5" />
</button>
</template>
<template v-else>
<button
v-if="isLastMessage && !isThinking"
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.regenerate')"
@click="emit('regenerate')"
>
<RotateCw class="h-3.5 w-3.5" />
</button>
<button
v-if="showChatRating && !isThinking && !message.rated"
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.rate')"
@click="emit('open-feedback')"
>
<MessageSquareText class="h-3.5 w-3.5" />
</button>
</template>
</div>
</div>
</div>
<Teleport to="body">
<div
v-if="activeInlineDialogEntry"
class="dialog-overlay z-[130] items-center"
@click.self="closeInlinePreviewDialog"
>
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,1360px)] max-w-[1360px] flex-col">
<div class="dialog-header">
<div>
<h3 class="section-title">{{ activeInlineDialogEntry.file.name }}</h3>
<p class="section-desc mt-1">
{{ $t('chat.inlineFile.previewHint', { rows: activeInlineDialogEntry.table.totalRows }) }}
</p>
</div>
<div class="flex items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
@click="handleInlineDownload(activeInlineDialogEntry.file)"
>
<Download class="h-3.5 w-3.5" />
{{ $t('chat.inlineFile.download') }}
</button>
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="closeInlinePreviewDialog">
<X class="h-5 w-5" />
</button>
</div>
</div>
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
<div
v-if="activeInlineDialogEntry.table.headers.length > 0"
class="grid gap-3 md:grid-cols-4"
>
<input
v-model="inlineDialogAssetIdKeyword"
type="text"
class="rounded-xl border border-default bg-surface px-3 py-2 text-sm text-primary outline-none transition focus:border-blue-400"
:placeholder="$t('chat.inlineFile.filters.assetId')"
/>
<input
v-model="inlineDialogCustodianKeyword"
type="text"
class="rounded-xl border border-default bg-surface px-3 py-2 text-sm text-primary outline-none transition focus:border-blue-400"
:placeholder="$t('chat.inlineFile.filters.custodianPerson')"
/>
<input
v-model="inlineDialogDeptKeyword"
type="text"
class="rounded-xl border border-default bg-surface px-3 py-2 text-sm text-primary outline-none transition focus:border-blue-400"
:placeholder="$t('chat.inlineFile.filters.custodianDept')"
/>
<button
type="button"
class="rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft"
@click="resetInlineDialogFilters"
>
{{ $t('chat.inlineFile.filters.reset') }}
</button>
</div>
<div class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
<table
v-if="activeInlineDialogEntry.table.headers.length > 0"
class="min-w-full border-collapse text-sm"
>
<thead class="sticky top-0 z-10 bg-slate-50">
<tr>
<th
v-for="(header, headerIndex) in activeInlineDialogEntry.table.headers"
:key="`${activeInlineDialogEntry.file.name}-dialog-header-${headerIndex}`"
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
>
{{ header || '-' }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(row, rowIndex) in activeInlinePageRows"
:key="`${activeInlineDialogEntry.file.name}-dialog-row-${rowIndex}`"
class="odd:bg-white even:bg-slate-50/50"
>
<td
v-for="(cell, cellIndex) in row"
:key="`${activeInlineDialogEntry.file.name}-dialog-cell-${rowIndex}-${cellIndex}`"
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
>
<div class="whitespace-pre-wrap break-all">{{ cell || '-' }}</div>
</td>
</tr>
</tbody>
</table>
<div v-else class="p-4 text-sm text-secondary">
<div class="whitespace-pre-wrap break-all">{{ activeInlineDialogEntry.file.data }}</div>
</div>
</div>
<div
v-if="activeInlineDialogEntry.table.headers.length > 0"
class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between"
>
<div class="text-sm text-muted">
{{
activeInlineFilteredRows.length > 0
? $t('chat.inlineFile.pagination.range', {
start: activeInlineRangeStart,
end: activeInlineRangeEnd,
total: activeInlineFilteredRows.length,
})
: $t('chat.inlineFile.pagination.empty')
}}
</div>
<div
v-if="activeInlineFilteredRows.length > INLINE_DIALOG_PAGE_SIZE"
class="flex items-center gap-2"
>
<button
type="button"
class="rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
:disabled="inlineDialogPage <= 1"
@click="changeInlineDialogPage(inlineDialogPage - 1)"
>
{{ $t('chat.inlineFile.pagination.prev') }}
</button>
<div class="text-sm text-muted">
{{ $t('chat.inlineFile.pagination.page', { page: inlineDialogPage, total: activeInlineTotalPages }) }}
</div>
<button
type="button"
class="rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
:disabled="inlineDialogPage >= activeInlineTotalPages"
@click="changeInlineDialogPage(inlineDialogPage + 1)"
>
{{ $t('chat.inlineFile.pagination.next') }}
</button>
</div>
</div>
</div>
</div>
</div>
</Teleport>
</template>
<style scoped>
:deep(.chat-markdown) {
max-width: 100%;
}
:deep(.chat-markdown .chat-table-scroll) {
max-width: 100%;
overflow-x: auto;
overflow-y: hidden;
margin: 0.75rem 0;
-webkit-overflow-scrolling: touch;
}
:deep(.chat-markdown .chat-table-inner) {
width: max-content;
min-width: 100%;
}
:deep(.chat-markdown table) {
width: max-content;
min-width: 100%;
border-collapse: collapse;
margin: 0;
font-size: 0.875rem;
}
:deep(.chat-markdown th),
:deep(.chat-markdown td) {
border: 1px solid rgb(226 232 240);
padding: 0.5rem 0.75rem;
text-align: left;
vertical-align: top;
white-space: nowrap;
}
:deep(.chat-markdown th) {
background: rgb(248 250 252);
font-weight: 600;
}
:deep(.dark .chat-markdown th),
:deep(.dark .chat-markdown td) {
border-color: rgb(51 65 85);
}
:deep(.dark .chat-markdown th) {
background: rgb(30 41 59);
}
:deep(.chat-markdown details) {
margin-top: 1rem;
border: 1px solid rgb(226 232 240);
border-radius: 0.75rem;
background: rgb(248 250 252 / 0.9);
padding: 0.75rem 1rem;
}
:deep(.dark .chat-markdown details) {
border-color: rgb(51 65 85);
background: rgb(30 41 59 / 0.65);
}
:deep(.chat-markdown details summary) {
cursor: pointer;
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.08em;
color: rgb(71 85 105);
list-style-position: inside;
}
:deep(.dark .chat-markdown details summary) {
color: rgb(203 213 225);
}
:deep(.chat-markdown details[open] summary) {
margin-bottom: 0.75rem;
}
:deep(.chat-markdown details pre) {
margin-bottom: 0;
}
:deep(.chat-markdown .leave-action-trigger) {
display: inline-flex;
align-items: center;
justify-content: center;
margin: 0 0.2rem;
padding: 0.1rem 0.6rem;
border-radius: 9999px;
border: 1px solid rgb(59 130 246 / 0.28);
background: rgb(239 246 255);
color: rgb(29 78 216);
font-weight: 600;
text-decoration: none;
cursor: pointer;
transition: all 0.2s ease;
}
:deep(.chat-markdown .leave-action-trigger:hover) {
background: rgb(219 234 254);
border-color: rgb(59 130 246 / 0.4);
}
:deep(.chat-markdown .leave-intent-highlight) {
display: inline-block;
margin: 0 0.2rem;
padding: 0.05rem 0.4rem;
border-radius: 0.5rem;
background: rgb(254 249 195);
color: rgb(161 98 7);
font-weight: 600;
}
:deep(.dark .chat-markdown .leave-action-trigger) {
border-color: rgb(96 165 250 / 0.35);
background: rgb(30 41 59);
color: rgb(147 197 253);
}
:deep(.dark .chat-markdown .leave-action-trigger:hover) {
background: rgb(30 64 175 / 0.25);
}
:deep(.dark .chat-markdown .leave-intent-highlight) {
background: rgb(113 63 18 / 0.45);
color: rgb(253 224 71);
}
</style>