123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610 |
- <template>
- <div class="border-gray-200 p-3 h-full flex flex-col" style="min-height: 750px; max-height: 750px;">
- <div class="text-sm font-medium mb-3 flex justify-between">
- <span style="color: #075985">DeepSeek大模型CRM数据分析</span>
- <span class="text-gray-500 text-right">开会做PPT利器!</span>
- </div>
-
- <!-- Chat messages container with fixed height and scrolling -->
- <div class="mb-3 border-gray-200 border rounded overflow-y-auto flex-grow" style="min-height: 0;">
- <div class="p-3 flex flex-col gap-3">
- <div v-for="(message, index) in messages" :key="index" class="flex" :class="{'justify-end': message.role === 'user', 'justify-start': message.role === 'assistant'}">
- <div v-if="message.role === 'assistant'" class="flex items-start gap-2">
- <el-avatar :size="24" class="bg-gray-200 flex items-center justify-center">
- <el-icon><ChatLineRound /></el-icon>
- </el-avatar>
- <div class="border-gray-200 border rounded p-2 text-sm max-w-[80%] bg-gray-50 relative">
- <div class="text-xs text-gray-500 mb-1" v-if="message.dataSource">
- [{{ message.dataSource }}{{ message.dataName ? '-' + message.dataName : '' }}]
- </div>
- <div class="markdown-body" v-html="renderMarkdown(message.content)"></div>
- <div v-if="message.loading" class="loading-dots">
- <span></span>
- <span></span>
- <span></span>
- </div>
- <el-button
- v-if="!message.loading && message.role === 'assistant' && index > 0 && '抱歉,请求处理失败,请稍后再试' != message.content && '无数据' != message.content"
- @click="exportToWord(message.content)"
- size="small"
- type="text"
- class="absolute -bottom-3 -right-3"
- :icon="Download"
- />
- </div>
- </div>
- <div v-if="message.role === 'user'" class="flex items-start gap-2 justify-end">
- <div class="border-gray-200 border rounded p-2 text-sm max-w-[80%] bg-blue-50">
- <div class="text-xs text-gray-500 mb-1" v-if="message.dataSource">
- [{{ message.dataSource }}{{ message.dataName ? '-' + message.dataName : '' }}]
- </div>
- <div class="markdown-body" v-html="renderMarkdown(message.content)"></div>
- </div>
- <el-avatar :size="24" class="bg-gray-200 flex items-center justify-center">
- <el-icon><User /></el-icon>
- </el-avatar>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Data source selection -->
- <div class="mb-3 flex gap-2">
- <div>
- <span class="text-sm mr-2">数据来源</span>
- <el-select v-model="dataSource" size="small" style="width: 120px">
- <el-option label="系统表" value="system" />
- <el-option label="自定义报表" value="custom" />
- <el-option label="本地上传" value="upload" />
- <el-option label="自由交流" value="free" />
- </el-select>
- </div>
-
- <div v-if="dataSource === 'system'">
- <el-select v-model="systemTable" size="small" style="width: 120px">
- <el-option label="线索" value="clue" />
- <el-option label="商机" value="business_opportunity" />
- <el-option label="客户" value="custom" />
- <el-option label="联系人" value="contacts" />
- <el-option label="合同" value="contract" />
- <el-option label="销售订单" value="sales_order" />
- <el-option label="产品" value="product" />
- </el-select>
- </div>
- <div v-if="dataSource === 'custom'">
- <el-select
- v-model="selectedReportId"
- size="small"
- style="width: 200px"
- placeholder="选择报表"
- @focus="loadCustomReports"
- >
- <el-option
- v-for="report in customReports"
- :key="report.relateFormId"
- :label="report.storeName"
- :value="report.relateFormId"
- />
- </el-select>
- </div>
-
- <div v-if="dataSource === 'upload'">
- <el-upload
- :show-file-list="false"
- :before-upload="beforeUpload"
- :http-request="handleUpload"
- accept=".xlsx,.xls"
- >
- <el-button size="small" type="primary">上传Excel</el-button> <span style="margin-left:5px;color:orange">{{ uploadedFilePath?'上传成功':'' }}</span>
- </el-upload>
- </div>
-
- <div v-if="dataSource === 'system'" class="ml-auto">
- <span class="text-sm mr-2">时间段</span>
- <el-date-picker
- v-model="dateRange"
- type="daterange"
- size="small"
- range-separator="/"
- start-placeholder="开始日期"
- end-placeholder="结束日期"
- format="YYYY-MM-DD"
- value-format="YYYY-MM-DD"
- />
- </div>
- </div>
-
- <!-- Input area -->
- <div class="flex gap-2 items-end mt-auto">
- <el-input
- v-model="inputMessage"
- type="textarea"
- :rows="2"
- placeholder="请进行数据分析,给一个总结报告,不超过300字"
- class="flex-1"
- resize="none"
- @keyup.enter="inputMessage.trim() && !loading ? sendMessage() : null"
- />
- <el-button
- type="primary"
- @click="sendMessage"
- :disabled="loading || !inputMessage.trim()"
- size="small"
- style="height: 53px; "
- >
- 发送
- </el-button>
- </div>
- </div>
- </template>
- <script lang="ts" setup>
- import { ref, reactive, nextTick, computed, onMounted } from 'vue';
- import { marked } from 'marked';
- import { ChatLineRound, User, Download } from '@element-plus/icons-vue';
- import { Document, Paragraph, TextRun, Packer } from 'docx';
- import {
- askAIQuestion,
- uploadFileApi,
- getLatestQuestionList,
- getCustomReports,
- type AIQuestionParams,
- type UploadFileResponse,
- type ChatContent,
- type LatestQuestionResponse,
- type AIQuestionResponse,
- type CustomReport
- } from '../api';
- import { ElMessage } from 'element-plus/es'
- import * as internal from 'stream';
- const renderMarkdown = (content: string): string => {
- // Configure marked with options
- marked.setOptions({
- breaks: true,
- gfm: true
- });
- try {
- return marked.parse(content) as string;
- } catch (error) {
- console.error('Markdown parsing error:', error);
- return content.replace(/</g, '<').replace(/>/g, '>'); // Escape HTML if parsing fails
- }
- };
- const exportToWord = async (content: string) => {
- // 先将markdown转换为HTML
- let htmlContent = '';
- try {
- const result = await marked.parse(content, {
- breaks: true,
- gfm: true
- });
- htmlContent = result;
- } catch (error) {
- console.error('Markdown parsing error:', error);
- htmlContent = content; // Fallback to raw content
- }
-
- // 创建一个临时的div来解析HTML
- const tempDiv = document.createElement('div');
- tempDiv.innerHTML = htmlContent;
-
- // 准备Word文档的段落
- const docChildren: Paragraph[] = [];
-
- // 处理每个HTML元素并转换为Word文档元素
- Array.from(tempDiv.childNodes).forEach((node) => {
- if (node.nodeType === Node.TEXT_NODE) {
- // 处理纯文本节点
- if (node.textContent && node.textContent.trim()) {
- docChildren.push(
- new Paragraph({
- children: [new TextRun({ text: node.textContent.trim() })],
- })
- );
- }
- } else if (node.nodeType === Node.ELEMENT_NODE) {
- const element = node as HTMLElement;
-
- // 根据HTML标签类型创建不同的Word元素
- if (element.tagName === 'H1' || element.tagName === 'H2' || element.tagName === 'H3') {
- docChildren.push(
- new Paragraph({
- heading: element.tagName === 'H1' ? 'Heading1' : element.tagName === 'H2' ? 'Heading2' : 'Heading3',
- children: [
- new TextRun({
- text: element.textContent || '',
- bold: true,
- size: element.tagName === 'H1' ? 36 : element.tagName === 'H2' ? 32 : 28,
- }),
- ],
- })
- );
- } else if (element.tagName === 'P') {
- docChildren.push(
- new Paragraph({
- children: [new TextRun({ text: element.textContent || '' })],
- spacing: { after: 200 },
- })
- );
- } else if (element.tagName === 'UL' || element.tagName === 'OL') {
- // 处理列表
- Array.from(element.children).forEach((li, index) => {
- docChildren.push(
- new Paragraph({
- children: [
- new TextRun({ text: element.tagName === 'UL' ? '• ' : `${index + 1}. ` }),
- new TextRun({ text: li.textContent || '' }),
- ],
- indent: { left: 720 }, // 缩进
- spacing: { after: 120 },
- })
- );
- });
- } else if (element.tagName === 'BLOCKQUOTE') {
- docChildren.push(
- new Paragraph({
- children: [new TextRun({ text: element.textContent || '', italics: true })],
- indent: { left: 720 },
- border: { left: { color: '#CCCCCC', size: 6, space: 15, style: 'single' } },
- spacing: { after: 200 },
- })
- );
- } else if (element.tagName === 'PRE') {
- // 代码块
- docChildren.push(
- new Paragraph({
- children: [new TextRun({
- text: element.textContent || '',
- font: { name: 'Courier New' }
- })],
- shading: {
- fill: '#F6F8FA',
- type: 'clear'
- },
- spacing: { after: 200 },
- })
- );
- } else {
- // 其他元素默认处理
- docChildren.push(
- new Paragraph({
- children: [new TextRun({ text: element.textContent || '' })],
- })
- );
- }
- }
- });
-
- // 创建Word文档
- const doc = new Document({
- sections: [{
- properties: {},
- children: docChildren,
- }],
- });
- const blob = await Packer.toBlob(doc);
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = 'AI分析报告.docx';
- a.click();
- URL.revokeObjectURL(url);
- };
- type DataSourceType = 'system' | 'custom' | 'upload' | 'free';
- type SystemTableType = 'clue' | 'business_opportunity' | 'custom' | 'contacts' | 'contract' | 'sales_order' | 'product';
- interface ChatMessage {
- role: 'user' | 'assistant';
- content: string;
- loading?: boolean;
- dataSource?: string;
- dataName?: string;
- }
- // Data source selection
- const dataSource = ref<DataSourceType>('system');
- const systemTable = ref<SystemTableType>('clue');
- const customReports = ref<CustomReport[]>([]);
- const selectedReportId = ref<string>('');
- const formatDate = (date: Date) => {
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}`;
- };
- const getFirstDayOfMonth = () => {
- const date = new Date();
- return new Date(date.getFullYear(), date.getMonth(), 1);
- };
- const uploadFile = ref<File | null>(null);
- const uploadedFilePath = ref<string>('');
- const beforeUpload = (file: File) => {
- uploadFile.value = file;
- uploadedFilePath.value = '';
- return true;
- };
- const handleUpload = async (options: any) => {
- try {
- const result = await uploadFileApi(options.file);
- if (result.code === 'ok') {
- uploadedFilePath.value = result.data;
- // Show upload success message
- ElMessage.success("上传成功,请输入问题并发送")
- } else {
- console.error('Upload failed:', result);
- }
- } catch (error) {
- console.error('Upload error:', error);
- }
- };
- const dateRange = ref([formatDate(getFirstDayOfMonth()), formatDate(new Date())]);
- // Chat functionality
- const inputMessage = ref('请进行数据分析,给一个总结报告,不超过300字');
- const loading = ref(false);
- const messages = reactive<ChatMessage[]>([]);
- const questionId = ref<number | null>(null);
- const loadCustomReports = async () => {
- if (customReports.value.length === 0) {
- try {
- const result = await getCustomReports();
- if (result.code === 'ok') {
- customReports.value = result.data;
- }
- } catch (error) {
- console.error('Failed to load custom reports:', error);
- ElMessage.error('加载自定义报表失败');
- }
- }
- };
- const isSameDay = (dateString: string, compareDate: Date) => {
- // Parse yyyy-MM-dd hh:mm:ss format
- const [datePart] = dateString.split(' ');
- const [year, month, day] = datePart.split('-').map(Number);
-
- return year === compareDate.getFullYear() &&
- month - 1 === compareDate.getMonth() && // Months are 0-indexed in JS
- day === compareDate.getDate();
- };
- onMounted(async () => {
- try {
- const result = await getLatestQuestionList();
- if (result.code === 'ok' && result.data.contents) {
- result.data.contents.forEach(content => {
- messages.push({
- role: content.type === 0 ? 'assistant' : 'user',
- content: content.content
- });
- // Check if createTime is today and set questionId
- if (content.createTime && content.questionId) {
- if (isSameDay(content.createTime, new Date())) {
- questionId.value = content.questionId;
- }
- }
- });
- } else {
- // Default message if no history
- messages.push({ role: 'assistant', content: '你好,需要分析查询哪些数据,请交给我' });
- }
- } catch (error) {
- console.error('Failed to load chat history:', error);
- messages.push({ role: 'assistant', content: '你好,需要分析查询哪些数据,请交给我' });
- }
- // 触发滚动到底部
- nextTick(() => {
- const container = document.querySelector('.overflow-y-auto');
- if (container) {
- container.scrollTop = container.scrollHeight;
- }
- });
- });
- const sendMessage = async () => {
- if (!inputMessage.value.trim() || loading.value) return;
- type DataSourceType = 'system' | 'custom' | 'upload' | 'free';
- const dataSourceNameMap: Record<DataSourceType, string> = {
- 'system': '系统表',
- 'custom': '自定义报表',
- 'upload': '本地上传',
- 'free': '自由交流'
- };
- const dataSourceMap: Record<DataSourceType, number> = {
- 'system': 1,
- 'custom': 2,
- 'upload': 3,
- 'free': 4
- };
- const sourceName = dataSourceNameMap[dataSource.value]
- const dataName = dataSource.value === 'system' ?
- systemTable.value === 'clue' ? '线索' :
- systemTable.value === 'business_opportunity' ? '商机' :
- systemTable.value === 'custom' ? '客户' :
- systemTable.value === 'contacts' ? '联系人' :
- systemTable.value === 'contract' ? '合同' :
- systemTable.value === 'sales_order' ? '销售订单' : '产品' :
- dataSource.value === 'custom' ?
- customReports.value.find(r => r.relateFormId === selectedReportId.value)?.storeName || '' :
- dataSource.value === 'upload' ?
- uploadFile.value?.name || '' : ''
- const finalContent = '['+sourceName+(dataName?('-'+dataName):'')+']'+'<br>' + inputMessage.value;
- if (!dataName) {
- if (dataSource.value == 'custom') {
- //提示:请选择报表
- ElMessage.error({
- message: "请选择报表",
- type: "error",
- duration: 2000,
- })
- return
- } else if (dataSource.value == 'upload') {
- ElMessage.error({
- message: "请上传数据文件(仅支持excel格式)",
- type: "error",
- duration: 2000,
- })
- return
- }
- }
- loading.value = true;
- const userMessage: ChatMessage = { role: 'user', content: finalContent };
- messages.push(userMessage);
- const thinkingIndex = messages.length;
- messages.push({ role: 'assistant', content: 'AI正在思考', loading: true });
-
- try {
- console.log('发送日期=='+dateRange);
- console.log(dateRange.value[0]);
- const params: AIQuestionParams & { questionId?: number } = {
- questionDataSource: dataSourceMap[dataSource.value],
- sourceContent: dataSource.value === 'system' ? systemTable.value :
- dataSource.value === 'custom' ? selectedReportId.value : '',
- content: finalContent,
- startDate: dateRange.value[0],
- endDate: dateRange.value[1],
- url: dataSource.value === 'upload' ? uploadedFilePath.value : ''
- };
- // Only include questionId if we have one from today's conversation
- if (questionId.value) {
- params.questionId = questionId.value;
- }
- // reset message input
- inputMessage.value = '';
- //上方聊天记录页面自动滚动到最下面
- nextTick(() => {
- const container = document.querySelector('.overflow-y-auto');
- if (container) {
- container.scrollTop = container.scrollHeight;
- }
- });
- const result = await askAIQuestion(params);
- messages[thinkingIndex] = {
- role: 'assistant',
- content: result.data.queryRes || '根据您的请求,我已分析了相关数据。分析结果显示...',
- loading: false
- };
- questionId.value = result.data.questionId;
- } catch (error) {
- console.error('API error:', error);
- messages[thinkingIndex] = {
- role: 'assistant',
- content: '抱歉,请求处理失败,请稍后再试',
- loading: false
- };
- }
- loading.value = false;
- // 触发滚动到底部
- nextTick(() => {
- const container = document.querySelector('.overflow-y-auto');
- if (container) {
- container.scrollTop = container.scrollHeight;
- }
- });
- };
- </script>
- <style scoped>
- :deep(.el-textarea__inner) {
- resize: none;
- }
- .markdown-body {
- line-height: 1.5;
- word-wrap: break-word;
- }
- .markdown-body :deep(h1),
- .markdown-body :deep(h2),
- .markdown-body :deep(h3),
- .markdown-body :deep(h4),
- .markdown-body :deep(h5),
- .markdown-body :deep(h6) {
- margin-top: 0.5em;
- margin-bottom: 0.5em;
- font-weight: bold;
- }
- .markdown-body :deep(p) {
- margin-bottom: 1em;
- }
- .markdown-body :deep(ul),
- .markdown-body :deep(ol) {
- padding-left: 2em;
- margin-bottom: 1em;
- }
- .markdown-body :deep(li) {
- margin-bottom: 0.5em;
- }
- .markdown-body :deep(code) {
- background-color: rgba(175, 184, 193, 0.2);
- border-radius: 3px;
- padding: 0.2em 0.4em;
- font-family: monospace;
- }
- .markdown-body :deep(pre) {
- background-color: #f6f8fa;
- border-radius: 3px;
- padding: 1em;
- overflow: auto;
- margin-bottom: 1em;
- }
- .markdown-body :deep(blockquote) {
- border-left: 4px solid #dfe2e5;
- color: #6a737d;
- padding-left: 1em;
- margin-left: 0;
- margin-bottom: 1em;
- }
- .loading-dots {
- display: inline-flex;
- align-items: center;
- gap: 2px;
- }
- .loading-dots span {
- display: inline-block;
- width: 6px;
- height: 6px;
- border-radius: 50%;
- background-color: currentColor;
- animation: bounce 1.4s infinite ease-in-out both;
- }
- .loading-dots span:nth-child(1) {
- animation-delay: -0.32s;
- }
- .loading-dots span:nth-child(2) {
- animation-delay: -0.16s;
- }
- @keyframes bounce {
- 0%, 80%, 100% {
- transform: scale(0);
- } 40% {
- transform: scale(1.0);
- }
- }
- </style>
|