From 2db98acd7d2c36fe23756051c2c858ab33244572 Mon Sep 17 00:00:00 2001
From: wujingjing <gersonwu@qq.com>
Date: 星期二, 31 十二月 2024 10:25:35 +0800
Subject: [PATCH] 删除无关代码——关联查询; 整理代码

---
 src/components/chat/Chat.vue |  410 +++++++++++++++++++++++++++++++---------------------------
 1 files changed, 220 insertions(+), 190 deletions(-)

diff --git a/src/components/chat/Chat.vue b/src/components/chat/Chat.vue
index 4fc9ca3..4cad518 100644
--- a/src/components/chat/Chat.vue
+++ b/src/components/chat/Chat.vue
@@ -3,7 +3,6 @@
 		:loading="chatListLoading"
 		:more-is-loading="moreIsLoading"
 		:is-share-page="isSharePage"
-		:is-share-check="isShareCheck"
 		:chat-width="chatWidth"
 		ref="containerRef"
 	>
@@ -35,31 +34,32 @@
 									<div class="rounded-[6px] p-4 leading-relaxed bg-white">
 										<!-- #region ====================== 娑堟伅鍐呭 ======================-->
 										<!-- <template v-if="item.content?.values"> -->
-											<!-- #region ====================== 鎶ラ敊淇℃伅 ======================-->
-											<div v-if="item.content?.errCode === ErrorCode.Message" class="flex-column w-full">
-												<p class="text-red-500">
-													{{ item.content.errMsg }}
-												</p>
-												<div class="mt-3 flex" v-if="showFixQuestion(item)">
-													<div class="text-gray-600 flex-0 mb-auto py-3">
-														{{ '鐚滀綘鎯抽棶锛�' }}
-													</div>
-													<div class="flex-auto space-x-2 space-y-1 inline-flex flex-wrap items-center">
-														<div
-															v-for="fixItem in item.content.origin?.sample_question"
-															:key="fixItem"
-															class="bg-gray-200 p-3 hover:bg-[#c5e0ff] hover:text-[#1c86ff] cursor-pointer rounded-lg first-of-type:ml-2 first-of-type:mt-1"
-															@click="fixQuestionClick(fixItem, item.content.origin)"
-														>
-															{{ fixItem }}
-														</div>
+										<!-- #region ====================== 鎶ラ敊淇℃伅 ======================-->
+										<div v-if="item.content?.errCode === ErrorCode.Message" class="flex-column w-full">
+											<p class="text-danger">
+												{{ item.content.errMsg }}
+											</p>
+											<div class="mt-3 flex" v-if="showFixQuestion(item)">
+												<div class="text-gray-600 flex-0 mb-auto py-3">
+													{{ '鐚滀綘鎯抽棶锛�' }}
+												</div>
+												<div class="flex-auto space-x-2 space-y-1 inline-flex flex-wrap items-center">
+													<div
+														v-for="fixItem in item.content.origin?.sample_question"
+														:key="fixItem"
+														class="bg-gray-200 p-3 hover:bg-[#c5e0ff] hover:text-[#1c86ff] cursor-pointer rounded-lg first-of-type:ml-2 first-of-type:mt-1"
+														@click="fixQuestionClick(fixItem, item.content.origin)"
+													>
+														{{ fixItem }}
 													</div>
 												</div>
 											</div>
-											<!-- #endregion -->
-											<!-- #region ====================== 鍥炵瓟缁勪欢 ======================-->
-											<template v-else>
-												<template v-if="item.content.type === AnswerType.Report">
+										</div>
+										<!-- #endregion -->
+										<!-- #region ====================== 鍥炵瓟缁勪欢 ======================-->
+										<template v-else>
+											<template v-if="item.content.type === AnswerType.Report">
+												<template v-if="item?.stepGroup?.length > 0">
 													<div v-for="(num, index) in item?.stepGroup?.length" :key="index">
 														<!-- #region ====================== 鎰忓浘鍒嗘瀽 ======================-->
 														<div class="flex flex-col" v-if="item?.stepGroup?.[index]?.value?.length > 0">
