ZdyRagList.vue
18.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
<template>
<div class="chat-container">
<!-- 主内容区域 -->
<div class="main-content">
<!-- 聊天消息区域 -->
<div class="chat-messages" ref="messagesContainer">
<div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
<div class="message-content">
<div class="message-text" v-html="message.text"></div>
<div v-if="message.type === 'assistant' && message.similarity" class="message-meta">
相似度: {{ (message.similarity * 100).toFixed(2) }}%
<div v-if="message.fileBase64">
相关资料:
<a @click="showPreview(message)">{{message.fileName}}</a>
</div>
</div>
</div>
</div>
<div v-if="loading" class="message assistant">
<div class="message-content">
<div class="message-text">思考中...</div>
</div>
</div>
</div>
<!-- 文件预览区域 -->
<div v-if="previewContent" class="file-preview">
<div class="preview-header">
<span class="preview-title">文件预览</span>
<div class="preview-actions">
<a-button type="link" @click="downloadFile" class="download-btn">
<DownloadOutlined />
<span class="btn-text">下载</span>
</a-button>
<a-button
type="text"
@click="closePreview"
class="close-btn"
title="关闭预览"
>
<CloseOutlined />
</a-button>
</div>
</div>
<div class="preview-content">
<div v-if="previewType === 'txt' || previewType === 'md'" class="text-preview">
<pre>{{ previewContent }}</pre>
</div>
<div v-else-if="previewType === 'pdf'" class="pdf-preview" ref="pdfPreview"></div>
<div v-else-if="previewType === 'docx'" class="docx-preview" ref="docxPreview"></div>
<div v-else-if="previewType === 'doc'" class="unsupported-preview">
不支持预览 DOC 格式的文件,请下载后使用本地软件查看
</div>
<div v-else class="unsupported-preview">
不支持预览 {{ previewType.toUpperCase() }} 格式的文件
</div>
</div>
</div>
</div>
<div>
<a-button
style="margin-left: 1%;
background-color: white;
color: #666;
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 16px;
cursor: pointer;
font-size: 14px;
padding: 2px 10px;
width: max-content;
margin-right: 6px;
white-space: nowrap;
transition: all 300ms ease;
"
v-for="(btn, index) in buttonList"
:key="index"
type="primary"
class="action-button"
@click="sendButtonMessage(btn.buttonValues)"
>
{{ btn.buttonName }}
</a-button>
</div>
<!-- 输入区域 -->
<div class="chat-input">
<a-input
v-model:value="inputMessage"
placeholder="请输入您的问题..."
@pressEnter="sendMessage"
:disabled="loading"
/>
<a-button
type="primary"
@click="sendMessage"
:loading="loading"
:disabled="!inputMessage.trim()"
>
发送
</a-button>
</div>
</div>
</template>
<script lang="ts" name="zdy-rag-chat" setup>
import { ref, reactive, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { sendMessage as apiSendMessage , getButtonList} from './ZdyRag.api';
import { useMessage } from '/@/hooks/web/useMessage';
import { CloseOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import * as pdfjsLib from 'pdfjs-dist';
import * as mammoth from 'mammoth';
import { renderAsync } from 'docx-preview';
// 设置PDF.js worker路径
pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.min.js';
const buttonList = reactive<any[]>([]);
onMounted(async () => {
try {
const res = await getButtonList();
if (res && Array.isArray(res)) {
buttonList.push(...res);
} else {
// createMessage.warning('未获取到按钮列表数据');
}
} catch (error) {
console.error('获取按钮列表失败:', error);
// createMessage.error('获取按钮列表失败');
}
});
// 聊天消息数据
const messages = reactive([
{
type: 'assistant',
text: '您好!我是智能助手,请问有什么可以帮您?',
similarity: null,
fileBase64: null,
fileName: null
}
]);
const inputMessage = ref('');
const loading = ref(false);
const messagesContainer = ref<HTMLElement>();
const previewContent = ref('');
const previewType = ref('');
const previewUrl = ref('');
const currentFile = ref<any>(null);
const pdfPreview = ref<HTMLElement>();
const docxPreview = ref<HTMLElement>();
// 发送消息
const sendMessage = async () => {
const text = inputMessage.value.trim();
if (!text || loading.value) return;
// 添加用户消息
messages.push({
type: 'user',
text: text,
similarity: null,
fileBase64: null,
fileName: null
});
inputMessage.value = '';
loading.value = true;
closePreview();
try {
// 调用API发送消息
const res = await apiSendMessage({ questionText: text });
console.log('API响应:', res);
if (res) {
const newMessage = {
type: 'assistant',
text: formatAnswer(res.answer),
similarity: res.similarity || null,
fileBase64: res.fileBase64 || null,
fileName: res.fileName || ''
};
messages.push(newMessage);
} else {
// createMessage.error('获取回答失败: 返回数据为空');
}
} catch (error: any) {
console.error('发送消息失败:', error);
// createMessage.error('发送消息失败: ' + error.message);
} finally {
loading.value = false;
scrollToBottom();
}
};
const sendButtonMessage = async (buttonValue: string) => {
if (loading.value) return;
// 添加用户消息
messages.push({
type: 'user',
text: buttonValue,
similarity: null,
fileBase64: null,
fileName: null
});
loading.value = true;
closePreview();
try {
// 调用API发送按钮值
const res = await apiSendMessage({ questionText: buttonValue });
if (res) {
const newMessage = {
type: 'assistant',
text: formatAnswer(res.answer),
similarity: res.similarity || null,
fileBase64: res.fileBase64 || null,
fileName: res.fileName || ''
};
messages.push(newMessage);
} else {
console.error('获取回答失败: 返回数据为空');
}
} catch (error: any) {
console.error('发送按钮消息失败:', error);
// createMessage.error('发送按钮消息失败: ' + error.message);
} finally {
loading.value = false;
scrollToBottom();
}
};
// 增强版showPreview函数
const showPreview = async (message: any) => {
try {
// 验证基本数据
if (!message?.fileBase64 || !message?.fileName) {
throw new Error('文件数据不完整');
}
// 关闭之前的预览
closePreview();
// 设置当前文件
currentFile.value = message;
const fileExt = getFileExtension(message.fileName);
previewType.value = fileExt;
// 根据文件类型处理
if (['txt', 'md'].includes(fileExt)) {
// 文本文件处理
previewContent.value = decodeBase64Content(message.fileBase64);
} else if (fileExt === 'pdf') {
// PDF文件处理
previewContent.value = 'pdf-preview';
await nextTick(); // 等待DOM更新
await renderPdf(message.fileBase64);
} else if (fileExt === 'docx') {
// DOCX文件处理
previewContent.value = 'docx-preview';
await nextTick(); // 等待DOM更新
await renderDocx(message.fileBase64);
} else if (fileExt === 'doc') {
// 不支持DOC格式预览
previewContent.value = 'unsupported';
throw new Error('不支持DOC格式预览,请下载后查看');
} else {
throw new Error(`不支持的文件类型: ${fileExt}`);
}
} catch (error) {
console.error('预览失败:', error);
previewContent.value = 'error';
// createMessage.error(`预览失败: ${error.message}`);
}
};
// 渲染PDF
const renderPdf = async (base64: string) => {
if (!pdfPreview.value) return;
// 清空容器
pdfPreview.value.innerHTML = '';
// 将Base64转换为Uint8Array
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
// 加载PDF文档
const pdfDoc = await pdfjsLib.getDocument({ data: bytes }).promise;
// 创建Canvas容器
const container = document.createElement('div');
container.className = 'pdf-pages';
pdfPreview.value.appendChild(container);
// 渲染每一页
for (let i = 1; i <= pdfDoc.numPages; i++) {
const page = await pdfDoc.getPage(i);
const viewport = page.getViewport({ scale: 1.5 });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: context,
viewport: viewport
};
await page.render(renderContext).promise;
const pageDiv = document.createElement('div');
pageDiv.className = 'pdf-page';
pageDiv.appendChild(canvas);
container.appendChild(pageDiv);
}
};
// 渲染DOCX
const renderDocx = async (base64: string) => {
if (!docxPreview.value) return;
// 清空容器
docxPreview.value.innerHTML = '';
// 将Base64转换为Blob
const byteString = atob(base64);
const byteNumbers = new Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {
byteNumbers[i] = byteString.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
});
// 使用docx-preview渲染
await renderAsync(blob, docxPreview.value);
};
// 获取文件扩展名
const getFileExtension = (filename: string): string => {
const match = filename.match(/\.([0-9a-z]+)(?:[\?#]|$)/i);
return match ? match[1].toLowerCase() : 'unknown';
};
// Base64解码
const decodeBase64Content = (base64: string): string => {
try {
return decodeURIComponent(escape(atob(base64)));
} catch {
return atob(base64);
}
};
// 下载文件
const downloadFile = () => {
if (!currentFile.value || !currentFile.value.fileBase64 || !currentFile.value.fileName) {
// createMessage.warning('无法下载文件');
return;
}
try {
const byteCharacters = atob(currentFile.value.fileBase64);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: 'application/octet-stream' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = currentFile.value.fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// createMessage.success('文件下载开始');
} catch (error: any) {
console.error('文件下载失败:', error);
// createMessage.error('文件下载失败: ' + error.message);
}
};
// 关闭预览
const closePreview = () => {
previewContent.value = '';
previewType.value = '';
if (previewUrl.value) {
URL.revokeObjectURL(previewUrl.value);
previewUrl.value = '';
}
currentFile.value = null;
// 清空预览容器
if (pdfPreview.value) pdfPreview.value.innerHTML = '';
if (docxPreview.value) docxPreview.value.innerHTML = '';
};
// 格式化回答内容
const formatAnswer = (answer: string) => {
// 替换[n]为换行符,然后将换行符转换为<br>标签
return answer.replace(/\[n\]/g, '\n').replace(/\n/g, '<br>');
};
// 滚动到底部
const scrollToBottom = () => {
nextTick(() => {
if (messagesContainer.value) {
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
}
});
};
// 组件卸载时清理资源
onBeforeUnmount(() => {
closePreview();
});
</script>
<style lang="less" scoped>
/* 样式保持不变 */
.chat-container {
display: flex;
flex-direction: column;
height: calc(100vh - 120px);
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
border-radius: 8px;
}
.main-content {
display: flex;
flex: 1;
gap: 20px;
margin-bottom: 20px;
overflow: hidden;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 15px;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
min-height: 300px;
}
//.file-preview {
// width: 55%;
// min-width: 300px;
// display: flex;
// flex-direction: column;
// background-color: white;
// border-radius: 8px;
// box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
// overflow: hidden;
//
// .preview-header {
// display: flex;
// justify-content: space-between;
// align-items: center;
// padding: 10px 15px;
// background-color: #f0f0f0;
// border-bottom: 1px solid #e8e8e8;
//
// .preview-actions {
// display: flex;
// align-items: center;
// gap: 8px;
// }
// }
//
// .preview-content {
// flex: 1;
// overflow: auto;
// padding: 10px;
//
// .text-preview {
// padding: 15px;
// white-space: pre-wrap;
// font-family: monospace;
// line-height: 1.6;
// }
//
// .pdf-preview {
// height: 100%;
// overflow-y: auto;
//
// .pdf-pages {
// display: flex;
// flex-direction: column;
// gap: 20px;
// padding: 10px;
//
// .pdf-page {
// border: 1px solid #e8e8e8;
// box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
// }
// }
// }
//
// .docx-preview {
// height: 100%;
// overflow-y: auto;
// padding: 20px;
// background-color: #fff;
// }
//
// .unsupported-preview {
// height: 100%;
// padding: 20px;
// display: flex;
// align-items: center;
// justify-content: center;
// color: #ff4d4f;
// font-weight: 500;
// }
// }
//}
.file-preview {
width: 55%;
min-width: 300px;
display: flex;
flex-direction: column;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
overflow: hidden;
.preview-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background-color: #f0f0f0;
border-bottom: 1px solid #e8e8e8;
font-weight: 500;
font-size: 14px;
.preview-actions {
display: flex;
align-items: center;
gap: 10px;
.ant-btn {
padding: 0;
height: auto;
color: #666;
display: flex;
align-items: center;
transition: color 0.3s;
&:hover {
color: #1890ff;
background: transparent;
}
.anticon {
font-size: 16px;
}
}
.ant-btn-link {
padding: 0 8px;
}
}
}
.preview-content {
flex: 1;
overflow: auto;
padding: 10px;
.text-preview {
padding: 15px;
white-space: pre-wrap;
font-family: monospace;
line-height: 1.6;
background-color: #fafafa;
border-radius: 4px;
}
.pdf-preview {
height: 100%;
overflow-y: auto;
.pdf-pages {
display: flex;
flex-direction: column;
gap: 20px;
padding: 10px;
.pdf-page {
border: 1px solid #e8e8e8;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
background-color: white;
}
}
}
.docx-preview {
height: 100%;
overflow-y: auto;
padding: 20px;
background-color: #fff;
border: 1px solid #f0f0f0;
border-radius: 4px;
}
.unsupported-preview {
height: 100%;
padding: 20px;
display: flex;
align-items: center;
justify-content: center;
color: #ff4d4f;
font-weight: 500;
background-color: #fff2f0;
border-radius: 4px;
text-align: center;
}
}
}
/* 响应式设计 */
@media (max-width: 768px) {
.file-preview {
width: 100%;
min-width: auto;
max-height: 300px;
.preview-header {
padding: 8px 12px;
.preview-actions {
gap: 6px;
.ant-btn-link {
padding: 0 4px;
}
}
}
.preview-content {
padding: 8px;
.text-preview,
.docx-preview {
padding: 10px;
}
}
}
}
.message {
margin-bottom: 15px;
display: flex;
&.user {
justify-content: flex-end;
.message-content {
background-color: #1890ff;
color: white;
border-radius: 18px 18px 0 18px;
}
}
&.assistant {
justify-content: flex-start;
.message-content {
background-color: #f0f0f0;
color: #333;
border-radius: 18px 18px 18px 0;
}
}
}
.message-content {
max-width: 80%;
padding: 12px 16px;
word-wrap: break-word;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.message-meta {
font-size: 12px;
color: #666;
margin-top: 8px;
text-align: right;
a {
margin-left: 10px;
color: #1890ff;
cursor: pointer;
&:hover {
text-decoration: underline;
}
}
}
.chat-input {
display: flex;
gap: 12px;
padding: 10px 0;
:deep(.ant-input) {
flex: 1;
border-radius: 20px;
padding: 12px 18px;
border: 1px solid #d9d9d9;
transition: all 0.3s;
&:hover {
border-color: #40a9ff;
}
&:focus {
box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}
}
.ant-btn {
border-radius: 20px;
padding: 0 24px;
height: 40px;
font-weight: 500;
}
}
/* 响应式设计 */
@media (max-width: 768px) {
.main-content {
flex-direction: column;
}
.file-preview {
width: 100%;
min-width: auto;
max-height: 300px;
}
.message-content {
max-width: 90%;
}
}
</style>