2772 lines
120 KiB
Vue
2772 lines
120 KiB
Vue
|
||
|
||
<script setup lang="ts">
|
||
/**
|
||
* ChatView.vue
|
||
* 文件用途:单个 Agent 的对话界面
|
||
* 引用文件:vue, vue-router, lucide-vue-next, useChat 组合函数
|
||
* 逻辑关系:
|
||
* - 使用 useChat 发送消息并接收 SSE 流
|
||
* - 支持从首页携带预设问题快速发起对话
|
||
* - 在回答结束后允许用户对本次回答进行评分与意见反馈
|
||
*/
|
||
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
|
||
import { useI18n } from 'vue-i18n';
|
||
import { useChat } from '../composables/useChat';
|
||
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search, LayoutGrid, History } from 'lucide-vue-next';
|
||
import { marked } from 'marked';
|
||
import { useRoute, useRouter } from 'vue-router';
|
||
import { config } from '../config';
|
||
import FilePreviewModal from '../components/FilePreviewModal.vue';
|
||
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
|
||
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
|
||
import { useIsMobile } from '../composables/useIsMobile';
|
||
import { getAuthHeaders, getStoredAuthUser, clearAuthUser } from '../utils/auth';
|
||
|
||
const { t } = useI18n();
|
||
const { showMessageDialog } = useGlobalMessageDialog();
|
||
const { isMobile } = useIsMobile();
|
||
const showMobileAgentPopover = ref(false);
|
||
const mobileAgentPopoverRef = ref<HTMLElement | null>(null);
|
||
|
||
const handleMobileAgentPopoverClickOutside = (e: MouseEvent | TouchEvent) => {
|
||
if (mobileAgentPopoverRef.value && !mobileAgentPopoverRef.value.contains(e.target as Node)) {
|
||
showMobileAgentPopover.value = false;
|
||
}
|
||
};
|
||
|
||
const toggleMobileAgentPopover = () => {
|
||
showMobileAgentPopover.value = !showMobileAgentPopover.value;
|
||
if (showMobileAgentPopover.value) {
|
||
loadUserAgents();
|
||
}
|
||
};
|
||
const currentUser = ref(getStoredAuthUser());
|
||
const showUserDropdown = ref(false);
|
||
const userMenuRef = ref<HTMLElement | null>(null);
|
||
|
||
const selectedKb = ref('企业知识库');
|
||
const showKbDropdown = ref(false);
|
||
const kbMenuRef = ref<HTMLElement | null>(null);
|
||
const kbOptions = ['企业知识库', 'ERP知识库'];
|
||
const chatScrollContainer = ref<HTMLElement | null>(null);
|
||
let scrollToBottomFrame: number | null = null;
|
||
let wasThinking = false;
|
||
|
||
marked.setOptions({
|
||
gfm: true,
|
||
breaks: true,
|
||
});
|
||
|
||
const currentUserDisplayName = computed(() => {
|
||
const realName = currentUser.value?.real_name?.trim();
|
||
if (realName) return realName;
|
||
const aliasName = (currentUser.value as any)?.name?.trim?.() || (currentUser.value as any)?.wecom_name?.trim?.();
|
||
if (aliasName) return aliasName;
|
||
const username = currentUser.value?.username?.trim();
|
||
if (username && !/^\d+$/.test(username)) return username;
|
||
return '当前用户';
|
||
});
|
||
|
||
const currentUserEmployeeId = computed(() => {
|
||
const employeeId = currentUser.value?.employee_id?.trim();
|
||
if (employeeId) return employeeId;
|
||
const username = currentUser.value?.username?.trim();
|
||
return username || '-';
|
||
});
|
||
|
||
const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
|
||
const target = event.target as Node | null;
|
||
if (!target) return;
|
||
if (showUserDropdown.value && userMenuRef.value && !userMenuRef.value.contains(target)) {
|
||
showUserDropdown.value = false;
|
||
}
|
||
if (showKbDropdown.value && kbMenuRef.value && !kbMenuRef.value.contains(target)) {
|
||
showKbDropdown.value = false;
|
||
}
|
||
};
|
||
|
||
const handleLogout = () => {
|
||
clearAuthUser();
|
||
router.push('/');
|
||
};
|
||
|
||
const handleVoiceFeatureClick = () => {
|
||
showMessageDialog('info', '该功能正在开发中');
|
||
};
|
||
|
||
const stripReasoningPrelude = (text: string) => {
|
||
if (!text) return '';
|
||
let cleaned = text
|
||
.replace(/<think[\s\S]*?<\/think>/gi, '')
|
||
.replace(/<analysis[\s\S]*?<\/analysis>/gi, '')
|
||
.trim();
|
||
|
||
const reasoningMarkers = [
|
||
'让我分析',
|
||
'根据应答生成规则',
|
||
'分析知识库返回的内容',
|
||
'我需要直接给出答案',
|
||
'思考过程',
|
||
'推理过程',
|
||
];
|
||
const hasReasoningMarker = reasoningMarkers.some((marker) => cleaned.includes(marker));
|
||
if (!hasReasoningMarker) return cleaned;
|
||
|
||
const headingMatch = cleaned.match(/(^|\n)\s{0,3}#{1,6}\s+/);
|
||
if (headingMatch && typeof headingMatch.index === 'number') {
|
||
const start = headingMatch.index + (headingMatch[1] ? headingMatch[1].length : 0);
|
||
cleaned = cleaned.slice(start).trim();
|
||
}
|
||
return cleaned;
|
||
};
|
||
|
||
const renderMarkdown = (text: string) => {
|
||
if (!text) return '';
|
||
const displayText = stripReasoningPrelude(text);
|
||
try {
|
||
// 把 # 标题、代码块、[链接](url) 等 Markdown 解析成 HTML
|
||
return marked.parse(displayText);
|
||
} catch (e) {
|
||
return displayText;
|
||
}
|
||
};
|
||
|
||
const getSourceTitle = (item: any) => {
|
||
return item?.document_name || item?.title || item?.source || 'Untitled Source';
|
||
};
|
||
|
||
const getSourceMeta = (item: any) => {
|
||
const parts: string[] = [];
|
||
if (item?.dataset_name) parts.push(item.dataset_name);
|
||
if (item?.segment_id) parts.push(`segment: ${item.segment_id}`);
|
||
if (typeof item?.score === 'number') parts.push(`score: ${item.score.toFixed(3)}`);
|
||
return parts.join(' | ');
|
||
};
|
||
|
||
const getSourceContent = (item: any) => {
|
||
return item?.content || item?.segment_content || item?.text || '';
|
||
};
|
||
|
||
const getSourceBrief = (item: any) => {
|
||
const raw = getSourceContent(item);
|
||
const plain = raw
|
||
.replace(/\[[^\]]+\]\(([^)]+)\)/g, '$1')
|
||
.replace(/[#>*`]/g, ' ')
|
||
.replace(/\s+/g, ' ')
|
||
.trim();
|
||
if (!plain) return '';
|
||
return plain.length > 180 ? `${plain.slice(0, 180)}...` : plain;
|
||
};
|
||
|
||
interface SourceFileLink {
|
||
name: string;
|
||
url?: string;
|
||
datasetId?: string;
|
||
remoteDocumentId?: string;
|
||
}
|
||
|
||
// 源文件展示配置(来自 config.ts)
|
||
// const sourceFileConfig = {
|
||
// // 是否显示整个“源文件”区域
|
||
// showSourceFiles: config.workspace?.sourceFiles?.showSourceFiles !== false,
|
||
// // 是否显示 MD 源文件(.md/.markdown)
|
||
// showMdFiles: config.workspace?.sourceFiles?.showMdFiles !== false,
|
||
// // MD 源文件是否默认展开“源文档”详情
|
||
// expandMdByDefault: config.workspace?.sourceFiles?.expandMdByDefault === true,
|
||
// };
|
||
|
||
const PREFERRED_SOURCE_EXTS = new Set([
|
||
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
|
||
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp',
|
||
'txt', 'rtf', 'md', 'markdown',
|
||
]);
|
||
|
||
const safeDecode = (value: string) => {
|
||
try {
|
||
return decodeURIComponent(value);
|
||
} catch {
|
||
return value;
|
||
}
|
||
};
|
||
|
||
const normalizeUrl = (url: string) => {
|
||
// 统一清洗 URL:去掉包裹引号、还原转义字符、剔除末尾标点。
|
||
// 目的:让后续提取逻辑面对 Dify 返回的不同转义形态时保持稳定。
|
||
let v = url
|
||
.trim()
|
||
.replace(/^['"]|['"]$/g, '')
|
||
.replace(/\\\//g, '/')
|
||
.replace(/\\u0026/gi, '&')
|
||
.replace(/\\u003d/gi, '=')
|
||
.replace(/\\u003a/gi, ':')
|
||
.replace(/\\u002f/gi, '/')
|
||
.replace(/&/g, '&');
|
||
v = v.replace(/[),.;]+$/g, '');
|
||
if (!v) return '';
|
||
if (v.startsWith('//')) return `${window.location.protocol}${v}`;
|
||
if (/^https?:\/\//i.test(v) || v.startsWith('/')) return v;
|
||
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\//.test(v)) return `http://${v}`;
|
||
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\//.test(v)) return `http://${v}`;
|
||
return '';
|
||
};
|
||
|
||
const getUrlExt = (url: string) => {
|
||
const clean = (url.split('?')[0] || '').toLowerCase();
|
||
const idx = clean.lastIndexOf('.');
|
||
if (idx < 0) return '';
|
||
return clean.slice(idx + 1);
|
||
};
|
||
|
||
const isChunkLikeLink = (url: string) => {
|
||
// 保留原始 Markdown 文件链接;仅过滤明显的分片/切片类链接。
|
||
return /segment|chunk|fragments?|split/i.test(url);
|
||
};
|
||
|
||
const isPreferredSourceLink = (url: string) => {
|
||
const ext = getUrlExt(url);
|
||
return PREFERRED_SOURCE_EXTS.has(ext);
|
||
};
|
||
|
||
const isNoisySourceUrl = (_url: string) => {
|
||
// 带签名参数的下载链接在 UI 中可读性差(如 download?version_id=...&token=...)。
|
||
// 暂时注释掉这段校验逻辑,保证有元数据能被展示出来
|
||
// return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
|
||
return false;
|
||
};
|
||
|
||
const isNoisySourceName = (_name: string) => {
|
||
// 兜底过滤:名称如果本质是查询串而不是文件名,则不展示。
|
||
// 注释掉,允许带参数的链接在没有文件名时也可以显示(作为退路)
|
||
// return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
|
||
return false;
|
||
};
|
||
|
||
const looksLikeFileName = (name: string) => {
|
||
const n = (name || '').trim();
|
||
if (!n) return false;
|
||
// 保留中英文文件名,如 员工手册.doc
|
||
return /\.[A-Za-z0-9]{2,8}$/.test(n);
|
||
};
|
||
|
||
const findFirstByKeys = (payload: any, keyCandidates: string[]): string => {
|
||
if (payload == null) return '';
|
||
if (Array.isArray(payload)) {
|
||
for (const item of payload) {
|
||
const found = findFirstByKeys(item, keyCandidates);
|
||
if (found) return found;
|
||
}
|
||
return '';
|
||
}
|
||
if (typeof payload !== 'object') return '';
|
||
for (const key of keyCandidates) {
|
||
const value = payload?.[key];
|
||
if (value != null && String(value).trim()) {
|
||
return String(value).trim();
|
||
}
|
||
}
|
||
for (const value of Object.values(payload)) {
|
||
const found = findFirstByKeys(value, keyCandidates);
|
||
if (found) return found;
|
||
}
|
||
return '';
|
||
};
|
||
|
||
const getResourceIds = (item: any) => {
|
||
const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']);
|
||
const remoteDocumentId = findFirstByKeys(item, [
|
||
'remote_document_id',
|
||
'dify_document_id',
|
||
'document_id',
|
||
'doc_id',
|
||
'source_document_id',
|
||
]);
|
||
return { datasetId, remoteDocumentId };
|
||
};
|
||
|
||
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
|
||
|
||
const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase());
|
||
|
||
const extractUrlsFromText = (text: string) => {
|
||
if (!text) return [];
|
||
const urls: string[] = [];
|
||
// 先把常见 JSON/Markdown 转义做一次反转义,避免 regex 漏抓。
|
||
const normalizedText = text
|
||
.replace(/\\\//g, '/')
|
||
.replace(/\\u0026/gi, '&')
|
||
.replace(/\\u003d/gi, '=')
|
||
.replace(/\\u003a/gi, ':')
|
||
.replace(/\\u002f/gi, '/');
|
||
|
||
// 1) Markdown 链接: [name](url)
|
||
const mdRegex = /\[[^\]]+\]\(([^)]+)\)/g;
|
||
let m;
|
||
while ((m = mdRegex.exec(normalizedText)) !== null) {
|
||
const url = normalizeUrl(m[1] || '');
|
||
if (url) urls.push(url);
|
||
}
|
||
|
||
// 2) HTML 链接: href/src 属性
|
||
const htmlAttrRegex = /\b(?:href|src)\s*=\s*["']([^"']+)["']/gi;
|
||
while ((m = htmlAttrRegex.exec(normalizedText)) !== null) {
|
||
const url = normalizeUrl(m[1] || '');
|
||
if (url) urls.push(url);
|
||
}
|
||
|
||
// 3) 尖括号 URL: <http://...>
|
||
const angleRegex = /<\s*((?:https?:\/\/|\/\/)[^>\s]+)\s*>/gi;
|
||
while ((m = angleRegex.exec(normalizedText)) !== null) {
|
||
const url = normalizeUrl(m[1] || '');
|
||
if (url) urls.push(url);
|
||
}
|
||
|
||
// 4) 原始 URL:支持带/不带协议、内网 IP、相对路径文件等
|
||
const rawRegex =
|
||
/((?:https?:\/\/|\/\/)[^\s"'<>]+|(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\/[^\s"'<>]+|[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?::\d+)?\/[^\s"'<>]+|\/[^\s"'<>]+\.(?:md|markdown|txt|pdf|doc|docx|ppt|pptx|xls|xlsx|jpg|jpeg|png|gif|webp|svg|bmp))/gi;
|
||
while ((m = rawRegex.exec(normalizedText)) !== null) {
|
||
const url = normalizeUrl(m[1] || '');
|
||
if (url) urls.push(url);
|
||
}
|
||
return urls;
|
||
};
|
||
|
||
const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||
const map = new Map<string, SourceFileLink>();
|
||
const mergeSourceLink = (key: string, nextLink: SourceFileLink) => {
|
||
const existing = map.get(key);
|
||
if (!existing) {
|
||
map.set(key, nextLink);
|
||
return;
|
||
}
|
||
map.set(key, {
|
||
...existing,
|
||
...(nextLink.url ? { url: nextLink.url } : {}),
|
||
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
|
||
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
|
||
});
|
||
};
|
||
for (const item of resources) {
|
||
const { datasetId, remoteDocumentId } = getResourceIds(item);
|
||
const directCandidates = [
|
||
item?.source_download_url,
|
||
item?.url,
|
||
item?.file_url,
|
||
item?.document_url,
|
||
item?.source_url,
|
||
item?.download_url,
|
||
item?.metadata?.source_download_url,
|
||
item?.metadata?.url,
|
||
item?.metadata?.file_url,
|
||
item?.metadata?.document_url,
|
||
].filter(Boolean) as string[];
|
||
|
||
const content = getSourceContent(item);
|
||
// 直接强制从对象的顶层属性里获取文件名和链接
|
||
const forceName = item?.source_filename || item?.document_name || item?.title;
|
||
const forceUrl = normalizeUrl(item?.source_download_url || item?.url || '');
|
||
|
||
if (forceName) {
|
||
const key = forceName;
|
||
mergeSourceLink(key, {
|
||
name: forceName,
|
||
...(forceUrl ? { url: forceUrl } : {}),
|
||
...(datasetId ? { datasetId } : {}),
|
||
...(remoteDocumentId ? { remoteDocumentId } : {}),
|
||
});
|
||
}
|
||
|
||
const serialized = JSON.stringify(item || {});
|
||
const discovered = [
|
||
...directCandidates.map(normalizeUrl).filter(Boolean),
|
||
...extractUrlsFromText(content),
|
||
...extractUrlsFromText(serialized),
|
||
];
|
||
|
||
// 若 Dify 返回了 files 数组,额外补充其显式文件链接。
|
||
const files = Array.isArray(item?.files) ? item.files : [];
|
||
for (const f of files) {
|
||
const fu = normalizeUrl(f?.url || f?.download_url || f?.file_url || '');
|
||
if (fu) {
|
||
discovered.push(fu);
|
||
}
|
||
}
|
||
|
||
for (const url of discovered) {
|
||
if (isChunkLikeLink(url)) continue;
|
||
// URL 若为噪声签名链接,且没有可用文件名元数据,则跳过。
|
||
// 这里去掉 isNoisySourceUrl 判断的直接 continue,让有名的链接能过
|
||
// if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
|
||
const name = item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file');
|
||
// Skip links whose display name itself is noisy.
|
||
if (isNoisySourceName(name)) continue;
|
||
// 根据配置决定是否显示 MD 文件
|
||
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
|
||
|
||
// Deduplicate by name if it looks like a filename, else by name + base URL
|
||
const key = looksLikeFileName(name) ? name : `${name}|${url.split('?')[0]}`;
|
||
mergeSourceLink(key, {
|
||
name,
|
||
url,
|
||
...(datasetId ? { datasetId } : {}),
|
||
...(remoteDocumentId ? { remoteDocumentId } : {}),
|
||
});
|
||
}
|
||
}
|
||
const links = Array.from(map.values());
|
||
// 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示
|
||
// const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||
// return preferred.length > 0 ? preferred : links;
|
||
return links;
|
||
};
|
||
|
||
const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||
// if (!sourceFileConfig.showSourceFiles) {
|
||
// console.info('showSourceFiles is false');
|
||
// return [];
|
||
// }
|
||
const map = new Map<string, SourceFileLink>();
|
||
|
||
const merge = (links: SourceFileLink[]) => {
|
||
const mergeMessageLink = (key: string, nextLink: SourceFileLink) => {
|
||
const existing = map.get(key);
|
||
if (!existing) {
|
||
map.set(key, nextLink);
|
||
return;
|
||
}
|
||
map.set(key, {
|
||
...existing,
|
||
...(nextLink.url ? { url: nextLink.url } : {}),
|
||
...(nextLink.datasetId ? { datasetId: nextLink.datasetId } : {}),
|
||
...(nextLink.remoteDocumentId ? { remoteDocumentId: nextLink.remoteDocumentId } : {}),
|
||
});
|
||
};
|
||
for (const link of links) {
|
||
const linkUrl = link.url || '';
|
||
if (linkUrl && isChunkLikeLink(linkUrl)) continue;
|
||
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
|
||
if (isNoisySourceName(link.name)) continue;
|
||
if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue;
|
||
if (isMarkdownFileName(link.name)) {
|
||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
|
||
mergeMessageLink(key, link);
|
||
continue;
|
||
}
|
||
if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue;
|
||
const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`;
|
||
mergeMessageLink(key, link);
|
||
}
|
||
};
|
||
|
||
if (msg?.retriever_resources) {
|
||
// 仅使用结构化 retriever_resources 生成源文件按钮,
|
||
// 避免把回答正文里的普通 URL 误显示为“源文件”。
|
||
merge(getSourceLinks(msg.retriever_resources));
|
||
}
|
||
|
||
const links = Array.from(map.values());
|
||
const preferred = links.filter((l) => l.url && isPreferredSourceLink(l.url));
|
||
return preferred.length > 0 ? preferred : links;
|
||
};
|
||
|
||
const getDisplayRetrieverResources = (msg: any): any[] => {
|
||
// if (!sourceFileConfig.showSourceFiles) return [];
|
||
const list = Array.isArray(msg?.retriever_resources) ? msg.retriever_resources : [];
|
||
// if (sourceFileConfig.showMdFiles) return list;
|
||
return list.filter((doc: any) => {
|
||
const name = doc?.source_filename || doc?.document_name || doc?.title || '';
|
||
const url = doc?.source_download_url || doc?.url || doc?.file_url || doc?.document_url || '';
|
||
return !(isMarkdownFileName(String(name)) || isMarkdownByUrl(String(url)));
|
||
});
|
||
};
|
||
|
||
const shouldExpandSourceDetails = (msg: any): boolean => {
|
||
// if (!sourceFileConfig.showSourceFiles) {
|
||
// console.info('showSourceFiles is false');
|
||
// return false;
|
||
// }
|
||
|
||
// if (!sourceFileConfig.showMdFiles || !sourceFileConfig.expandMdByDefault) return false;
|
||
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url || ''));
|
||
};
|
||
|
||
const shouldRenderMessage = (msg: any): boolean => {
|
||
if (msg?.role === 'user') return true;
|
||
if (msg?.type === 'leave-form' || msg?.type === 'leave-confirmation' || msg?.type === 'leave-result') return true;
|
||
const content = (msg?.content || '').trim();
|
||
if (content) return true;
|
||
if (getMessageLinks(msg).length > 0) return true;
|
||
if (getDisplayRetrieverResources(msg).length > 0) return true;
|
||
return Array.isArray(msg?.attribution_parts) && msg.attribution_parts.length > 0;
|
||
};
|
||
|
||
// “正在生成回答...” 仅在当前轮次还没有任何可显示的 assistant 内容时显示。
|
||
// 一旦最后一条用户消息之后出现了可渲染的 assistant 内容(思考或答案文本等),
|
||
// 该 loading 气泡就会隐藏,避免与正文同时出现。
|
||
const shouldShowThinkingBubble = computed(() => {
|
||
if (!isThinking.value) return false;
|
||
let lastUserIndex = -1;
|
||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||
if (messages.value[i]?.role === 'user') {
|
||
lastUserIndex = i;
|
||
break;
|
||
}
|
||
}
|
||
if (lastUserIndex < 0) return true;
|
||
return !messages.value
|
||
.slice(lastUserIndex + 1)
|
||
.some((msg) => msg?.role === 'assistant' && shouldRenderMessage(msg));
|
||
});
|
||
|
||
const filePreviewVisible = ref(false);
|
||
const previewFile = ref<{ name: string; url: string } | null>(null);
|
||
|
||
const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string }> => {
|
||
if (file.url) {
|
||
return {
|
||
name: file.name,
|
||
url: file.url,
|
||
};
|
||
}
|
||
if (!file.datasetId || !file.remoteDocumentId) {
|
||
throw new Error('当前源文件暂未返回可预览链接');
|
||
}
|
||
|
||
const params = new URLSearchParams({
|
||
agent_id: String(agentId),
|
||
dataset_id: file.datasetId,
|
||
remote_document_id: file.remoteDocumentId,
|
||
});
|
||
const response = await fetch(`/api/chat/source-file?${params.toString()}`, {
|
||
headers: getAuthHeaders(),
|
||
});
|
||
const data = await response.json().catch(() => ({}));
|
||
if (!response.ok) {
|
||
throw new Error(data?.error || `HTTP ${response.status}`);
|
||
}
|
||
|
||
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
|
||
if (!resolvedUrl) {
|
||
throw new Error('未查询到源文件下载地址');
|
||
}
|
||
|
||
return {
|
||
...file,
|
||
url: resolvedUrl,
|
||
name: data?.source_filename || file.name,
|
||
};
|
||
};
|
||
|
||
const openPreview = async (file: SourceFileLink) => {
|
||
try {
|
||
const resolvedFile = await resolveSourceLink(file);
|
||
previewFile.value = resolvedFile;
|
||
filePreviewVisible.value = true;
|
||
} catch (error: any) {
|
||
showMessageDialog('warning', error?.message || '当前源文件暂时无法预览');
|
||
}
|
||
};
|
||
|
||
const parsePlmPreviewLink = (href: string): SourceFileLink | null => {
|
||
const rawHref = (href || '').trim();
|
||
if (!rawHref.startsWith('#plm-preview?')) return null;
|
||
const params = new URLSearchParams(rawHref.slice('#plm-preview?'.length));
|
||
const name = (params.get('name') || '').trim();
|
||
const url = (params.get('url') || '').trim();
|
||
if (!name || !url) return null;
|
||
return { name, url };
|
||
};
|
||
const route = useRoute();
|
||
const router = useRouter();
|
||
const agentId = Number(route.params.agentId);
|
||
|
||
// Sidebar state for mobile
|
||
const isSidebarOpen = ref(false);
|
||
const isSidebarCollapsed = ref(false);
|
||
const copiedIndex = ref<number | null>(null);
|
||
|
||
// 从 useChat 中解构出消息列表、思考状态、会话 ID 与发送函数
|
||
const { messages, isThinking, conversationId, sendMessage } = useChat();
|
||
const input = ref('');
|
||
const currentAgent = ref<any>(null);
|
||
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
|
||
const showGeneralFeedbackDialog = ref(false);
|
||
const showAgentPanel = ref(true);
|
||
|
||
const OA_BASE_URL = 'http://192.168.100.221:8888';
|
||
const OA_VERIFY_LOGIN_URL = `${OA_BASE_URL}/login/VerifyLogin.jsp`;
|
||
const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
|
||
const OA_REQUEST_VIEW_PATH = '/workflow/request/ViewRequest.jsp?requestid=';
|
||
const OA_AUTO_LOGIN_TARGET = 'hxops-oa-leave-request';
|
||
|
||
// OA 登录对话框状态
|
||
const OA_PASSWORD_STORAGE_KEY = 'hxops_oa_login_password';
|
||
const showOALoginDialog = ref(false);
|
||
const oaLoginEmployeeId = ref('');
|
||
const oaLoginPassword = ref(localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '');
|
||
const oaLoginGopage = ref('');
|
||
const oaLoginTarget = ref(OA_AUTO_LOGIN_TARGET);
|
||
|
||
const openOAAutoLoginPage = (gopage: string, username: string, password: string, target = OA_AUTO_LOGIN_TARGET) => {
|
||
// 直接在弹出窗口内写入自动提交表单,避免跨窗口时序问题
|
||
const popup = window.open('about:blank', target);
|
||
if (!popup) {
|
||
showMessageDialog('warning', '浏览器拦截了 OA 页面,请允许弹出窗口后重试。');
|
||
return;
|
||
}
|
||
|
||
const formHtml = `
|
||
<!DOCTYPE html>
|
||
<html>
|
||
<head><meta charset="utf-8"><title>正在登录OA系统...</title></head>
|
||
<body>
|
||
<p style="text-align:center;margin-top:100px;font-family:sans-serif;color:#666;">正在登录OA系统,请稍候...</p>
|
||
<form id="oaLoginForm" action="${OA_VERIFY_LOGIN_URL}" method="POST">
|
||
<input type="hidden" name="loginid" value="${username}" />
|
||
<input type="hidden" name="userpassword" value="${password.replace(/"/g, '"')}" />
|
||
<input type="hidden" name="gopage" value="${gopage}" />
|
||
<input type="hidden" name="logintype" value="1" />
|
||
</form>
|
||
<script>document.getElementById('oaLoginForm').submit();<\/script>
|
||
</body>
|
||
</html>
|
||
`;
|
||
|
||
popup.document.open();
|
||
popup.document.write(formHtml);
|
||
popup.document.close();
|
||
};
|
||
|
||
const openOALeaveRequestDirectly = () => {
|
||
const employeeId = currentUserEmployeeId.value;
|
||
if (!employeeId || employeeId === '-') {
|
||
showMessageDialog('warning', '没有工号信息无法登录OA系统!');
|
||
return;
|
||
}
|
||
oaLoginEmployeeId.value = employeeId;
|
||
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
|
||
oaLoginGopage.value = OA_LEAVE_APPLY_PATH;
|
||
oaLoginTarget.value = OA_AUTO_LOGIN_TARGET;
|
||
showOALoginDialog.value = true;
|
||
};
|
||
|
||
const confirmOALogin = () => {
|
||
if (!oaLoginPassword.value.trim()) {
|
||
showMessageDialog('warning', '请输入OA登录密码!');
|
||
return;
|
||
}
|
||
// 记住密码到 localStorage
|
||
localStorage.setItem(OA_PASSWORD_STORAGE_KEY, oaLoginPassword.value.trim());
|
||
showOALoginDialog.value = false;
|
||
openOAAutoLoginPage(oaLoginGopage.value, oaLoginEmployeeId.value, oaLoginPassword.value.trim(), oaLoginTarget.value);
|
||
};
|
||
|
||
const cancelOALogin = () => {
|
||
showOALoginDialog.value = false;
|
||
};
|
||
|
||
const openOARequestDirectly = (requestId: string) => {
|
||
const normalizedRequestId = String(requestId || '').trim();
|
||
if (!normalizedRequestId || normalizedRequestId === '-') {
|
||
showMessageDialog('warning', '当前未获取到 OA 单据编号,暂时无法打开单据详情。');
|
||
return;
|
||
}
|
||
const employeeId = currentUserEmployeeId.value;
|
||
if (!employeeId || employeeId === '-') {
|
||
showMessageDialog('warning', '没有工号信息无法登录OA系统!');
|
||
return;
|
||
}
|
||
oaLoginEmployeeId.value = employeeId;
|
||
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
|
||
oaLoginGopage.value = `${OA_REQUEST_VIEW_PATH}${encodeURIComponent(normalizedRequestId)}`;
|
||
oaLoginTarget.value = `hxops-oa-request-${normalizedRequestId}`;
|
||
showOALoginDialog.value = true;
|
||
};
|
||
|
||
const activeFeedbackMessageIndex = ref<number | null>(null);
|
||
const browserPanelOpen = ref(false);
|
||
const browserDraftUrl = ref('');
|
||
const browserCurrentUrl = ref('');
|
||
const browserFrameKey = ref(0);
|
||
const browserPanelWidth = ref(420);
|
||
const isBrowserResizing = ref(false);
|
||
const viewportWidth = ref(typeof window === 'undefined' ? 1440 : window.innerWidth);
|
||
|
||
const MIN_BROWSER_PANEL_WIDTH = 320;
|
||
const MAX_BROWSER_PANEL_WIDTH = 960;
|
||
|
||
const LEAVE_TYPES = [
|
||
{ label: '事假(小时)', value: '005' },
|
||
{ label: '病假(小时)', value: '006' },
|
||
{ label: '丧假(天)', value: '007' },
|
||
{ label: '年假(天)', value: '010' },
|
||
{ label: '因公出差(小时)', value: '021' },
|
||
{ label: '调休假(小时)', value: '025' },
|
||
{ label: '产假(天)', value: '401' },
|
||
{ label: '陪产假(天)', value: '402' },
|
||
{ label: '婚假(天)', value: '403' },
|
||
{ label: '住院病假(小时)', value: '405' },
|
||
{ label: '工伤假(天)', value: '406' },
|
||
{ label: '返乡假(小时)', value: 'ZZ01' },
|
||
{ label: '事假(经理专用小时)', value: 'ZZ04' },
|
||
{ label: '病假(经理专用小时)', value: 'ZZ05' },
|
||
{ label: '丧假(经理专用天)', value: 'ZZ07' },
|
||
{ label: '产假(经理专用天)', value: 'ZZ08' },
|
||
{ label: '陪产假(经理专用天)', value: 'ZZ09' },
|
||
{ label: '婚假(经理专用天)', value: 'ZZ10' },
|
||
{ label: '其他假(小时)', value: '035' },
|
||
{ label: '育儿假(小时)', value: '408' }
|
||
];
|
||
|
||
const getLeaveTypeLabel = (val: string) => {
|
||
const t = LEAVE_TYPES.find(x => x.value === val);
|
||
return t ? t.label : val;
|
||
};
|
||
|
||
interface LeaveRequestFormData {
|
||
applicantName: string;
|
||
employeeId: string;
|
||
applicantUid: string;
|
||
applicantJobTitle?: string;
|
||
applicantJobTitleName?: string;
|
||
applicantDepartmentId?: string;
|
||
applicantSubCompanyId1?: string;
|
||
applicantDepartmentName?: string;
|
||
applicantSubCompanyName?: string;
|
||
applyTime: string;
|
||
fillerName: string;
|
||
fillerJobTitle?: string;
|
||
fillerJobTitleName?: string;
|
||
fillerDepartmentId?: string;
|
||
fillerSubCompanyId1?: string;
|
||
fillerDepartmentName?: string;
|
||
fillerSubCompanyName?: string;
|
||
agentUid: string;
|
||
agentEmployeeId: string;
|
||
agentName: string;
|
||
agentJobTitle?: string;
|
||
agentJobTitleName?: string;
|
||
agentDepartmentId?: string;
|
||
agentSubCompanyId1?: string;
|
||
agentDepartmentName?: string;
|
||
agentSubCompanyName?: string;
|
||
leaveType: string;
|
||
startTime: string;
|
||
endTime: string;
|
||
durationHours: number;
|
||
isOutOfOffice: 0 | 1 | null;
|
||
isWorkInjury: 0 | 1 | null;
|
||
}
|
||
|
||
interface LeaveFormPayload {
|
||
formId: string;
|
||
form: LeaveRequestFormData;
|
||
submitting: boolean;
|
||
confirmationGenerated: boolean;
|
||
}
|
||
|
||
interface LeaveConfirmationPayload {
|
||
formId: string;
|
||
form: LeaveRequestFormData;
|
||
submitting: boolean;
|
||
confirmed?: boolean;
|
||
}
|
||
|
||
interface LeaveResultPayload {
|
||
formId: string;
|
||
success: boolean;
|
||
referenceNo: string;
|
||
submittedAt: string;
|
||
requestName?: string;
|
||
errorMessage?: string;
|
||
}
|
||
|
||
interface LeaveAgentOption {
|
||
uid: string;
|
||
employeeId: string;
|
||
name: string;
|
||
jobtitle?: string;
|
||
jobtitleName?: string;
|
||
departmentid?: string;
|
||
subcompanyid1?: string;
|
||
departmentName?: string;
|
||
subcompanyName?: string;
|
||
}
|
||
|
||
let leaveFlowCounter = 0;
|
||
const leaveAgentOptions = ref<LeaveAgentOption[]>([]);
|
||
const leaveAgentLoading = ref(false);
|
||
const leaveAgentKeyword = ref('');
|
||
const leaveAgentPage = ref(1);
|
||
const leaveAgentHasMore = ref(true);
|
||
|
||
const fetchLeaveAgents = async (isLoadMore = false) => {
|
||
if (leaveAgentLoading.value) return;
|
||
if (!isLoadMore) {
|
||
leaveAgentPage.value = 1;
|
||
leaveAgentOptions.value = [];
|
||
}
|
||
|
||
leaveAgentLoading.value = true;
|
||
try {
|
||
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=${leaveAgentPage.value}&page_size=20&agent_id=${agentId}`, {
|
||
headers: getAuthHeaders()
|
||
});
|
||
if (res.ok) {
|
||
const data = await res.json();
|
||
if (isLoadMore) {
|
||
leaveAgentOptions.value.push(...data.items);
|
||
} else {
|
||
leaveAgentOptions.value = data.items;
|
||
}
|
||
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
|
||
}
|
||
} catch (e) {
|
||
console.error('Failed to load OA employees', e);
|
||
} finally {
|
||
leaveAgentLoading.value = false;
|
||
}
|
||
};
|
||
|
||
const handleAgentSearch = () => {
|
||
fetchLeaveAgents(false);
|
||
};
|
||
|
||
const loadMoreAgents = () => {
|
||
if (!leaveAgentHasMore.value) return;
|
||
leaveAgentPage.value += 1;
|
||
fetchLeaveAgents(true);
|
||
};
|
||
|
||
const loadAllAgents = async () => {
|
||
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
|
||
leaveAgentLoading.value = true;
|
||
try {
|
||
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=1&page_size=100000&agent_id=${agentId}`, {
|
||
headers: getAuthHeaders()
|
||
});
|
||
if (res.ok) {
|
||
const data = await res.json();
|
||
leaveAgentOptions.value = data.items;
|
||
leaveAgentHasMore.value = false;
|
||
}
|
||
} catch (e) {
|
||
console.error('Failed to load all OA employees', e);
|
||
} finally {
|
||
leaveAgentLoading.value = false;
|
||
}
|
||
};
|
||
|
||
const showLeaveAgentDialog = ref(false);
|
||
const leaveUserSelectRole = ref<'agent' | 'applicant'>('agent');
|
||
const activeLeaveAgentFormId = ref<string | null>(null);
|
||
|
||
const formatDateTime = (date: Date) => {
|
||
const year = date.getFullYear();
|
||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||
const day = String(date.getDate()).padStart(2, '0');
|
||
const hours = String(date.getHours()).padStart(2, '0');
|
||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||
return `${year}-${month}-${day}T${hours}:${minutes}`;
|
||
};
|
||
|
||
const parseDateTime = (value: string) => {
|
||
const normalized = (value || '').trim().replace('T', ' ');
|
||
const match = normalized.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/);
|
||
if (!match) return null;
|
||
const [, year, month, day, hour, minute] = match;
|
||
const date = new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute));
|
||
return Number.isNaN(date.getTime()) ? null : date;
|
||
};
|
||
|
||
const calculateDurationHours = (startTime: string, endTime: string) => {
|
||
const start = parseDateTime(startTime);
|
||
const end = parseDateTime(endTime);
|
||
if (!start || !end || end.getTime() <= start.getTime()) return 0;
|
||
return Number((((end.getTime() - start.getTime()) / 1000 / 60 / 60)).toFixed(2));
|
||
};
|
||
|
||
const formatDurationLabel = (hours: number) => {
|
||
if (!hours) return '0 小时';
|
||
if (hours >= 8 && Number.isInteger((hours / 8) * 10) && (hours / 8) >= 1) {
|
||
const days = Number((hours / 8).toFixed(2));
|
||
return `${days} 天 / ${hours} 小时`;
|
||
}
|
||
return `${hours} 小时`;
|
||
};
|
||
|
||
const extractLeaveTypeFromIntent = (content: string) => {
|
||
if (!content) return '';
|
||
const map: Record<string, string> = {
|
||
'事假': '005',
|
||
'病假': '006',
|
||
'丧假': '007',
|
||
'年假': '010',
|
||
'因公出差': '021',
|
||
'出差': '021',
|
||
'调休': '025',
|
||
'产假': '401',
|
||
'陪产假': '402',
|
||
'婚假': '403',
|
||
'住院': '405',
|
||
'工伤': '406',
|
||
'育儿假': '408',
|
||
'返乡': 'ZZ01',
|
||
};
|
||
for (const [key, val] of Object.entries(map)) {
|
||
if (content.includes(key)) {
|
||
return val;
|
||
}
|
||
}
|
||
return '';
|
||
};
|
||
|
||
const createLeaveFormData = (content?: string): LeaveRequestFormData => {
|
||
const now = new Date();
|
||
const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000);
|
||
const startTime = formatDateTime(now);
|
||
const endTime = formatDateTime(oneHourLater);
|
||
const initialLeaveType = extractLeaveTypeFromIntent(content || '');
|
||
return {
|
||
applicantName: currentUserDisplayName.value,
|
||
employeeId: currentUserEmployeeId.value,
|
||
applicantUid: '',
|
||
applyTime: formatDateTime(now),
|
||
fillerName: currentUserDisplayName.value,
|
||
agentUid: '',
|
||
agentEmployeeId: '',
|
||
agentName: '',
|
||
leaveType: initialLeaveType,
|
||
startTime,
|
||
endTime,
|
||
durationHours: calculateDurationHours(startTime, endTime),
|
||
isOutOfOffice: 1,
|
||
isWorkInjury: 1,
|
||
};
|
||
};
|
||
|
||
const newLocalMessageId = (prefix: string) => {
|
||
leaveFlowCounter += 1;
|
||
return `${prefix}-${Date.now()}-${leaveFlowCounter}`;
|
||
};
|
||
|
||
const syncLeaveDuration = (form: LeaveRequestFormData) => {
|
||
form.durationHours = calculateDurationHours(form.startTime, form.endTime);
|
||
};
|
||
|
||
const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\s+/g, '');
|
||
|
||
const isStrongLeaveIntent = (content: string) => {
|
||
const normalized = getLeaveIntentNormalized(content);
|
||
// 弱意图(咨询流程/步骤)应走正常问答,不触发表单分流。
|
||
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定)/;
|
||
if (weakConsultationIntent.test(normalized)) return false;
|
||
if (/^(请假|休假|年假|事假|病假|调休)$/.test(normalized)) return true;
|
||
return /(我要请|申请请|发起请|请假申请|我要休|申请休|想请|帮我请|代我请|提交请)/.test(normalized);
|
||
};
|
||
|
||
const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
|
||
try {
|
||
const res = await fetch('/api/chat/messages/local', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
...getAuthHeaders()
|
||
},
|
||
body: JSON.stringify({
|
||
conversation_id: conversationId.value,
|
||
type: msg.type,
|
||
content: msg.content,
|
||
payload: msg.payload,
|
||
query: userQuery,
|
||
agent_id: agentId
|
||
})
|
||
});
|
||
if (res.ok) {
|
||
const data = await res.json();
|
||
if (!conversationId.value && data.conversation_id) {
|
||
conversationId.value = data.conversation_id;
|
||
}
|
||
if (data.chat_log_id) {
|
||
msg.chat_log_id = data.chat_log_id;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
console.error('Failed to save local message', e);
|
||
}
|
||
};
|
||
|
||
const NEED_BALANCE_CHECK_TYPES = new Set(['010', '408']);
|
||
|
||
const formatLeaveBalanceNumber = (value: any) => {
|
||
if (value === null || value === undefined) return '暂无数据';
|
||
const num = Number(value);
|
||
if (Number.isNaN(num)) return String(value);
|
||
return Number.isInteger(num) ? String(num) : num.toFixed(2);
|
||
};
|
||
|
||
const checkLeaveBalance = async (leaveTypeCode: string): Promise<{
|
||
has_balance: boolean;
|
||
leave_type_label: string;
|
||
year: number;
|
||
total_hours: number | null;
|
||
used_hours: number | null;
|
||
remaining_hours: number | null;
|
||
} | null> => {
|
||
try {
|
||
const res = await fetch(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveTypeCode)}`, {
|
||
headers: getAuthHeaders(),
|
||
});
|
||
if (!res.ok) return null;
|
||
return await res.json();
|
||
} catch (e) {
|
||
console.error('Failed to check leave balance', e);
|
||
return null;
|
||
}
|
||
};
|
||
|
||
const startLocalLeaveFlow = async (content: string) => {
|
||
const initialLeaveType = extractLeaveTypeFromIntent(content);
|
||
|
||
if (initialLeaveType && NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
|
||
messages.value.push({ role: 'user', content, type: 'text' });
|
||
|
||
const thinkingMsg = {
|
||
role: 'assistant' as const,
|
||
type: 'text' as const,
|
||
content: '正在查询您的假期余额,请稍候...',
|
||
};
|
||
messages.value.push(thinkingMsg);
|
||
|
||
const balance = await checkLeaveBalance(initialLeaveType);
|
||
|
||
const thinkingIndex = messages.value.indexOf(thinkingMsg);
|
||
if (thinkingIndex >= 0) {
|
||
messages.value.splice(thinkingIndex, 1);
|
||
}
|
||
|
||
if (balance && !balance.has_balance) {
|
||
const unit = initialLeaveType === '010' ? '天' : '小时';
|
||
const detailLines = [
|
||
`**${balance.leave_type_label}余额不足,暂无可用假期。**`,
|
||
'',
|
||
`| 假别 | 年度 | 可休 | 已休 | 当前剩余 |`,
|
||
`| :---: | :---: | :---: | :---: | :---: |`,
|
||
`| ${balance.leave_type_label} | ${balance.year} | ${formatLeaveBalanceNumber(balance.total_hours)}${unit} | ${formatLeaveBalanceNumber(balance.used_hours)}${unit} | ${formatLeaveBalanceNumber(balance.remaining_hours)}${unit} |`,
|
||
'',
|
||
'如有疑问,请联系人事部门确认假期数据。',
|
||
];
|
||
const noBalanceMsg = {
|
||
role: 'assistant' as const,
|
||
type: 'text' as const,
|
||
content: detailLines.join('\n'),
|
||
};
|
||
messages.value.push(noBalanceMsg);
|
||
await saveLocalMessageToBackend(noBalanceMsg, content);
|
||
|
||
if (history.value.length === 0 || !history.value.some(h => h.conversation_id === conversationId.value)) {
|
||
await loadHistory();
|
||
}
|
||
return;
|
||
}
|
||
}
|
||
|
||
const formId = newLocalMessageId('leave-form');
|
||
const payload: LeaveFormPayload = {
|
||
formId,
|
||
form: createLeaveFormData(content),
|
||
submitting: false,
|
||
confirmationGenerated: false,
|
||
};
|
||
|
||
if (!initialLeaveType || !NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
|
||
messages.value.push({ role: 'user', content, type: 'text' });
|
||
}
|
||
const formMsg = {
|
||
role: 'assistant' as const,
|
||
type: 'leave-form' as const,
|
||
content: '已为你生成请假申请表,请直接在下方填写并提交。或登录OA系统直接申请',
|
||
payload,
|
||
local_id: formId,
|
||
local_only: true,
|
||
};
|
||
messages.value.push(formMsg);
|
||
|
||
try {
|
||
const keyword = payload.form.applicantName || payload.form.employeeId;
|
||
if (keyword) {
|
||
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(keyword)}&page=1&page_size=1&agent_id=${agentId}`, { headers: getAuthHeaders() });
|
||
if (res.ok) {
|
||
const data = await res.json();
|
||
const match = (data.items || []).find((item: LeaveAgentOption) => item.employeeId === payload.form.employeeId);
|
||
if (match) {
|
||
payload.form.fillerJobTitle = match.jobtitle || '';
|
||
payload.form.fillerJobTitleName = match.jobtitleName || '';
|
||
payload.form.fillerDepartmentId = match.departmentid || '';
|
||
payload.form.fillerSubCompanyId1 = match.subcompanyid1 || '';
|
||
payload.form.fillerDepartmentName = match.departmentName || '';
|
||
payload.form.fillerSubCompanyName = match.subcompanyName || '';
|
||
payload.form.applicantUid = match.uid || '';
|
||
payload.form.applicantJobTitle = match.jobtitle || '';
|
||
payload.form.applicantJobTitleName = match.jobtitleName || '';
|
||
payload.form.applicantDepartmentId = match.departmentid || '';
|
||
payload.form.applicantSubCompanyId1 = match.subcompanyid1 || '';
|
||
payload.form.applicantDepartmentName = match.departmentName || '';
|
||
payload.form.applicantSubCompanyName = match.subcompanyName || '';
|
||
}
|
||
}
|
||
}
|
||
} catch (e) {
|
||
console.error('Failed to prefill OA user info', e);
|
||
}
|
||
|
||
await saveLocalMessageToBackend(formMsg, content);
|
||
|
||
// 发送完成后刷新历史记录,确保新会话出现
|
||
if (history.value.length === 0 || !history.value.some(h => h.conversation_id === conversationId.value)) {
|
||
await loadHistory();
|
||
}
|
||
};
|
||
|
||
const handleChatMarkdownClick = (event: MouseEvent) => {
|
||
const target = event.target as HTMLElement | null;
|
||
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
|
||
const previewFile = parsePlmPreviewLink(anchor?.getAttribute('href') || '');
|
||
if (previewFile) {
|
||
event.preventDefault();
|
||
openPreview(previewFile);
|
||
return;
|
||
}
|
||
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
|
||
if (!actionElement) return;
|
||
const action = actionElement.getAttribute('data-leave-action');
|
||
if (action !== 'start-leave-flow' || isThinking.value) return;
|
||
event.preventDefault();
|
||
startLocalLeaveFlow('我要请假');
|
||
};
|
||
|
||
const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => (
|
||
msg?.type === 'leave-form' && msg?.payload ? msg.payload as LeaveFormPayload : null
|
||
);
|
||
|
||
const getLeaveConfirmationPayload = (msg: any): LeaveConfirmationPayload | null => (
|
||
msg?.type === 'leave-confirmation' && msg?.payload ? msg.payload as LeaveConfirmationPayload : null
|
||
);
|
||
|
||
const getLeaveResultPayload = (msg: any): LeaveResultPayload | null => (
|
||
msg?.type === 'leave-result' && msg?.payload ? msg.payload as LeaveResultPayload : null
|
||
);
|
||
|
||
const findMessageIndexByLocalId = (localId: string) => messages.value.findIndex((msg: any) => msg?.local_id === localId || msg?.payload?.formId === localId);
|
||
|
||
const getLeaveAgentDisplayValue = (form: LeaveRequestFormData) => {
|
||
if (!form.agentName) return '';
|
||
const parts = [form.agentName];
|
||
if (form.agentEmployeeId) parts.push(form.agentEmployeeId);
|
||
return parts.join(' / ');
|
||
};
|
||
|
||
const formatYesNoLabel = (value: 0 | 1 | null) => {
|
||
if (value === 0) return '是';
|
||
if (value === 1) return '否';
|
||
return '未选择';
|
||
};
|
||
|
||
const syncCurrentUserProfile = async () => {
|
||
if (currentUser.value?.real_name?.trim()) return;
|
||
try {
|
||
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
|
||
if (!res.ok) return;
|
||
const data = await res.json();
|
||
currentUser.value = { ...currentUser.value, ...data };
|
||
} catch (e) {
|
||
console.error('Failed to load current user profile', e);
|
||
}
|
||
};
|
||
|
||
const openLeaveAgentDialog = (msg: any, role: 'agent' | 'applicant' = 'agent') => {
|
||
const payload = getLeaveFormPayload(msg);
|
||
if (!payload || payload.submitting || payload.confirmationGenerated) return;
|
||
activeLeaveAgentFormId.value = payload.formId;
|
||
leaveUserSelectRole.value = role;
|
||
showLeaveAgentDialog.value = true;
|
||
|
||
leaveAgentKeyword.value = '';
|
||
fetchLeaveAgents(false);
|
||
};
|
||
|
||
const closeLeaveAgentDialog = () => {
|
||
showLeaveAgentDialog.value = false;
|
||
activeLeaveAgentFormId.value = null;
|
||
};
|
||
|
||
const selectLeaveAgent = (option: LeaveAgentOption) => {
|
||
if (!activeLeaveAgentFormId.value) return;
|
||
const sourceIndex = findMessageIndexByLocalId(activeLeaveAgentFormId.value);
|
||
if (sourceIndex < 0) {
|
||
closeLeaveAgentDialog();
|
||
return;
|
||
}
|
||
const payload = getLeaveFormPayload(messages.value[sourceIndex]);
|
||
if (!payload) {
|
||
closeLeaveAgentDialog();
|
||
return;
|
||
}
|
||
|
||
if (leaveUserSelectRole.value === 'agent') {
|
||
payload.form.agentUid = option.uid;
|
||
payload.form.agentEmployeeId = option.employeeId;
|
||
payload.form.agentName = option.name;
|
||
payload.form.agentJobTitle = option.jobtitle;
|
||
payload.form.agentJobTitleName = option.jobtitleName;
|
||
payload.form.agentDepartmentId = option.departmentid;
|
||
payload.form.agentSubCompanyId1 = option.subcompanyid1;
|
||
payload.form.agentDepartmentName = option.departmentName;
|
||
payload.form.agentSubCompanyName = option.subcompanyName;
|
||
} else {
|
||
payload.form.applicantUid = option.uid;
|
||
payload.form.employeeId = option.employeeId;
|
||
payload.form.applicantName = option.name;
|
||
payload.form.applicantJobTitle = option.jobtitle;
|
||
payload.form.applicantJobTitleName = option.jobtitleName;
|
||
payload.form.applicantDepartmentId = option.departmentid;
|
||
payload.form.applicantSubCompanyId1 = option.subcompanyid1;
|
||
payload.form.applicantDepartmentName = option.departmentName;
|
||
payload.form.applicantSubCompanyName = option.subcompanyName;
|
||
}
|
||
|
||
closeLeaveAgentDialog();
|
||
saveLocalMessageToBackend(messages.value[sourceIndex]);
|
||
};
|
||
|
||
const browserPanelStyle = computed(() => {
|
||
if (viewportWidth.value < 1024) return undefined;
|
||
return { width: `${browserPanelWidth.value}px` };
|
||
});
|
||
|
||
const scrollChatToBottom = async () => {
|
||
await nextTick();
|
||
const container = chatScrollContainer.value;
|
||
if (!container) return;
|
||
container.scrollTo({
|
||
top: container.scrollHeight,
|
||
behavior: 'auto',
|
||
});
|
||
};
|
||
|
||
const scrollToUserQuestion = async () => {
|
||
if (scrollToBottomFrame !== null) {
|
||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||
scrollToBottomFrame = null;
|
||
}
|
||
await nextTick();
|
||
await nextTick();
|
||
const container = chatScrollContainer.value;
|
||
if (!container) return;
|
||
let lastUserIndex = -1;
|
||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||
if (messages.value[i]?.role === 'user') {
|
||
lastUserIndex = i;
|
||
break;
|
||
}
|
||
}
|
||
if (lastUserIndex < 0) return;
|
||
const el = container.querySelector(`[data-msg-index="${lastUserIndex}"]`) as HTMLElement | null;
|
||
if (el) {
|
||
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||
}
|
||
};
|
||
|
||
const scheduleScrollChatToBottom = () => {
|
||
if (scrollToBottomFrame !== null) {
|
||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||
}
|
||
scrollToBottomFrame = window.requestAnimationFrame(() => {
|
||
scrollToBottomFrame = null;
|
||
void scrollChatToBottom();
|
||
});
|
||
};
|
||
|
||
const normalizeBrowserInput = (value: string) => {
|
||
const raw = (value || '').trim();
|
||
if (!raw) return '';
|
||
if (/^https?:\/\//i.test(raw)) return raw;
|
||
if (/^localhost(?::\d+)?(\/.*)?$/i.test(raw)) return `http://${raw}`;
|
||
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?(\/.*)?$/.test(raw)) return `http://${raw}`;
|
||
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\/.*)?$/.test(raw)) return `https://${raw}`;
|
||
return '';
|
||
};
|
||
|
||
const toggleBrowserPanel = () => {
|
||
browserPanelOpen.value = !browserPanelOpen.value;
|
||
};
|
||
|
||
const loadBrowserPage = () => {
|
||
const normalized = normalizeBrowserInput(browserDraftUrl.value);
|
||
if (!normalized) {
|
||
showMessageDialog('warning', '请输入有效的网址,例如 `https://example.com` 或 `localhost:8891`。');
|
||
return;
|
||
}
|
||
browserCurrentUrl.value = normalized;
|
||
browserDraftUrl.value = normalized;
|
||
browserFrameKey.value += 1;
|
||
browserPanelOpen.value = true;
|
||
};
|
||
|
||
const refreshBrowserPage = () => {
|
||
if (!browserCurrentUrl.value) {
|
||
loadBrowserPage();
|
||
return;
|
||
}
|
||
browserFrameKey.value += 1;
|
||
};
|
||
|
||
const openBrowserInNewTab = () => {
|
||
const normalized = browserCurrentUrl.value || normalizeBrowserInput(browserDraftUrl.value);
|
||
if (!normalized) {
|
||
showMessageDialog('warning', '请先输入可打开的网址。');
|
||
return;
|
||
}
|
||
window.open(normalized, '_blank', 'noopener,noreferrer');
|
||
};
|
||
|
||
const handleBrowserUrlEnter = (event: KeyboardEvent) => {
|
||
if (event.key !== 'Enter') return;
|
||
event.preventDefault();
|
||
loadBrowserPage();
|
||
};
|
||
|
||
const clampBrowserPanelWidth = (width: number) => {
|
||
const maxAllowed = Math.min(MAX_BROWSER_PANEL_WIDTH, Math.max(MIN_BROWSER_PANEL_WIDTH, Math.floor(window.innerWidth * 0.7)));
|
||
return Math.min(Math.max(width, MIN_BROWSER_PANEL_WIDTH), maxAllowed);
|
||
};
|
||
|
||
const handleBrowserResizeMove = (event: MouseEvent) => {
|
||
if (!isBrowserResizing.value) return;
|
||
browserPanelWidth.value = clampBrowserPanelWidth(window.innerWidth - event.clientX);
|
||
};
|
||
|
||
const stopBrowserResize = () => {
|
||
if (!isBrowserResizing.value) return;
|
||
isBrowserResizing.value = false;
|
||
document.body.style.cursor = '';
|
||
document.body.style.userSelect = '';
|
||
window.removeEventListener('mousemove', handleBrowserResizeMove);
|
||
window.removeEventListener('mouseup', stopBrowserResize);
|
||
};
|
||
|
||
const startBrowserResize = (event: MouseEvent) => {
|
||
if (viewportWidth.value < 1024) return;
|
||
event.preventDefault();
|
||
isBrowserResizing.value = true;
|
||
document.body.style.cursor = 'col-resize';
|
||
document.body.style.userSelect = 'none';
|
||
window.addEventListener('mousemove', handleBrowserResizeMove);
|
||
window.addEventListener('mouseup', stopBrowserResize);
|
||
};
|
||
|
||
const syncViewportWidth = () => {
|
||
viewportWidth.value = window.innerWidth;
|
||
if (viewportWidth.value >= 1024) {
|
||
browserPanelWidth.value = clampBrowserPanelWidth(browserPanelWidth.value);
|
||
}
|
||
};
|
||
|
||
const handleOpenFeedback = (index: number) => {
|
||
activeFeedbackMessageIndex.value = index;
|
||
showGeneralFeedbackDialog.value = true;
|
||
};
|
||
|
||
const currentGeneralFeedbackChatLogId = computed(() => {
|
||
if (activeFeedbackMessageIndex.value !== null) {
|
||
const msg = messages.value[activeFeedbackMessageIndex.value];
|
||
const id = Number(msg?.chat_log_id);
|
||
if (Number.isInteger(id) && id > 0) return id;
|
||
}
|
||
|
||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||
const msg: any = messages.value[i];
|
||
if (msg?.role === 'assistant') {
|
||
const id = Number(msg?.chat_log_id);
|
||
if (Number.isInteger(id) && id > 0) return id;
|
||
}
|
||
}
|
||
return null;
|
||
});
|
||
|
||
interface ChatHistoryItem {
|
||
id: number;
|
||
conversation_id: string;
|
||
title: string;
|
||
created_at: string;
|
||
}
|
||
const history = ref<ChatHistoryItem[]>([]);
|
||
|
||
// 预设问题:从路由 query.preset 中读取(如果有)
|
||
const presetQuestion = computed(() => {
|
||
const q = route.query.preset;
|
||
return typeof q === 'string' ? q : '';
|
||
});
|
||
|
||
/**
|
||
* handleSend
|
||
* 用途:将输入框内容发送给当前 Agent
|
||
*/
|
||
|
||
const handleSend = async (textOrEvent?: string | Event) => {
|
||
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
|
||
if (!content.trim() || isThinking.value) return;
|
||
|
||
if (typeof textOrEvent !== 'string') input.value = '';
|
||
|
||
if (isStrongLeaveIntent(content)) {
|
||
startLocalLeaveFlow(content);
|
||
return;
|
||
}
|
||
|
||
await sendMessage(content, agentId, selectedKb.value);
|
||
|
||
if (!conversationId.value && history.value.length === 0) {
|
||
await loadHistory();
|
||
} else if (conversationId.value) {
|
||
const exists = history.value.some(h => h.conversation_id === conversationId.value);
|
||
if (!exists) await loadHistory();
|
||
}
|
||
};
|
||
|
||
const validateLeaveForm = (form: LeaveRequestFormData) => {
|
||
if (!form.applicantName.trim()) return '请假人不能为空。';
|
||
if (!form.employeeId.trim()) return '工号不能为空。';
|
||
if (!form.leaveType.trim()) return '请选择假别。';
|
||
if (!form.agentUid.trim()) return '请选择代理人。';
|
||
if (!parseDateTime(form.startTime)) return '请选择正确的开始时间。';
|
||
if (!parseDateTime(form.endTime)) return '请选择正确的结束时间。';
|
||
if (calculateDurationHours(form.startTime, form.endTime) <= 0) return '时长必须大于0小时,请检查开始时间和结束时间。';
|
||
return '';
|
||
};
|
||
|
||
const submitLeaveForm = (msg: any) => {
|
||
const payload = getLeaveFormPayload(msg);
|
||
if (!payload) return;
|
||
syncLeaveDuration(payload.form);
|
||
const error = validateLeaveForm(payload.form);
|
||
if (error) {
|
||
showMessageDialog('warning', error);
|
||
return;
|
||
}
|
||
|
||
const existingConfirmIndex = messages.value.findIndex((item: any) => item?.type === 'leave-confirmation' && item?.payload?.formId === payload.formId);
|
||
if (existingConfirmIndex >= 0) {
|
||
messages.value.splice(existingConfirmIndex, 1);
|
||
}
|
||
|
||
payload.confirmationGenerated = true;
|
||
const summary = JSON.parse(JSON.stringify(payload.form)) as LeaveRequestFormData;
|
||
const confirmMsg = {
|
||
role: 'assistant' as const,
|
||
type: 'leave-confirmation' as const,
|
||
content: '请确认以下请假信息,确认无误后再提交到 OA。',
|
||
payload: {
|
||
formId: payload.formId,
|
||
form: summary,
|
||
submitting: false,
|
||
},
|
||
local_id: newLocalMessageId('leave-confirm'),
|
||
local_only: true,
|
||
};
|
||
messages.value.push(confirmMsg);
|
||
|
||
// 保存更新后的表单消息和新的确认消息
|
||
saveLocalMessageToBackend(msg);
|
||
saveLocalMessageToBackend(confirmMsg);
|
||
};
|
||
|
||
const editLeaveConfirmation = (msg: any, index: number) => {
|
||
const payload = getLeaveConfirmationPayload(msg);
|
||
if (!payload) return;
|
||
const sourceIndex = findMessageIndexByLocalId(payload.formId);
|
||
if (sourceIndex >= 0) {
|
||
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
|
||
if (sourcePayload) {
|
||
sourcePayload.confirmationGenerated = false;
|
||
saveLocalMessageToBackend(messages.value[sourceIndex]);
|
||
}
|
||
}
|
||
|
||
// 从后端删除对应的确认消息,或者不删除直接隐藏?
|
||
// 暂时在前端移除,后端不需要立刻删除(如果没有删除接口),它在会话记录里可能残留。
|
||
// 但是我们之前有 /api/chat/messages/local 吗?如果需要,也可以调一个删除接口。
|
||
// 为了简单,我们只在前端切除。
|
||
messages.value.splice(index, 1);
|
||
};
|
||
|
||
const confirmLeaveSubmission = async (msg: any) => {
|
||
const payload = getLeaveConfirmationPayload(msg);
|
||
if (!payload || payload.submitting) return;
|
||
payload.submitting = true;
|
||
|
||
const sourceIndex = findMessageIndexByLocalId(payload.formId);
|
||
if (sourceIndex >= 0) {
|
||
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
|
||
if (sourcePayload) {
|
||
sourcePayload.submitting = true;
|
||
sourcePayload.confirmationGenerated = true;
|
||
}
|
||
}
|
||
|
||
try {
|
||
const res = await fetch('/api/user/leave-workflow/submit', {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
...getAuthHeaders(),
|
||
},
|
||
body: JSON.stringify(payload.form),
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) {
|
||
throw new Error(data?.error || 'OA 请假提交失败,请稍后重试。');
|
||
}
|
||
|
||
const resultMsg = {
|
||
role: 'assistant' as const,
|
||
type: 'leave-result' as const,
|
||
content: '请假单已推送到 OA,具体单据请 【 登录OA系统查看提交】',
|
||
payload: {
|
||
formId: payload.formId,
|
||
success: true,
|
||
referenceNo: data.request_id || '-',
|
||
submittedAt: data.submitted_at || formatDateTime(new Date()),
|
||
requestName: data.request_name || '',
|
||
},
|
||
local_id: newLocalMessageId('leave-result'),
|
||
local_only: true,
|
||
};
|
||
messages.value.push(resultMsg);
|
||
payload.confirmed = true;
|
||
payload.submitting = false; // Add this line to immediately clear submitting state on success
|
||
saveLocalMessageToBackend(msg);
|
||
saveLocalMessageToBackend(resultMsg);
|
||
} catch (error: any) {
|
||
const errorMessage = error?.message || 'OA 请假提交失败,请稍后重试。';
|
||
showMessageDialog('error', errorMessage);
|
||
const resultMsg = {
|
||
role: 'assistant' as const,
|
||
type: 'leave-result' as const,
|
||
content: `请假单提交失败:${errorMessage}`,
|
||
payload: {
|
||
formId: payload.formId,
|
||
success: false,
|
||
referenceNo: '-',
|
||
submittedAt: formatDateTime(new Date()),
|
||
errorMessage,
|
||
},
|
||
local_id: newLocalMessageId('leave-result'),
|
||
local_only: true,
|
||
};
|
||
messages.value.push(resultMsg);
|
||
saveLocalMessageToBackend(resultMsg);
|
||
} finally {
|
||
payload.submitting = false;
|
||
if (sourceIndex >= 0) {
|
||
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
|
||
if (sourcePayload) {
|
||
sourcePayload.submitting = false;
|
||
}
|
||
}
|
||
}
|
||
};
|
||
|
||
const copyToClipboard = async (text: string, index: number) => {
|
||
try {
|
||
await navigator.clipboard.writeText(text);
|
||
copiedIndex.value = index;
|
||
setTimeout(() => {
|
||
copiedIndex.value = null;
|
||
}, 2000);
|
||
} catch (err) {
|
||
console.error('Failed to copy:', err);
|
||
}
|
||
};
|
||
|
||
const regenerate = () => {
|
||
const lastUserMsg = [...messages.value].reverse().find(m => m.role === 'user');
|
||
if (lastUserMsg) {
|
||
handleSend(lastUserMsg.content);
|
||
}
|
||
};
|
||
|
||
// 加载历史记录
|
||
const loadHistory = async () => {
|
||
try {
|
||
const res = await fetch(`/api/chat/sessions?agent_id=${agentId}`, { headers: getAuthHeaders() });
|
||
if (res.ok) {
|
||
history.value = await res.json();
|
||
}
|
||
} catch (e) {
|
||
console.error('Failed to load history', e);
|
||
}
|
||
};
|
||
|
||
const clearAllHistory = async () => {
|
||
if (!confirm('确定要清除全部聊天历史记录吗?此操作不可恢复。')) return;
|
||
try {
|
||
const res = await fetch(`/api/chat/sessions?agent_id=${agentId}`, {
|
||
method: 'DELETE',
|
||
headers: getAuthHeaders()
|
||
});
|
||
if (res.ok) {
|
||
history.value = [];
|
||
if (conversationId.value) {
|
||
startNewChat();
|
||
}
|
||
}
|
||
} catch (e) {
|
||
console.error('Failed to clear history', e);
|
||
}
|
||
};
|
||
|
||
const deleteHistoryItem = async (id: string, event: Event) => {
|
||
event.stopPropagation();
|
||
if (!confirm('确定要删除这条聊天记录吗?')) return;
|
||
try {
|
||
const res = await fetch(`/api/chat/sessions/${id}?agent_id=${agentId}`, {
|
||
method: 'DELETE',
|
||
headers: getAuthHeaders()
|
||
});
|
||
if (res.ok) {
|
||
history.value = history.value.filter(h => h.conversation_id !== id);
|
||
if (conversationId.value === id) {
|
||
startNewChat();
|
||
}
|
||
}
|
||
} catch (e) {
|
||
console.error('Failed to delete history item', e);
|
||
}
|
||
};
|
||
|
||
const loadConversation = async (id: string) => {
|
||
if (conversationId.value === id) return;
|
||
|
||
try {
|
||
const res = await fetch(`/api/chat/messages?conversation_id=${id}&agent_id=${agentId}`, { headers: getAuthHeaders() });
|
||
if (res.ok) {
|
||
messages.value = await res.json();
|
||
conversationId.value = id;
|
||
|
||
// Reset feedback state
|
||
}
|
||
} catch (e) {
|
||
console.error('Failed to load conversation', e);
|
||
}
|
||
};
|
||
|
||
const startNewChat = () => {
|
||
messages.value = [];
|
||
conversationId.value = null;
|
||
};
|
||
|
||
const loadAgent = async () => {
|
||
try {
|
||
const res = await fetch(`/api/user/agents/${agentId}`, { headers: getAuthHeaders() });
|
||
if (res.ok) {
|
||
currentAgent.value = await res.json();
|
||
} else {
|
||
if (res.status === 403) {
|
||
showMessageDialog('error', t('workspace.permission.denied') || 'Access denied');
|
||
router.push('/workspace?no_redirect=1');
|
||
return;
|
||
}
|
||
currentAgent.value = { name: t('workspace.unknownAgent') };
|
||
}
|
||
} catch (e) {
|
||
console.error('Failed to load agent', e);
|
||
}
|
||
};
|
||
|
||
const loadUserAgents = async () => {
|
||
try {
|
||
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
|
||
if (res.ok) {
|
||
const agents = await res.json();
|
||
userAgents.value = Array.isArray(agents)
|
||
? agents.filter((a: any) => a.id !== agentId && (a.dify_app_type || 'chatflow') === 'chatflow')
|
||
: [];
|
||
if (userAgents.value.length === 0) {
|
||
showAgentPanel.value = false;
|
||
}
|
||
}
|
||
} catch (e) {
|
||
userAgents.value = [];
|
||
showAgentPanel.value = false;
|
||
}
|
||
};
|
||
|
||
const switchToAgent = (agent: { id: number; name: string }) => {
|
||
if (agent.id === agentId) return;
|
||
const url = router.resolve(`/chat/${agent.id}`).href;
|
||
window.open(url, '_blank');
|
||
};
|
||
|
||
// 组件挂载时,如果存在预设问题,则自动触发一次发送
|
||
onMounted(async () => {
|
||
document.addEventListener('mousedown', handleDocumentPointerDown);
|
||
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
|
||
document.addEventListener('mousedown', handleMobileAgentPopoverClickOutside);
|
||
document.addEventListener('touchstart', handleMobileAgentPopoverClickOutside, { passive: true });
|
||
window.addEventListener('resize', syncViewportWidth);
|
||
await syncCurrentUserProfile();
|
||
await loadAgent();
|
||
await loadUserAgents();
|
||
|
||
await loadHistory();
|
||
|
||
const convId = route.query.conversation_id as string;
|
||
if (convId) {
|
||
await loadConversation(convId);
|
||
}
|
||
|
||
if (presetQuestion.value) {
|
||
input.value = presetQuestion.value;
|
||
handleSend();
|
||
}
|
||
// Use config from config.ts instead of API
|
||
showChatRating.value = config.workspace?.showChatRating ?? true;
|
||
scheduleScrollChatToBottom();
|
||
});
|
||
|
||
onBeforeUnmount(() => {
|
||
document.removeEventListener('mousedown', handleDocumentPointerDown);
|
||
document.removeEventListener('touchstart', handleDocumentPointerDown);
|
||
document.removeEventListener('mousedown', handleMobileAgentPopoverClickOutside);
|
||
document.removeEventListener('touchstart', handleMobileAgentPopoverClickOutside);
|
||
window.removeEventListener('resize', syncViewportWidth);
|
||
stopBrowserResize();
|
||
if (scrollToBottomFrame !== null) {
|
||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||
scrollToBottomFrame = null;
|
||
}
|
||
});
|
||
|
||
watch(
|
||
() => ({
|
||
messageCount: messages.value.length,
|
||
lastMessageContent: messages.value[messages.value.length - 1]?.content || '',
|
||
lastMessageRole: messages.value[messages.value.length - 1]?.role || '',
|
||
isThinking: isThinking.value,
|
||
conversationId: conversationId.value || '',
|
||
}),
|
||
() => {
|
||
if (wasThinking && !isThinking.value) {
|
||
wasThinking = false;
|
||
scrollToUserQuestion();
|
||
} else {
|
||
if (isThinking.value) wasThinking = true;
|
||
scheduleScrollChatToBottom();
|
||
}
|
||
},
|
||
{ deep: false },
|
||
);
|
||
|
||
/**
|
||
* 反馈相关状态
|
||
* showChatRating:是否启用评分功能(后续可接入配置)
|
||
*/
|
||
const showChatRating = ref(false);
|
||
</script>
|
||
|
||
<template>
|
||
<div class="relative flex h-screen overflow-hidden bg-slate-50 text-slate-800 dark:bg-slate-950 dark:text-slate-100">
|
||
<div
|
||
v-if="isSidebarOpen && !isMobile"
|
||
class="fixed inset-0 z-40 bg-slate-900/55 backdrop-blur-sm transition-opacity md:hidden"
|
||
@click="isSidebarOpen = false"
|
||
></div>
|
||
|
||
<aside
|
||
v-if="!isMobile"
|
||
class="glass-panel fixed inset-y-0 left-0 z-50 flex h-full flex-col border-r bg-white transition-all duration-300 ease-in-out dark:bg-slate-950 md:relative md:translate-x-0"
|
||
:class="[
|
||
isSidebarOpen ? 'translate-x-0 w-[86vw] max-w-[300px]' : '-translate-x-full w-[86vw] max-w-[300px]',
|
||
isSidebarCollapsed ? 'md:w-[72px]' : 'md:w-80'
|
||
]"
|
||
>
|
||
<template v-if="isSidebarCollapsed">
|
||
<div class="flex h-full w-full flex-col items-center py-4">
|
||
<button @click="isSidebarCollapsed = false" class="mb-6 text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
|
||
<PanelLeftOpen class="h-5 w-5" />
|
||
</button>
|
||
|
||
<div class="mb-4 flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-white shadow-sm shadow-brand-500/25">
|
||
<Sparkles class="h-5 w-5" />
|
||
</div>
|
||
|
||
<button @click="startNewChat(); isSidebarOpen = false;" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-slate-50 text-slate-700 shadow-sm transition-colors hover:bg-slate-100 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700" title="创建新对话">
|
||
<Plus class="h-5 w-5" />
|
||
</button>
|
||
|
||
<div class="mt-auto flex flex-col items-center gap-6 pb-2 text-slate-400">
|
||
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Sparkles class="h-5 w-5" /></button>
|
||
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-600 text-sm font-bold text-white shadow-sm shadow-brand-500/20">
|
||
{{ (currentUser?.username || 'I').charAt(0).toUpperCase() }}
|
||
</div>
|
||
<button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" title="意见反馈"><Mail class="h-5 w-5" /></button>
|
||
<button @click="router.push('/workspace?no_redirect=1')" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Settings class="h-5 w-5" /></button>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
|
||
<template v-else>
|
||
<div class="flex items-center justify-between p-4">
|
||
<div class="flex items-center gap-2">
|
||
<div class="flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">AI</div>
|
||
<span class="font-bold text-slate-800 dark:text-slate-100">{{ currentAgent?.name || 'AI' }}</span>
|
||
</div>
|
||
<button @click="isSidebarCollapsed = true" class="text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
|
||
<PanelLeftClose class="h-5 w-5" />
|
||
</button>
|
||
</div>
|
||
|
||
<div class="px-4 pb-4">
|
||
<button @click="startNewChat(); isSidebarOpen = false;" class="flex w-full items-center justify-center gap-2 rounded-xl border border-slate-200 bg-slate-50 py-3 text-sm font-medium text-slate-700 shadow-sm transition-colors hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700">
|
||
<Plus class="h-4 w-4" /> 创建新对话
|
||
</button>
|
||
</div>
|
||
|
||
<div class="flex items-center justify-between px-4 py-2">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">聊天记录</span>
|
||
<button v-if="history.length > 0" @click="clearAllHistory" class="text-xs text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
|
||
清空全部
|
||
</button>
|
||
</div>
|
||
|
||
<div class="flex-1 overflow-y-auto px-2 scrollbar-thin">
|
||
<div v-if="history.length === 0" class="py-8 text-center text-sm italic text-slate-400">{{ $t('chat.noHistory') }}</div>
|
||
<div v-else class="space-y-0.5">
|
||
<div
|
||
v-for="item in history"
|
||
:key="item.conversation_id"
|
||
class="group relative flex w-full items-center justify-between rounded-lg transition-colors"
|
||
:class="conversationId === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'"
|
||
>
|
||
<button
|
||
class="flex-1 truncate px-3 py-2.5 text-left text-sm pr-8"
|
||
:class="conversationId === item.conversation_id
|
||
? 'font-medium text-brand-700 dark:text-brand-300'
|
||
: 'text-slate-600 dark:text-slate-300'"
|
||
@click="loadConversation(item.conversation_id); isSidebarOpen = false;"
|
||
>
|
||
{{ item.title || $t('chat.newChat') }}
|
||
</button>
|
||
<button
|
||
@click="deleteHistoryItem(item.conversation_id, $event)"
|
||
class="absolute right-2 p-1.5 text-slate-400 opacity-0 transition-opacity hover:text-red-500 group-hover:opacity-100 dark:hover:text-red-400"
|
||
title="清除该记录"
|
||
>
|
||
<X class="h-4 w-4" />
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="mt-auto flex flex-col p-4">
|
||
<div v-if="userAgents.length > 0 && showAgentPanel" class="mb-4 rounded-2xl border border-slate-200 bg-slate-50/70 p-3 dark:border-slate-700 dark:bg-slate-800/60">
|
||
<div class="mb-2 flex items-center gap-1.5 text-xs font-semibold text-slate-500 dark:text-slate-400">
|
||
<LayoutGrid class="h-3.5 w-3.5" /> 智能体
|
||
</div>
|
||
<div class="grid grid-cols-2 gap-1.5">
|
||
<button
|
||
v-for="agent in userAgents"
|
||
:key="agent.id"
|
||
@click="switchToAgent(agent)"
|
||
class="flex items-center justify-center gap-1.5 rounded-xl px-2 py-2 text-xs font-medium text-slate-600 transition-colors hover:bg-white hover:shadow-sm dark:text-slate-200 dark:hover:bg-slate-700/50 truncate"
|
||
>
|
||
<div v-if="agent.icon_url" class="h-4 w-4 shrink-0 rounded bg-contain bg-center bg-no-repeat" :style="{ backgroundImage: `url(${agent.icon_url})` }"></div>
|
||
<div v-else class="flex h-4 w-4 shrink-0 items-center justify-center rounded bg-brand-100 text-[9px] font-bold text-brand-600 dark:bg-brand-900/30 dark:text-brand-400">{{ agent.name.charAt(0) }}</div>
|
||
<span class="truncate">{{ agent.name }}</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Bottom Icons -->
|
||
<div class="flex items-center justify-between text-slate-400 relative" ref="userMenuRef">
|
||
<button @click="showUserDropdown = !showUserDropdown" class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-600 text-sm font-bold text-white shadow-sm shadow-brand-500/20 hover:bg-brand-700 transition-colors">
|
||
{{ (currentUser?.username || 'I').charAt(0).toUpperCase() }}
|
||
</button>
|
||
|
||
<!-- User Dropdown Menu -->
|
||
<div v-if="showUserDropdown" class="absolute bottom-full left-0 mb-2 w-56 bg-white dark:bg-slate-900 rounded-xl shadow-xl border border-slate-100 dark:border-slate-700 py-1 z-50 animate-fade-in">
|
||
<div class="px-4 py-3 border-b border-slate-50 dark:border-slate-700 flex items-center gap-3">
|
||
<div class="w-10 h-10 bg-brand-600 rounded-full flex items-center justify-center text-white font-bold text-lg shrink-0 shadow-sm shadow-brand-500/20">
|
||
{{ (currentUser?.username || 'U').charAt(0).toUpperCase() }}
|
||
</div>
|
||
<div class="overflow-hidden">
|
||
<div class="text-sm font-bold text-slate-900 dark:text-slate-100 truncate">{{ currentUser?.username || 'User' }}</div>
|
||
<div v-if="(currentUser as any)?.employee_id" class="text-xs text-slate-500 dark:text-slate-400 truncate">工号: {{ (currentUser as any).employee_id }}</div>
|
||
<div v-else class="text-xs text-slate-500 dark:text-slate-400 truncate">{{ currentUser?.role }}</div>
|
||
</div>
|
||
</div>
|
||
|
||
<button @click="handleLogout" class="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center gap-2 transition-colors mt-1">
|
||
<LogOut class="w-4 h-4" />
|
||
退出登录
|
||
</button>
|
||
</div>
|
||
|
||
<div class="flex gap-3">
|
||
<button @click="userAgents.length === 0 ? undefined : (showAgentPanel = !showAgentPanel)" :class="showAgentPanel && userAgents.length > 0 ? 'text-brand-600 dark:text-brand-400' : ''" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" :title="userAgents.length === 0 ? '暂无可用智能体' : (showAgentPanel ? '收起智能体' : '展开智能体')"><LayoutGrid class="h-4 w-4" /></button>
|
||
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Heart class="h-4 w-4" /></button>
|
||
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Bell class="h-4 w-4" /></button>
|
||
<button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" title="意见反馈"><Mail class="h-4 w-4" /></button>
|
||
<button @click="router.push('/workspace?no_redirect=1')" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Settings class="h-4 w-4" /></button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</template>
|
||
</aside>
|
||
|
||
<div class="relative z-10 flex h-full w-full flex-1 flex-col overflow-hidden bg-white dark:bg-slate-950">
|
||
|
||
<header v-if="isMobile && currentAgent" class="flex items-center justify-between border-b border-slate-200 px-4 py-2.5 dark:border-slate-800">
|
||
<div class="flex items-center gap-2">
|
||
<div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20">AI</div>
|
||
<span class="text-sm font-semibold text-slate-800 dark:text-slate-100">{{ currentAgent?.name || 'AI' }}</span>
|
||
</div>
|
||
<div class="flex items-center gap-1">
|
||
<button @click="toggleMobileAgentPopover" class="flex h-9 w-9 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800" title="智能体">
|
||
<LayoutGrid class="h-5 w-5" />
|
||
</button>
|
||
<button @click="router.push('/workspace?view=history')" class="flex h-9 w-9 items-center justify-center rounded-full text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800" title="历史记录">
|
||
<History class="h-5 w-5" />
|
||
</button>
|
||
</div>
|
||
<div v-if="showMobileAgentPopover" ref="mobileAgentPopoverRef" class="absolute right-4 top-12 z-50 w-72 rounded-2xl border border-slate-200 bg-white p-3 shadow-xl dark:border-slate-700 dark:bg-slate-800">
|
||
<div class="mb-2 text-xs font-medium text-slate-400">智能体</div>
|
||
<div class="grid grid-cols-2 gap-2">
|
||
<button
|
||
v-for="agent in userAgents"
|
||
:key="agent.id"
|
||
@click="switchToAgent(agent); showMobileAgentPopover = false"
|
||
class="flex flex-col items-center gap-1.5 rounded-xl px-2 py-3 text-center transition-colors hover:bg-slate-100 dark:hover:bg-slate-700"
|
||
>
|
||
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-sm font-bold text-brand-600 dark:bg-brand-900/30">
|
||
{{ agent.name.charAt(0) }}
|
||
</div>
|
||
<span class="w-full truncate text-xs font-medium text-slate-700 dark:text-slate-200">{{ agent.name }}</span>
|
||
</button>
|
||
</div>
|
||
<div v-if="userAgents.length === 0" class="py-3 text-center text-xs text-slate-400">暂无其他智能体</div>
|
||
</div>
|
||
</header>
|
||
|
||
<div v-if="!currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
|
||
<Loader2 class="h-10 w-10 animate-spin text-brand-500" />
|
||
<p class="text-sm animate-pulse text-slate-500 dark:text-slate-300">{{ $t('chat.loadingAgent') }}</p>
|
||
</div>
|
||
|
||
<div v-else-if="currentAgent.type === 'iframe'" class="relative h-full w-full flex-1">
|
||
<iframe
|
||
:src="currentAgent.extra_config?.iframe_url"
|
||
class="h-full w-full border-0 bg-white dark:bg-slate-950"
|
||
allow="microphone; camera; clipboard-read; clipboard-write"
|
||
></iframe>
|
||
</div>
|
||
|
||
<template v-else>
|
||
<div class="flex min-h-0 flex-1">
|
||
<div class="flex min-h-0 flex-1 flex-col">
|
||
<main
|
||
ref="chatScrollContainer"
|
||
class="flex-1 p-3 md:p-8"
|
||
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
|
||
>
|
||
<div
|
||
:class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'"
|
||
>
|
||
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center py-2 md:pb-16">
|
||
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
|
||
AI
|
||
</div>
|
||
<h2 class="text-center text-xl font-medium text-slate-800 dark:text-slate-100 md:text-2xl">你好,我是和信AI数字人</h2>
|
||
</div>
|
||
|
||
<template v-for="(msg, index) in messages" :key="index">
|
||
<div
|
||
v-if="shouldRenderMessage(msg)"
|
||
:data-msg-index="index"
|
||
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
|
||
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
|
||
>
|
||
<div
|
||
class="flex flex-col"
|
||
:class="msg.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
|
||
>
|
||
<div
|
||
class="text-[15px] leading-relaxed"
|
||
:class="msg.role === 'user'
|
||
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
|
||
: 'w-full rounded-2xl border border-slate-200 bg-white px-6 py-4 shadow-sm dark:border-slate-800 dark:bg-slate-900 dark:text-slate-100'"
|
||
>
|
||
<div
|
||
v-if="msg.role === 'user'"
|
||
class="whitespace-pre-wrap"
|
||
>{{ msg.content }}</div>
|
||
<div v-else>
|
||
<div v-if="msg.type === 'leave-form'" class="space-y-4">
|
||
<div class="text-sm font-medium text-slate-700 dark:text-slate-200">
|
||
<template v-if="msg.content.includes('或登录OA系统直接申请')">
|
||
已为你生成请假申请表,请直接在下方填写并提交。或 <a href="#" @click.prevent="openOALeaveRequestDirectly" class="text-brand-600 font-bold hover:underline">登录OA系统直接申请</a>
|
||
</template>
|
||
<template v-else>
|
||
{{ msg.content }}
|
||
</template>
|
||
</div>
|
||
<div v-if="getLeaveFormPayload(msg)" class="grid gap-4 md:grid-cols-2">
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">填单人</span>
|
||
<input
|
||
v-model="getLeaveFormPayload(msg)!.form.fillerName"
|
||
type="text"
|
||
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-500 outline-none dark:border-slate-700 dark:bg-slate-950/60 dark:text-slate-400"
|
||
disabled
|
||
/>
|
||
</label>
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">工号</span>
|
||
<input
|
||
v-model="getLeaveFormPayload(msg)!.form.employeeId"
|
||
type="text"
|
||
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-500 outline-none dark:border-slate-700 dark:bg-slate-950/60 dark:text-slate-400"
|
||
disabled
|
||
/>
|
||
</label>
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">创建时间</span>
|
||
<input
|
||
:value="getLeaveFormPayload(msg)!.form.applyTime.replace('T', ' ')"
|
||
type="text"
|
||
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-500 outline-none dark:border-slate-700 dark:bg-slate-950/60 dark:text-slate-400"
|
||
disabled
|
||
/>
|
||
</label>
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">假别</span>
|
||
<select
|
||
v-model="getLeaveFormPayload(msg)!.form.leaveType"
|
||
class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||
>
|
||
<option value="" disabled>请选择假别</option>
|
||
<option v-for="leaveType in LEAVE_TYPES" :key="leaveType.value" :value="leaveType.value">{{ leaveType.label }}</option>
|
||
</select>
|
||
</label>
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">请假人</span>
|
||
<div class="relative">
|
||
<input
|
||
:value="getLeaveFormPayload(msg)!.form.applicantName ? `${getLeaveFormPayload(msg)!.form.applicantName} / ${getLeaveFormPayload(msg)!.form.employeeId}` : ''"
|
||
type="text"
|
||
placeholder="请选择请假人"
|
||
readonly
|
||
class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 pr-11 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||
@click="openLeaveAgentDialog(msg, 'applicant')"
|
||
/>
|
||
<button
|
||
type="button"
|
||
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-slate-400 transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||
@click="openLeaveAgentDialog(msg, 'applicant')"
|
||
title="选择请假人"
|
||
>
|
||
<Search class="h-4 w-4" />
|
||
</button>
|
||
</div>
|
||
</label>
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">代理人</span>
|
||
<div class="relative">
|
||
<input
|
||
:value="getLeaveAgentDisplayValue(getLeaveFormPayload(msg)!.form)"
|
||
type="text"
|
||
placeholder="请选择代理人"
|
||
readonly
|
||
class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 pr-11 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||
@click="openLeaveAgentDialog(msg)"
|
||
/>
|
||
<button
|
||
type="button"
|
||
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-slate-400 transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||
@click="openLeaveAgentDialog(msg)"
|
||
title="选择代理人"
|
||
>
|
||
<Search class="h-4 w-4" />
|
||
</button>
|
||
</div>
|
||
</label>
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">开始时间</span>
|
||
<input
|
||
v-model="getLeaveFormPayload(msg)!.form.startTime"
|
||
type="datetime-local"
|
||
class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||
@input="syncLeaveDuration(getLeaveFormPayload(msg)!.form)"
|
||
/>
|
||
</label>
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">结束时间</span>
|
||
<input
|
||
v-model="getLeaveFormPayload(msg)!.form.endTime"
|
||
type="datetime-local"
|
||
class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||
@input="syncLeaveDuration(getLeaveFormPayload(msg)!.form)"
|
||
/>
|
||
</label>
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">时长</span>
|
||
<input
|
||
:value="formatDurationLabel(getLeaveFormPayload(msg)!.form.durationHours)"
|
||
type="text"
|
||
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-500 outline-none dark:border-slate-700 dark:bg-slate-950/60 dark:text-slate-400"
|
||
disabled
|
||
/>
|
||
</label>
|
||
<label class="space-y-1.5">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">是否外出</span>
|
||
<select
|
||
v-model="getLeaveFormPayload(msg)!.form.isOutOfOffice"
|
||
class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||
>
|
||
<option :value="1">否</option>
|
||
<option :value="0">是</option>
|
||
</select>
|
||
</label>
|
||
<label class="space-y-1.5 md:col-span-2">
|
||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">是否为工伤</span>
|
||
<select
|
||
v-model="getLeaveFormPayload(msg)!.form.isWorkInjury"
|
||
class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||
>
|
||
<option :value="1">否</option>
|
||
<option :value="0">是</option>
|
||
</select>
|
||
</label>
|
||
</div>
|
||
<div v-if="getLeaveFormPayload(msg)?.confirmationGenerated" class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-xs text-amber-700 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200">
|
||
已生成确认单,如需调整可直接修改表单后再次点击提交。
|
||
</div>
|
||
<div class="flex justify-end">
|
||
<button
|
||
@click="submitLeaveForm(msg)"
|
||
:disabled="getLeaveFormPayload(msg)?.submitting || getLeaveFormPayload(msg)?.confirmationGenerated"
|
||
class="rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||
>
|
||
{{ getLeaveFormPayload(msg)?.submitting ? '提交中...' : '提交' }}
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<div v-else-if="msg.type === 'leave-confirmation' && getLeaveConfirmationPayload(msg)" class="space-y-4">
|
||
<div class="text-sm font-medium text-slate-700 dark:text-slate-200">{{ msg.content }}</div>
|
||
<div class="rounded-2xl border border-slate-200 bg-slate-50/90 p-4 dark:border-slate-700 dark:bg-slate-800/60">
|
||
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">填单人信息</div>
|
||
<div class="grid gap-3 text-sm md:grid-cols-2">
|
||
<div><span class="text-slate-500 dark:text-slate-400">填单人:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerName || '暂无数据' }}</div>
|
||
<div><span class="text-slate-500 dark:text-slate-400">创建时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.applyTime.replace('T', ' ') }}</div>
|
||
<div v-if="getLeaveConfirmationPayload(msg)!.form.fillerJobTitleName || getLeaveConfirmationPayload(msg)!.form.fillerJobTitle"><span class="text-slate-500 dark:text-slate-400">填单人职务:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerJobTitleName || getLeaveConfirmationPayload(msg)!.form.fillerJobTitle }}</div>
|
||
<div v-if="getLeaveConfirmationPayload(msg)!.form.fillerDepartmentName || getLeaveConfirmationPayload(msg)!.form.fillerDepartmentId"><span class="text-slate-500 dark:text-slate-400">填单人部门:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerDepartmentName || getLeaveConfirmationPayload(msg)!.form.fillerDepartmentId }}</div>
|
||
<div v-if="getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyName || getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyId1"><span class="text-slate-500 dark:text-slate-400">填单人公司:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyName || getLeaveConfirmationPayload(msg)!.form.fillerSubCompanyId1 }}</div>
|
||
</div>
|
||
<div class="my-3 border-t border-slate-200 dark:border-slate-700"></div>
|
||
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">申请人信息</div>
|
||
<div class="grid gap-3 text-sm md:grid-cols-2">
|
||
<div><span class="text-slate-500 dark:text-slate-400">请假人:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantName }}({{ getLeaveConfirmationPayload(msg)!.form.employeeId }})</div>
|
||
<div v-if="getLeaveConfirmationPayload(msg)!.form.applicantJobTitleName || getLeaveConfirmationPayload(msg)!.form.applicantJobTitle"><span class="text-slate-500 dark:text-slate-400">申请人职务:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantJobTitleName || getLeaveConfirmationPayload(msg)!.form.applicantJobTitle }}</div>
|
||
<div v-if="getLeaveConfirmationPayload(msg)!.form.applicantDepartmentName || getLeaveConfirmationPayload(msg)!.form.applicantDepartmentId"><span class="text-slate-500 dark:text-slate-400">申请人部门:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantDepartmentName || getLeaveConfirmationPayload(msg)!.form.applicantDepartmentId }}</div>
|
||
<div v-if="getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyName || getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyId1"><span class="text-slate-500 dark:text-slate-400">申请人公司:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyName || getLeaveConfirmationPayload(msg)!.form.applicantSubCompanyId1 }}</div>
|
||
</div>
|
||
<div class="my-3 border-t border-slate-200 dark:border-slate-700"></div>
|
||
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-slate-400 dark:text-slate-500">请假信息</div>
|
||
<div class="grid gap-3 text-sm md:grid-cols-2">
|
||
<div><span class="text-slate-500 dark:text-slate-400">代理人:</span>{{ getLeaveAgentDisplayValue(getLeaveConfirmationPayload(msg)!.form) || '未选择' }}</div>
|
||
<div v-if="getLeaveConfirmationPayload(msg)!.form.agentJobTitleName || getLeaveConfirmationPayload(msg)!.form.agentJobTitle"><span class="text-slate-500 dark:text-slate-400">代理人职务:</span>{{ getLeaveConfirmationPayload(msg)!.form.agentJobTitleName || getLeaveConfirmationPayload(msg)!.form.agentJobTitle }}</div>
|
||
<div v-if="getLeaveConfirmationPayload(msg)!.form.agentDepartmentName || getLeaveConfirmationPayload(msg)!.form.agentDepartmentId"><span class="text-slate-500 dark:text-slate-400">代理人部门:</span>{{ getLeaveConfirmationPayload(msg)!.form.agentDepartmentName || getLeaveConfirmationPayload(msg)!.form.agentDepartmentId }}</div>
|
||
<div v-if="getLeaveConfirmationPayload(msg)!.form.agentSubCompanyName || getLeaveConfirmationPayload(msg)!.form.agentSubCompanyId1"><span class="text-slate-500 dark:text-slate-400">代理人公司:</span>{{ getLeaveConfirmationPayload(msg)!.form.agentSubCompanyName || getLeaveConfirmationPayload(msg)!.form.agentSubCompanyId1 }}</div>
|
||
<div><span class="text-slate-500 dark:text-slate-400">假别:</span>{{ getLeaveTypeLabel(getLeaveConfirmationPayload(msg)!.form.leaveType) }}</div>
|
||
<div><span class="text-slate-500 dark:text-slate-400">时长:</span>{{ formatDurationLabel(getLeaveConfirmationPayload(msg)!.form.durationHours) }}</div>
|
||
<div><span class="text-slate-500 dark:text-slate-400">开始时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.startTime.replace('T', ' ') }}</div>
|
||
<div><span class="text-slate-500 dark:text-slate-400">结束时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.endTime.replace('T', ' ') }}</div>
|
||
<div><span class="text-slate-500 dark:text-slate-400">是否外出:</span>{{ formatYesNoLabel(getLeaveConfirmationPayload(msg)!.form.isOutOfOffice) }}</div>
|
||
<div><span class="text-slate-500 dark:text-slate-400">是否为工伤:</span>{{ formatYesNoLabel(getLeaveConfirmationPayload(msg)!.form.isWorkInjury) }}</div>
|
||
</div>
|
||
</div>
|
||
<div class="flex justify-end gap-3">
|
||
<button
|
||
v-if="!getLeaveConfirmationPayload(msg)?.submitting && !getLeaveConfirmationPayload(msg)?.confirmed"
|
||
@click="editLeaveConfirmation(msg, index)"
|
||
class="rounded-xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-60 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
|
||
>
|
||
返回修改
|
||
</button>
|
||
<button
|
||
@click="confirmLeaveSubmission(msg)"
|
||
:disabled="getLeaveConfirmationPayload(msg)?.submitting || getLeaveConfirmationPayload(msg)?.confirmed"
|
||
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||
>
|
||
{{ getLeaveConfirmationPayload(msg)?.submitting ? '确认中...' : (getLeaveConfirmationPayload(msg)?.confirmed ? '已确认' : '确认') }}
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<div v-else-if="msg.type === 'leave-result' && getLeaveResultPayload(msg)" class="space-y-3">
|
||
<div
|
||
class="rounded-2xl border px-4 py-4"
|
||
:class="getLeaveResultPayload(msg)!.success
|
||
? 'border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-500/30 dark:bg-emerald-500/10 dark:text-emerald-100'
|
||
: 'border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-500/30 dark:bg-rose-500/10 dark:text-rose-100'"
|
||
>
|
||
<div class="text-sm font-semibold">{{ getLeaveResultPayload(msg)!.success ? 'OA 提交结果' : 'OA 提交失败' }}</div>
|
||
<div v-if="getLeaveResultPayload(msg)!.success" class="mt-2 whitespace-pre-wrap text-sm leading-7">
|
||
请假单已推送到 OA,具体单据请
|
||
<a
|
||
href="#"
|
||
@click.prevent="openOARequestDirectly(getLeaveResultPayload(msg)!.referenceNo)"
|
||
class="ml-1 inline-flex items-center rounded-full border border-brand-200 bg-brand-50 px-3 py-0.5 font-bold text-brand-700 transition hover:bg-brand-100 hover:underline dark:border-brand-500/30 dark:bg-brand-500/10 dark:text-brand-200 dark:hover:bg-brand-500/20"
|
||
>
|
||
【 登录OA系统查看提交】
|
||
</a>
|
||
</div>
|
||
<div v-else class="mt-2 whitespace-pre-wrap text-sm leading-7">{{ msg.content }}</div>
|
||
<div class="mt-3 text-xs opacity-80">单据编号:{{ getLeaveResultPayload(msg)!.referenceNo }}</div>
|
||
<div class="mt-1 text-xs opacity-80">提交时间:{{ getLeaveResultPayload(msg)!.submittedAt }}</div>
|
||
</div>
|
||
</div>
|
||
<div
|
||
v-else
|
||
class="chat-markdown prose prose-sm max-w-none leading-7 text-slate-800 dark:text-slate-100 prose-a:text-blue-600 dark:prose-a:text-blue-400 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 dark:prose-code:bg-slate-800 dark:prose-code:text-blue-300 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
|
||
@click="handleChatMarkdownClick"
|
||
v-html="renderMarkdown(msg.content)"
|
||
></div>
|
||
</div>
|
||
</div>
|
||
|
||
<div
|
||
v-if=" msg.role === 'assistant' && msg.type !== 'leave-form' && msg.type !== 'leave-confirmation' && msg.type !== 'leave-result' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getSourceLinks(getDisplayRetrieverResources(msg)).length > 0)"
|
||
class="mt-2 space-y-2"
|
||
>
|
||
<!-- 带有URL链接的源文件名称,支持预览 -->
|
||
<div v-if="getSourceLinks(getDisplayRetrieverResources(msg)).length > 0" class="flex flex-wrap gap-2">
|
||
<button
|
||
v-for="(file, linkIndex) in getSourceLinks(getDisplayRetrieverResources(msg))"
|
||
:key="`src-link-top-${linkIndex}-${file.url}`"
|
||
@click="openPreview(file)"
|
||
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 dark:border-brand-500/30 dark:bg-brand-500/10 dark:text-brand-200 dark:hover:bg-brand-500/20"
|
||
>
|
||
{{ file.name }}
|
||
</button>
|
||
</div>
|
||
|
||
<details
|
||
v-if="getDisplayRetrieverResources(msg).length > 0"
|
||
class="rounded-xl border border-slate-200 bg-slate-50/90 px-4 py-3 dark:border-slate-700 dark:bg-slate-800/65"
|
||
:open="shouldExpandSourceDetails(msg)"
|
||
>
|
||
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300">
|
||
源文档 ({{ getDisplayRetrieverResources(msg).length }})
|
||
</summary>
|
||
<div class="mt-3 space-y-2">
|
||
<div
|
||
v-for="(doc, docIndex) in getDisplayRetrieverResources(msg)"
|
||
:key="`${doc.document_name || 'doc'}-${doc.segment_id || docIndex}`"
|
||
class="rounded-lg border border-slate-200 bg-white p-3 dark:border-slate-700 dark:bg-slate-900"
|
||
>
|
||
<div class="break-all text-sm font-semibold text-slate-800 dark:text-slate-100">{{ getSourceTitle(doc) }}</div>
|
||
<div v-if="getSourceMeta(doc)" class="mt-1 text-xs text-slate-500 dark:text-slate-400">{{ getSourceMeta(doc) }}</div>
|
||
<div v-if="getSourceBrief(doc)" class="mt-2 whitespace-pre-wrap break-all text-xs text-slate-600 dark:text-slate-300">{{ getSourceBrief(doc) }}</div>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<details
|
||
v-if="msg.attribution_parts && msg.attribution_parts.length > 0"
|
||
class="rounded-xl border border-slate-200 bg-slate-50/90 px-4 py-3 dark:border-slate-700 dark:bg-slate-800/65"
|
||
open
|
||
>
|
||
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300">
|
||
生成内容归属部分
|
||
</summary>
|
||
<ul class="mt-3 space-y-2">
|
||
<li
|
||
v-for="(part, partIndex) in msg.attribution_parts"
|
||
:key="`attr-${partIndex}`"
|
||
class="rounded-lg border border-slate-200 bg-white p-3 text-xs text-slate-700 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300"
|
||
>
|
||
{{ part }}
|
||
</li>
|
||
</ul>
|
||
</details>
|
||
</div>
|
||
|
||
<div
|
||
v-if="msg.type !== 'leave-form'"
|
||
class="mt-1 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100"
|
||
:class="msg.role === 'user' ? 'justify-end text-slate-500' : 'justify-start text-slate-500'"
|
||
>
|
||
<button
|
||
@click="copyToClipboard(msg.content, index)"
|
||
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
||
:title="$t('chat.actions.copy')"
|
||
>
|
||
<Check v-if="copiedIndex === index" class="h-3.5 w-3.5 text-emerald-500" />
|
||
<Copy v-else class="h-3.5 w-3.5" />
|
||
</button>
|
||
|
||
<template v-if="msg.role === 'user'">
|
||
<button
|
||
@click="input = msg.content"
|
||
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
||
:title="$t('chat.actions.edit')"
|
||
>
|
||
<Edit2 class="h-3.5 w-3.5" />
|
||
</button>
|
||
<button
|
||
@click="handleSend(msg.content)"
|
||
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
||
:title="$t('chat.actions.resend')"
|
||
>
|
||
<RotateCw class="h-3.5 w-3.5" />
|
||
</button>
|
||
</template>
|
||
|
||
<template v-else>
|
||
<button
|
||
v-if="index === messages.length - 1 && !isThinking"
|
||
@click="regenerate"
|
||
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
||
:title="$t('chat.actions.regenerate')"
|
||
>
|
||
<RotateCw class="h-3.5 w-3.5" />
|
||
</button>
|
||
<button
|
||
v-if="showChatRating && !isThinking && !(msg as any).rated"
|
||
@click="handleOpenFeedback(index)"
|
||
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
|
||
title="评价回答"
|
||
>
|
||
<MessageSquareText class="h-3.5 w-3.5" />
|
||
</button>
|
||
</template>
|
||
</div>
|
||
</div>
|
||
|
||
</div>
|
||
</template>
|
||
|
||
<div v-if="shouldShowThinkingBubble" class="mx-auto flex w-full max-w-4xl justify-start">
|
||
<div class="flex items-center gap-3 rounded-2xl rounded-tl-md border border-slate-200 bg-white/95 px-5 py-3 shadow-md dark:border-slate-700 dark:bg-slate-900/85">
|
||
<div class="flex gap-1">
|
||
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400"></span>
|
||
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400 delay-75"></span>
|
||
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400 delay-150"></span>
|
||
</div>
|
||
<span class="text-sm font-medium text-slate-500 dark:text-slate-300">{{ $t('chat.thinking') }}</span>
|
||
</div>
|
||
</div>
|
||
<div v-if="messages.length > 0" class="h-2 md:h-3"></div>
|
||
</div>
|
||
</main>
|
||
|
||
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
|
||
<div class="relative mx-auto max-w-4xl">
|
||
<div class="flex flex-col rounded-2xl bg-white p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all dark:bg-slate-900">
|
||
<textarea
|
||
v-model="input"
|
||
@keydown.enter.prevent="handleSend"
|
||
rows="1"
|
||
placeholder="问我任何事..."
|
||
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent dark:text-slate-100"
|
||
style="min-height: 44px; max-height: 220px;"
|
||
:disabled="isThinking"
|
||
spellcheck="false"
|
||
autocorrect="off"
|
||
autocapitalize="off"
|
||
></textarea>
|
||
|
||
<div class="mt-2 flex items-center justify-between px-2 pb-1">
|
||
<div class="flex items-center gap-3">
|
||
<button
|
||
@click="handleVoiceFeatureClick"
|
||
type="button"
|
||
title="语音功能"
|
||
class="text-slate-400 transition-colors hover:text-brand-600 dark:hover:text-brand-300"
|
||
>
|
||
<Mic class="h-5 w-5" />
|
||
</button>
|
||
<div class="relative" ref="kbMenuRef">
|
||
<button
|
||
@click="showKbDropdown = !showKbDropdown"
|
||
class="flex items-center gap-1 rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-600 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||
>
|
||
<Database class="h-3.5 w-3.5 text-brand-500" />
|
||
{{ selectedKb }} <ChevronDown class="h-3 w-3" />
|
||
</button>
|
||
<div
|
||
v-if="showKbDropdown"
|
||
class="absolute bottom-full left-0 mb-2 w-36 overflow-hidden rounded-xl border border-slate-100 bg-white py-1 shadow-xl animate-fade-in dark:border-slate-700 dark:bg-slate-900"
|
||
>
|
||
<button
|
||
v-for="option in kbOptions"
|
||
:key="option"
|
||
@click="selectedKb = option; showKbDropdown = false"
|
||
class="flex w-full items-center justify-between px-3 py-2 text-xs text-slate-700 transition-colors hover:bg-slate-50 dark:text-slate-300 dark:hover:bg-slate-800"
|
||
:class="{ 'font-bold text-brand-700 dark:text-brand-300': selectedKb === option }"
|
||
>
|
||
{{ option }}
|
||
<Check v-if="selectedKb === option" class="h-3.5 w-3.5" />
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<button
|
||
@click="toggleBrowserPanel"
|
||
class="flex items-center gap-1 rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-600 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||
>
|
||
<Globe class="h-3.5 w-3.5 text-brand-500" />
|
||
{{ browserPanelOpen ? '收起浏览器' : '打开浏览器' }}
|
||
</button>
|
||
</div>
|
||
<button
|
||
@click="handleSend"
|
||
:disabled="!input.trim() || isThinking"
|
||
class="flex h-10 w-10 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
|
||
:class="!input.trim() || isThinking
|
||
? 'border-slate-200 bg-slate-100 text-slate-400 dark:border-slate-700 dark:bg-slate-800'
|
||
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
|
||
>
|
||
<Send class="h-4 w-4" />
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<div class="mt-3 text-center text-[11px] text-slate-400">
|
||
AI 可能会犯错,请核实重要信息。
|
||
</div>
|
||
</div>
|
||
</footer>
|
||
</div>
|
||
|
||
<div
|
||
v-if="browserPanelOpen"
|
||
class="fixed inset-0 z-40 bg-slate-900/40 backdrop-blur-sm lg:hidden"
|
||
@click="browserPanelOpen = false"
|
||
></div>
|
||
|
||
<div
|
||
v-if="browserPanelOpen"
|
||
class="relative z-10 hidden w-2 shrink-0 cursor-col-resize bg-transparent lg:block"
|
||
@mousedown="startBrowserResize"
|
||
>
|
||
<div
|
||
class="absolute inset-y-0 left-1/2 w-px -translate-x-1/2 transition-colors"
|
||
:class="isBrowserResizing ? 'bg-brand-500' : 'bg-slate-200 dark:bg-slate-800'"
|
||
></div>
|
||
</div>
|
||
|
||
<aside
|
||
v-if="browserPanelOpen"
|
||
class="fixed inset-y-0 right-0 z-50 flex w-full max-w-[100vw] flex-col border-l border-slate-200 bg-white shadow-2xl dark:border-slate-800 dark:bg-slate-950 sm:w-[420px] lg:static lg:z-0 lg:w-[420px] lg:shadow-none"
|
||
:style="browserPanelStyle"
|
||
>
|
||
<div class="flex items-center justify-between border-b border-slate-200 px-4 py-3 dark:border-slate-800">
|
||
<div class="flex items-center gap-2 text-sm font-semibold text-slate-700 dark:text-slate-100">
|
||
<Globe class="h-4 w-4 text-brand-500" />
|
||
浏览器
|
||
</div>
|
||
<button
|
||
@click="browserPanelOpen = false"
|
||
class="rounded-md p-1.5 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600 dark:hover:bg-slate-800 dark:hover:text-slate-200"
|
||
title="关闭浏览器"
|
||
>
|
||
<X class="h-4 w-4" />
|
||
</button>
|
||
</div>
|
||
|
||
<div class="flex items-center gap-2 border-b border-slate-200 px-3 py-3 dark:border-slate-800">
|
||
<input
|
||
v-model="browserDraftUrl"
|
||
type="text"
|
||
placeholder="输入网址,例如 https://example.com"
|
||
class="flex-1 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-800 outline-none transition focus:border-brand-400 focus:bg-white dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100 dark:focus:bg-slate-950"
|
||
@keydown="handleBrowserUrlEnter"
|
||
/>
|
||
<button
|
||
@click="loadBrowserPage"
|
||
class="rounded-xl bg-brand-600 px-3 py-2 text-xs font-medium text-white transition-colors hover:bg-brand-500"
|
||
>
|
||
打开
|
||
</button>
|
||
<button
|
||
@click="refreshBrowserPage"
|
||
class="rounded-xl border border-slate-200 p-2 text-slate-500 transition-colors hover:bg-slate-50 hover:text-slate-700 dark:border-slate-700 dark:hover:bg-slate-800 dark:hover:text-slate-200"
|
||
title="刷新"
|
||
>
|
||
<RotateCw class="h-4 w-4" />
|
||
</button>
|
||
<button
|
||
@click="openBrowserInNewTab"
|
||
class="rounded-xl border border-slate-200 p-2 text-slate-500 transition-colors hover:bg-slate-50 hover:text-slate-700 dark:border-slate-700 dark:hover:bg-slate-800 dark:hover:text-slate-200"
|
||
title="新标签打开"
|
||
>
|
||
<ExternalLink class="h-4 w-4" />
|
||
</button>
|
||
</div>
|
||
|
||
<div class="min-h-0 flex-1 bg-slate-100 dark:bg-slate-900">
|
||
<div
|
||
v-if="!browserCurrentUrl"
|
||
class="flex h-full flex-col items-center justify-center gap-3 px-8 text-center text-sm text-slate-500 dark:text-slate-400"
|
||
>
|
||
<Globe class="h-8 w-8 text-brand-500" />
|
||
<div>在这里直接打开网页,边聊天边查看内容。</div>
|
||
<div class="text-xs">支持输入 `https://`、`localhost` 或内网 IP 地址。</div>
|
||
</div>
|
||
<iframe
|
||
v-else
|
||
:key="browserFrameKey"
|
||
:src="browserCurrentUrl"
|
||
class="h-full w-full border-0 bg-white dark:bg-slate-950"
|
||
allow="clipboard-read; clipboard-write"
|
||
></iframe>
|
||
</div>
|
||
</aside>
|
||
</div>
|
||
</template>
|
||
</div>
|
||
</div>
|
||
|
||
<FilePreviewModal
|
||
v-model="filePreviewVisible"
|
||
:file="previewFile"
|
||
:agent-id="agentId"
|
||
:auth-headers="getAuthHeaders()"
|
||
/>
|
||
<GeneralFeedbackDialog
|
||
v-model="showGeneralFeedbackDialog"
|
||
:auth-headers="getAuthHeaders()"
|
||
source-page="chat"
|
||
:chat-log-id="currentGeneralFeedbackChatLogId"
|
||
@submitted="() => {
|
||
if (activeFeedbackMessageIndex !== null && messages[activeFeedbackMessageIndex]) {
|
||
(messages[activeFeedbackMessageIndex] as any).rated = true;
|
||
}
|
||
showMessageDialog('success', '\u53cd\u9988\u63d0\u4ea4\u6210\u529f');
|
||
showGeneralFeedbackDialog = false;
|
||
}"
|
||
/>
|
||
<div
|
||
v-if="showLeaveAgentDialog"
|
||
class="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm p-4"
|
||
@click.self="closeLeaveAgentDialog"
|
||
>
|
||
<div class="flex w-full max-w-2xl max-h-[80vh] flex-col rounded-2xl bg-white p-6 shadow-2xl dark:bg-slate-900">
|
||
<div class="mb-4 flex items-center justify-between">
|
||
<div>
|
||
<h3 class="text-lg font-bold text-slate-800 dark:text-slate-100">选择{{ leaveUserSelectRole === 'agent' ? '代理人' : '请假人' }}</h3>
|
||
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">已接入 OA 数据库视图查询。</p>
|
||
</div>
|
||
<button @click="closeLeaveAgentDialog" class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200">
|
||
<X class="h-5 w-5" />
|
||
</button>
|
||
</div>
|
||
|
||
<div class="mb-4 relative shrink-0">
|
||
<input
|
||
v-model="leaveAgentKeyword"
|
||
@keydown.enter="handleAgentSearch"
|
||
type="text"
|
||
placeholder="输入姓名或工号搜索,按回车键查询"
|
||
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 pr-10 text-sm outline-none transition focus:border-brand-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||
/>
|
||
<button @click="handleAgentSearch" class="absolute inset-y-0 right-0 flex w-10 items-center justify-center text-slate-400 hover:text-brand-600">
|
||
<Search class="h-4 w-4" />
|
||
</button>
|
||
</div>
|
||
|
||
<div class="flex-1 space-y-3 overflow-y-auto pr-2 scrollbar-thin">
|
||
<div v-if="leaveAgentLoading && leaveAgentPage === 1" class="flex justify-center py-8">
|
||
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
|
||
</div>
|
||
<div v-else-if="leaveAgentOptions.length === 0" class="py-8 text-center text-sm text-slate-400">
|
||
暂无数据
|
||
</div>
|
||
<template v-else>
|
||
<button
|
||
v-for="option in leaveAgentOptions"
|
||
:key="option.uid"
|
||
type="button"
|
||
class="flex w-full items-center justify-between rounded-2xl border border-slate-200 px-4 py-4 text-left transition hover:border-brand-300 hover:bg-brand-50/50 dark:border-slate-700 dark:hover:border-brand-500/40 dark:hover:bg-brand-500/10"
|
||
@click="selectLeaveAgent(option)"
|
||
>
|
||
<div class="space-y-1">
|
||
<div class="text-sm font-semibold text-slate-800 dark:text-slate-100">{{ option.name }}</div>
|
||
<div class="text-xs text-slate-500 dark:text-slate-400">UID:{{ option.uid }}</div>
|
||
</div>
|
||
<div class="text-right text-xs text-slate-500 dark:text-slate-400">
|
||
<div>工号:{{ option.employeeId }}</div>
|
||
<div>姓名:{{ option.name }}</div>
|
||
</div>
|
||
</button>
|
||
|
||
<div v-if="leaveAgentHasMore" class="flex items-center justify-center space-x-6 py-4">
|
||
<button
|
||
@click="loadAllAgents"
|
||
:disabled="leaveAgentLoading"
|
||
class="text-xs text-slate-500 hover:text-slate-700 disabled:opacity-50 dark:text-slate-400 dark:hover:text-slate-300"
|
||
>
|
||
加载全部
|
||
</button>
|
||
<button
|
||
@click="loadMoreAgents"
|
||
:disabled="leaveAgentLoading"
|
||
class="text-xs text-brand-600 hover:text-brand-700 disabled:opacity-50"
|
||
>
|
||
{{ leaveAgentLoading ? '加载中...' : '加载更多' }}
|
||
</button>
|
||
</div>
|
||
<div v-else class="py-4 text-center text-xs text-slate-400">没有更多数据了</div>
|
||
</template>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- OA 登录对话框 -->
|
||
<Teleport to="body">
|
||
<div v-if="showOALoginDialog" class="fixed inset-0 z-[9999] flex items-center justify-center">
|
||
<div class="absolute inset-0 bg-black/40" @click="cancelOALogin"></div>
|
||
<div class="relative w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl dark:bg-slate-800">
|
||
<h3 class="mb-4 text-center text-lg font-bold text-slate-800 dark:text-slate-100">登录OA系统</h3>
|
||
<div class="space-y-4">
|
||
<label class="block space-y-1.5">
|
||
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">工号</span>
|
||
<input
|
||
v-model="oaLoginEmployeeId"
|
||
type="text"
|
||
disabled
|
||
class="w-full rounded-xl border border-slate-200 bg-slate-100 px-3 py-2.5 text-sm text-slate-600 outline-none dark:border-slate-600 dark:bg-slate-700 dark:text-slate-300"
|
||
/>
|
||
</label>
|
||
<label class="block space-y-1.5">
|
||
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">密码</span>
|
||
<input
|
||
v-model="oaLoginPassword"
|
||
type="password"
|
||
placeholder="请输入OA登录密码"
|
||
class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-800 outline-none focus:border-brand-400 focus:ring-2 focus:ring-brand-100 dark:border-slate-600 dark:bg-slate-900 dark:text-slate-100 dark:focus:border-brand-500 dark:focus:ring-brand-500/20"
|
||
@keyup.enter="confirmOALogin"
|
||
/>
|
||
</label>
|
||
</div>
|
||
<div class="mt-6 flex items-center justify-end gap-3">
|
||
<button
|
||
@click="cancelOALogin"
|
||
class="rounded-xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-50 dark:border-slate-600 dark:text-slate-300 dark:hover:bg-slate-700"
|
||
>
|
||
取消
|
||
</button>
|
||
<button
|
||
@click="confirmOALogin"
|
||
class="rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-brand-700 dark:bg-brand-500 dark:hover:bg-brand-600"
|
||
>
|
||
确认登录
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</Teleport>
|
||
|
||
|
||
</template>
|
||
<style scoped>
|
||
: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>
|