@@ -174,33 +174,19 @@
 														/>
 													</div>
 												</template>
-												<component
-													v-else
-													:historyId="item.historyId"
-													:conclusion="item.conclusion"
-													:is="answerTypeMapCom[item.content.type]"
-													:data="item.content.values"
-													:originData="item"
-													:isTalking="isTalking && msgIndex === computedMessageList.length - 1"
-												/>
-												<div
-													v-if="item.role === RoleEnum.assistant && item.content.origin?.ext_call_list"
-													class="flex font-bold items-center mt-6"
-												>
-													<div class="flex-0 mb-auto -mr-4">鍏宠仈鍔熻兘锛�</div>
-													<div class="space-x-5 flex flex-wrap">
-														<div
-															v-for="callItem in item.content.origin?.ext_call_list"
-															:key="callItem.call_ext_id"
-															@click="relativeQueryClick(callItem)"
-															class="cursor-pointer hover:underline first-of-type:ml-5"
-														>
-															{{ callItem.question }}
-														</div>
-													</div>
-												</div>
+												<p v-else class="text-info">鏆傛棤鍐呭锛岃閲嶈瘯</p>
 											</template>
-											<!-- #endregion -->
+											<component
+												v-else
+												:historyId="item.historyId"
+												:conclusion="item.conclusion"
+												:is="answerTypeMapCom[item.content.type]"
+												:data="item.content.values"
+												:originData="item"
+												:isTalking="isTalking && msgIndex === computedMessageList.length - 1"
+											/>
+										</template>
+										<!-- #endregion -->
 										<!-- </template> -->
 
 										<!-- #endregion -->
@@ -343,8 +329,7 @@
 import { loadAmisSource } from '../amis/load';
 import FeedbackPanel from './components/FeedbackPanel.vue';
 import { useAssistantContentOpt } from './hooks/useAssistantContentOpt';
-import { convertProcessItem, useScrollLoad } from './hooks/useScrollLoad';
-import { useScrollToBottom } from './hooks/useScrollToBottom';
+import { convertProcessItem, convertProcessToStep, formatShowTimeYear, useScrollLoad } from './hooks/useScrollLoad';
 import type { ChatContent } from './model/types';
 import {
 	AnswerState,
@@ -356,7 +341,7 @@
 	stepEnumMap,
 	type ChatMessage,
 } from './model/types';
-import { extCallQuery, questionStreamByPost } from '/@/api/ai/chat';
+import { extCallQuery, getShareChatJsonByPost, questionStreamByPost } from '/@/api/ai/chat';
 import PlayBar from '/@/components/chat/components/playBar/PlayBar.vue';
 import CustomDrawer from '/@/components/drawer/CustomDrawer.vue';
 import { Logger } from '/@/model/logger/Logger';
@@ -373,8 +358,6 @@
 	activeLLMId,
 	activeRoomId,
 	activeSampleId,
-	activeSectionAId,
-	getRoomConfig,
 	isSharePage,
 	roomConfig,
 } from '/@/stores/chatRoom';
@@ -382,7 +365,7 @@
 import { ErrorCode } from '/@/utils/request';
 import { useCompRef } from '/@/utils/types';
 import { toMyFixed } from '/@/utils/util';
-const containerRef = ref();
+const containerRef = useCompRef(ChatContainer);
 const chatListDom = computed(() => containerRef.value?.chatListDom);
 const chatWidth = '75%';
 const voicePageIsShow = ref(false);
@@ -421,7 +404,9 @@
 		type: AnswerType.Text,
 		values: '瑙f瀽澶辫触锛�',
 	};
-
+	if (res.type) {
+		res.answer_type = res.type;
+	}
 	const curExtraContent = parseExtraContent(res);
 
 	switch (res.answer_type) {
@@ -437,6 +422,12 @@
 				values: res.values ?? res.answer,
 			};
 			break;
+		case AnswerType.Script:
+			content = {
+				type: AnswerType.Script,
+				values: res,
+			};
+			break;
 
 		case AnswerType.Knowledge:
 			content = {
@@ -449,7 +440,7 @@
 			content = {
 				type: AnswerType.Report,
 				values: (res?.reports ?? []).map((item) => ({
-					content: parseContent(item, reportIsShow, { origin: item }),
+					content: parseContent(item, reportIsShow, { origin: item, conclusion: item.conclusion ?? [] }),
 				})),
 			};
 			break;
@@ -511,10 +502,8 @@
 
 //#endregion
 
-const DEFAULT_SECTION_A_ID = 'knowledge_base';
 let questionRes = null;
 let position = null;
-let finalCalcSectionAId = null;
 
 let lastAxiosSource: CancelTokenSource = null;
 const questionAi = async (text) => {
@@ -526,18 +515,6 @@
 			prev_question: preQuestion.value,
 		};
 	}
-	let currentSectionAId = '';
-	if (activeSectionAId.value) {
-		currentSectionAId = activeSectionAId.value;
-		activeSectionAId.value = '';
-	} else {
-		const lastSectionAItem = findLast(
-			computedMessageList.value as any,
-			(item) => item.role === RoleEnum.assistant && !!item.sectionAId
-		);
-		currentSectionAId = lastSectionAItem?.sectionAId ?? DEFAULT_SECTION_A_ID;
-	}
-	finalCalcSectionAId = currentSectionAId;
 
 	const params = {
 		question: text,
@@ -564,29 +541,37 @@
 	resetStep();
 	let lastTimestamp = new Date().getTime();
 	questionRes = {};
-
+	let lastIsResult = false;
 	const resultP = new Promise((resolve, reject) => {
 		const currentSource = axios.CancelToken.source();
 		lastAxiosSource = currentSource;
+
+		const getResReport = () => {
+			const resReport = {
+				answer_type: AnswerType.Report,
+				reports: [],
+			};
+			return resReport;
+		};
+		const checkReportEmpty = () => {
+			const isEmpty = !questionRes?.reports || questionRes?.reports?.length === 0;
+
+			return isEmpty;
+		};
 		questionStreamByPost(
 			params,
 			(chunkRes) => {
 				Logger.info('chunk response锛歕n\n' + JSON.stringify(chunkRes));
+
 				if (chunkRes.mode === 'result') {
+					lastIsResult = true;
 					const res = chunkRes.value;
 
-					if (!questionRes?.reports || questionRes?.reports?.length === 0) {
-						const resReport = {
-							answer_type: AnswerType.Report,
-							reports: [res],
-						};
+					if (checkReportEmpty()) {
+						const resReport = getResReport();
+						resReport.reports.push(res);
 						questionRes = resReport;
 						resolve(resReport);
-						// 寮�濮嬪鍔犳柊鐨� stepGroup
-						computedMessageList.value.at(-1).stepGroup.push({
-							value: [],
-							isShow: true,
-						});
 					} else {
 						const lastMsg = computedMessageList.value.at(-1);
 
@@ -604,9 +589,14 @@
 				if (chunkRes.mode === 'summary') {
 					const lastMsg = computedMessageList.value.at(-1);
 					const extraContent = parseExtraContent(chunkRes.value);
-
+					const isReportEmpty = checkReportEmpty();
+					// 娌℃湁缁忚繃 result 鎶ュ憡杩樻病鍒濆鍖�
+					if (isReportEmpty) {
+						const resReport = getResReport();
+						questionRes = resReport;
+					}
 					// 姝ゅ璇濆凡缁忓姞鍏ュ埌瀵硅瘽鍒楄〃
-					if (lastMsg.content && extraContent) {
+					if (lastMsg.content?.values && extraContent) {
 						for (const key in extraContent) {
 							if (Object.prototype.hasOwnProperty.call(extraContent, key)) {
 								const value = extraContent[key];
@@ -615,6 +605,11 @@
 								}
 							}
 						}
+
+						lastMsg.historyId = chunkRes.value.history_id;
+						const userMsg = computedMessageList.value.at(-2);
+						userMsg.historyId = chunkRes.value.history_id;
+						userMsg.content.values = chunkRes.value.question;
 					}
 
 					if (Object.keys(questionRes).length === 0) {
@@ -622,11 +617,15 @@
 					}
 
 					// 姝ゅ璇濊繕鏈姞鍏ュ埌瀵硅瘽鍒楄〃
-					if (!lastMsg.content && questionRes) {
+					if (!lastMsg.content?.values && questionRes) {
 						questionRes = {
 							...questionRes,
 							...chunkRes.value,
 						};
+					}
+
+					if (isReportEmpty) {
+						resolve(questionRes);
 					}
 					// computedMessageList.value[computedMessageList.value.length - 1] = finalMsg;
 					scrollToBottom();
@@ -635,8 +634,11 @@
 				}
 
 				if (chunkRes.mode === 'conclusion') {
-					computedMessageList.value.at(-1).conclusion = chunkRes.value;
-					chunkRes.value = '鍒嗘瀽缁撴潫';
+					const lastReport = computedMessageList.value.at(-1)?.content?.values?.at(-1);
+					if (lastReport) {
+						lastReport.conclusion = chunkRes.value;
+						chunkRes.value = '鍒嗘瀽缁撴潫';
+					}
 				}
 
 				if (chunkRes.mode === 'question') {
@@ -653,22 +655,32 @@
 					scrollToBottom();
 					return;
 				}
+				// 鏆傛椂涓嶈�冭檻澶氫釜 report鎯呭喌
 
+				// if (lastIsResult && chunkRes.mode !== 'finish') {
+				// 	// 寮�濮嬪鍔犳柊鐨� stepGroup
+				// 	computedMessageList.value.at(-1).stepGroup.push({
+				// 		value: [],
+				// 		isShow: true,
+				// 	});
+				// 	lastIsResult = false;
+				// }
 				const lastGroup = computedMessageList.value.at(-1).stepGroup.at(-1);
 				const stepList = lastGroup?.value ?? [];
 				const currentTimeStamp = new Date().getTime();
 				const ms = toMyFixed(currentTimeStamp - lastTimestamp, 2) + ' ms';
 				if (chunkRes.mode === 'finish') {
 					stepList.at(-1).ms = ms;
+					isTalking.value = false;
 
 					return;
 				}
 
 				if (stepList?.length >= 1) {
 					stepList.at(-1).ms = ms;
-				}else{
-					const stepGroup = computedMessageList.value.at(-1).stepGroup
-					if(stepGroup.length > 1){
+				} else {
+					const stepGroup = computedMessageList.value.at(-1).stepGroup;
+					if (stepGroup.length > 1) {
 						const lastStepList = stepGroup.at(-2).value;
 						lastStepList.at(-1).ms = ms;
 					}
@@ -678,7 +690,7 @@
 
 				stepList.push(stepItem);
 				// 寮哄埗瑙﹀彂鏇存柊
-		
+
 				scrollToBottom();
 			},
 			{
@@ -722,15 +734,47 @@
 	computedMessageList.value.at(-1).isStopMsg = true;
 };
 
-const sendChatMessage = async (content: ChatContent = messageContent.value, cb?: any, isCallExtParams?: any) => {
+const checkCanSend = (content: ChatContent = messageContent.value) => {
 	if (!content?.values) {
-		return;
+		return false;
 	}
 	if (isTalking.value || chatListLoading.value) {
 		ElMessage.warning('ai 姝e湪鍥炲涓紝璇风◢鍚庡皾璇曟彁闂�');
+		return false;
+	}
+	return true;
+};
+
+const addChatItem = (content: ChatContent) => {
+	isTalking.value = true;
+	const userItem: ChatMessage = { role: RoleEnum.user, content, isChecked: false } as any;
+	const assistantItem: ChatMessage = {
+		role: RoleEnum.assistant,
+		content: {
+			type: AnswerType.Report,
+		},
+		state: AnswerState.Null,
+		stepGroup: [
+			{
+				value: [],
+				isShow: true,
+			},
+		],
+		isStopMsg: false,
+		isChecked: false,
+	} as any;
+	messageList.value.push(userItem);
+	clearMessageContent();
+
+	messageList.value.push(assistantItem);
+	scrollToBottom();
+	return [userItem, assistantItem];
+};
+
+const sendChatMessage = async (content: ChatContent = messageContent.value) => {
+	if (!checkCanSend(content)) {
 		return;
 	}
-
 	const isNewChat = messageList.value.length === 0;
 	if (isNewChat) {
 		if (activeSampleId.value) {
@@ -744,48 +788,18 @@
 	let resMsgContent: ChatContent = null;
 
 	try {
-		isTalking.value = true;
-		const userItem: ChatMessage = { role: RoleEnum.user, content, isChecked: false } as any;
-		const assistantItem: ChatMessage = {
-			role: RoleEnum.assistant,
-			content: {
-				type: AnswerType.Report,
-			},
-			state: AnswerState.Null,
-			stepGroup: [
-				{
-					value: [],
-					isShow: true,
-				},
-			],
-			isStopMsg: false,
-			isChecked: false,
-		} as any;
-		messageList.value.push(userItem);
-		clearMessageContent();
+		const [userItem, assistantItem] = addChatItem(content);
 
-		messageList.value.push(assistantItem);
-		scrollToBottom();
+		resMsgContent = await questionAi(content.values);
 
-		if (isCallExtParams) {
-			const extRes = await extCallQuery(isCallExtParams);
-			questionRes = extRes;
-			resMsgContent = parseContent(extRes, true);
-		} else {
-			resMsgContent = await questionAi(content.values);
-		}
-		nextUserMsgEndIndex.value++;
-		if (isNewChat) {
-			const firstResCb = getRoomConfig(currentRouteId, 'firstResCb');
-			firstResCb?.(resMsgContent);
-		} else {
-			cb?.(resMsgContent);
-		}
+		updateLoadIndex();
+
 		userItem.historyId = questionRes?.history_id;
 		userItem.content.values = questionRes?.question ?? userItem.content.values;
 		assistantItem.historyId = questionRes?.history_id;
-		assistantItem.sectionAId = finalCalcSectionAId;
-		appendLastMessageContent(resMsgContent);
+		const currentTime = formatShowTimeYear(moment().format('YYYY-MM-DD HH:mm:ss'));
+		assistantItem.createTime = currentTime;
+		assistantItem.content = resMsgContent;
 		setTimeout(() => {
 			// 鏀跺埌鍥炲锛岀户缁粴
 			scrollToBottom();
@@ -793,18 +807,11 @@
 	} catch (error: any) {}
 };
 
-const sendClick = (cb) => {
-	sendChatMessage(messageContent.value, cb);
-};
-const appendLastMessageContent = (content: ChatContent) => {
-	const currentTime = moment().format('MM鏈圖D鏃� HH:mm:ss');
-	if (messageList.value.at(-1)) {
-		messageList.value.at(-1).content = content;
-		messageList.value.at(-1).createTime = currentTime;
-	}
+const sendClick = () => {
+	sendChatMessage(messageContent.value);
 };
 
-const { loadRangeData, onChatListScroll, moreIsLoading, nextUserMsgEndIndex } = useScrollLoad({
+const { loadRangeData, onChatListScroll, moreIsLoading, updateLoadIndex } = useScrollLoad({
 	container: chatListDom,
 	historyGroupId: currentRouteId,
 	messageList,
@@ -813,67 +820,97 @@
 
 const chatListLoading = ref(true);
 
-const { scrollToBottom, scrollToTop, isBottom } = useScrollToBottom({
-	chatListDom: chatListDom,
-});
-
 onActivated(() => {
 	emitter.emit('updateHeaderTitle', activeChatRoom.value?.title ?? '');
 });
 
+const initNewChat = () => {
+	messageContent.value = {
+		type: AnswerType.Text,
+		values: activeChatRoom.value?.title,
+	};
+	sendChatMessage();
+};
+const scrollToBottom = () => {
+	containerRef.value?.scrollToBottom();
+};
+
+const initHistoryChat = () => {
+	// 鍒濆鐘舵�佹粴涓�涓�
+	scrollToBottom();
+
+	setTimeout(() => {
+		chatListDom.value.addEventListener('scroll', onChatListScroll);
+	}, 300);
+};
+
+/**
+ * 鍔犺浇鍒嗕韩鏁版嵁
+ */
+const loadShareData = async () => {
+	const res = await getShareChatJsonByPost({
+		share_id: router.currentRoute.value.query.id as string,
+	});
+
+	const msgValue = res?.values;
+	if (!msgValue) {
+		messageList.value = [];
+		return;
+	}
+	const userMsg: ChatMessage = {
+		historyId: msgValue.history_id,
+		role: RoleEnum.user,
+		content: {
+			type: AnswerType.Text,
+			values: msgValue.question,
+		},
+		isChecked: false,
+	};
+
+	const assistantMsg: ChatMessage = {
+		historyId: msgValue.history_id,
+		role: RoleEnum.assistant,
+		content: parseContent(msgValue),
+		stepGroup: (msgValue?.reports ?? []).map((item) => ({
+			value: convertProcessToStep(item?.exec_process),
+			isShow: false,
+		})),
+		isStopMsg: false,
+
+		conclusion: msgValue.conclusion ?? [],
+		isChecked: false,
+	};
+	messageList.value = [userMsg, assistantMsg];
+};
+
 onMounted(async () => {
 	messageList.value = [];
 	chatListLoading.value = true;
-	await loadRangeData().finally(() => {
-		chatListLoading.value = false;
-	});
+	if (isSharePage.value) {
+		await loadShareData().finally(() => {
+			chatListLoading.value = false;
+		});
+	} else {
+		await loadRangeData().finally(() => {
+			chatListLoading.value = false;
+		});
+	}
 	setTimeout(() => {
 		emitter.emit('updateHeaderTitle', activeChatRoom.value?.title ?? '');
 	}, 300);
 
 	if (messageList.value.length === 0) {
-		messageContent.value = {
-			type: AnswerType.Text,
-			values: activeChatRoom.value?.title,
-		};
-
-		sendChatMessage();
+		initNewChat();
 	} else {
-		if (isSharePage.value) {
-			// setTimeout(() => {
-			// 	// 婊氬姩鍒伴《閮�
-			// 	scrollToTop();
-			// }, 300);
-		} else {
+		if (!isSharePage.value) {
 			setTimeout(() => {
-				// 鍒濆鐘舵�佹粴涓�涓�
-				scrollToBottom();
-
-				setTimeout(() => {
-					chatListDom.value.addEventListener('scroll', onChatListScroll);
-				}, 300);
+				initHistoryChat();
 			}, 300);
 		}
 	}
 	loadAmisSource();
 });
-//#region ====================== 鍏宠仈鏌ヨ ======================
-const relativeQueryClick = async (val) => {
-	sendChatMessage(
-		{
-			type: AnswerType.Text,
-			values: val.question,
-		},
-		undefined,
-		{
-			history_group_id: currentRouteId,
-			question: val.question,
-			call_ext_id: val.call_ext_id,
-			call_ext_args: val.agrs ? JSON.stringify(val.agrs) : null,
-		}
-	);
-};
-//#endregion
+
 //#region ====================== 鍏夋爣杈撳叆涓婁笅绠ご鏄剧ず鍘嗗彶娑堟伅 ======================
 const currentIndex = ref(null);
 const history_data = computed(() => {
@@ -934,14 +971,7 @@
 //#endregion
 //#region ====================== 鐢ㄦ埛璇㈤棶鐨勯棶棰樿缃负甯哥敤璇� ======================
 const setCommonQuestionInfo = ref({});
-const { toClipboard } = useClipboard();
 
-//鐢ㄦ埛澶嶅埗闂
-const copyUserClick = (item) => {
-	const text = item.content.values;
-	ElMessage.success('澶嶅埗鎴愬姛');
-	toClipboard(text);
-};
 //鐢ㄦ埛闂璁剧疆涓哄父鐢ㄨ
 const setCommonQuestionClick = (item) => {
 	setCommonQuestionInfo.value = item;

--
Gitblit v1.9.3