feat: 调整项目结构

This commit is contained in:
duanshuwen
2025-09-21 17:25:09 +08:00
parent 0b66462d16
commit 9f23854ad5
410 changed files with 3806 additions and 1668 deletions

View File

@@ -0,0 +1,70 @@
<template>
<view class="container">
<view class="chat-ai">
<view class="loading-container">
<image
v-if="isLoading"
class="loading-img"
src="/static/chat_msg_loading.gif"
mode="aspectFit"
/>
<ChatMarkdown :key="textKey" :text="processedText" />
<DotLoading v-if="isLoading" />
</view>
<slot name="content"></slot>
</view>
<slot name="footer"></slot>
</view>
</template>
<script setup>
import { defineProps, computed, ref, watch } from "vue";
import ChatMarkdown from "../ChatMarkdown/index.vue";
import DotLoading from "../../loading/DotLoading.vue";
const props = defineProps({
text: {
type: String,
default: "",
},
isLoading: {
type: Boolean,
default: false,
},
});
// 用于强制重新渲染的key
const textKey = ref(0);
// 处理文本内容
const processedText = computed(() => {
if (!props.text) {
return "";
}
// 确保文本是字符串类型
const textStr = String(props.text);
// 处理加载状态的文本
if (textStr.includes("加载中") || textStr.includes("...")) {
return textStr;
}
return textStr;
});
// 监听text变化强制重新渲染
watch(
() => props.text,
(newText, oldText) => {
if (newText !== oldText) {
textKey.value++;
}
},
{ immediate: true }
);
</script>
<style lang="scss" scoped>
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,34 @@
.container {
display: flex;
flex-direction: column;
max-width: 100%; // ✅ 限制最大宽度
overflow-x: hidden; // ✅ 防止横向撑开
.chat-ai {
margin: 6px 12px;
padding: 0 12px;
max-width: 100%; // ✅ 限制最大宽度
min-width: 100px;
background: rgba(255, 255, 255, 0.4);
box-shadow: 2px 2px 6px 0px rgba(0, 0, 0, 0.1);
border-radius: 4px 20px 20px 20px;
border: 1px solid;
border-color: #ffffff;
overflow: hidden; // ✅ 超出内容被切掉
word-wrap: break-word; // ✅ 长单词自动换行
word-break: break-all; // ✅ 强制换行
}
}
.loading-container {
display: flex;
align-items: center;
padding: 4px 0;
max-width: 100%; // ✅ 限制最大宽度
}
.loading-img {
margin-right: 8px;
width: 30px;
height: 25px;
}

View File

@@ -0,0 +1,20 @@
<template>
<view class="chat-mine">
<text>{{ text }}</text>
<slot></slot>
</view>
</template>
<script setup>
import { defineProps } from "vue";
defineProps({
text: {
type: String,
default: "",
},
});
</script>
<style lang="scss" scoped>
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,26 @@
.chat-mine {
margin: 6px 12px;
padding: 8px 16px;
background-color: #00a6ff;
box-shadow: 2px 2px 10px 0px rgba(0, 0, 0, 0.1);
border-radius: 20px 4px 20px 20px;
border: 1px solid;
border-color: #ffffff;
display: flex;
flex-direction: column;
max-width: 100%; // ✅ 限制最大宽度
overflow-x: hidden; // ✅ 防止横向撑开
text {
font-family: PingFang SC, PingFang SC;
font-weight: 400;
font-size: 15px;
color: #ffffff;
line-height: 22px;
text-align: justify;
font-style: normal;
text-transform: none;
}
}

View File

@@ -0,0 +1,20 @@
<template>
<view class="chat-other">
<text>{{ text }}</text>
<slot></slot>
</view>
</template>
<script setup>
import { defineProps } from "vue";
defineProps({
text: {
type: String,
default: "",
},
});
</script>
<style lang="scss" scoped>
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,16 @@
.chat-other {
width: 100%;
margin: 6px 0;
padding: 0 12px;
display: flex;
flex-direction: column;
max-width: 100%; // ✅ 限制最大宽度
overflow-x: hidden; // ✅ 防止横向撑开
text {
font-family: PingFang SC, PingFang SC;
font-weight: 400;
font-size: 14px;
color: #333333;
}
}

View File

@@ -0,0 +1,235 @@
<template>
<view class="input-area-wrapper">
<view v-if="!visibleWaveBtn" class="area-input">
<!-- 语音/键盘切换 -->
<view class="input-container-voice" @click="toggleVoiceMode">
<image v-if="!isVoiceMode" src="/static/input_voice_icon.png"></image>
<image v-else src="/static/input_keyboard_icon.png"></image>
</view>
<!-- 输入框/语音按钮容器 -->
<view class="input-button-container">
<textarea
ref="textareaRef"
v-if="!isVoiceMode"
class="textarea"
type="text"
cursor-spacing="20"
confirm-type="send"
v-model="inputMessage"
auto-height
:confirm-hold="true"
:placeholder="placeholder"
:show-confirm-bar="false"
:hold-keyboard="holdKeyboard"
:adjust-position="true"
:disable-default-padding="true"
maxlength="300"
@confirm="sendMessage"
@focus="handleFocus"
@blur="handleBlur"
@touchstart="handleTouchStart"
@touchend="handleTouchEnd"
/>
<view
v-if="isVoiceMode"
class="hold-to-talk-button"
@longpress="handleVoiceTouchStart"
@touchend="handleVoiceTouchEnd"
@touchcancel="handleVoiceTouchEnd"
>
按住 说话
</view>
</view>
<view class="input-container-send">
<view class="input-container-send-btn" @click="sendMessage">
<image
v-if="props.isSessionActive"
src="/static/input_stop_icon.png"
></image>
<image v-else src="/static/input_send_icon.png"></image>
</view>
</view>
</view>
<!-- 录音按钮 -->
<RecordingWaveBtn v-if="visibleWaveBtn" ref="recordingWaveBtnRef" />
</view>
</template>
<script setup>
import { ref, computed, watch, nextTick, onMounted, defineExpose } from "vue";
import RecordingWaveBtn from "@/components/Speech/RecordingWaveBtn.vue";
import { getCurrentConfig } from "@/constant/base";
const plugin = requirePlugin("WechatSI");
const manager = plugin.getRecordRecognitionManager();
const props = defineProps({
modelValue: String,
holdKeyboard: Boolean,
isSessionActive: Boolean,
stopRequest: Function,
});
const emit = defineEmits([
"update:modelValue",
"send",
"noHideKeyboard",
"keyboardShow",
"keyboardHide",
"sendVoice",
]);
const textareaRef = ref(null);
const recordingWaveBtnRef = ref(null);
const placeholder = computed(() => getCurrentConfig().placeholder);
const inputMessage = ref(props.modelValue || "");
const isFocused = ref(false);
const keyboardHeight = ref(0);
const isVoiceMode = ref(false);
const visibleWaveBtn = ref(false);
// 保持和父组件同步
watch(
() => props.modelValue,
(val) => {
inputMessage.value = val;
}
);
// 当子组件的 inputMessage 变化时,通知父组件(但要避免循环更新)
watch(inputMessage, (val) => {
// 只有当值真正不同时才emit避免循环更新
if (val !== props.modelValue) {
emit("update:modelValue", val);
}
});
// 切换语音/文本模式
const toggleVoiceMode = () => {
isVoiceMode.value = !isVoiceMode.value;
};
// 处理语音按钮长按开始
const handleVoiceTouchStart = () => {
manager.start({ lang: "zh_CN" });
visibleWaveBtn.value = true;
// 启动音频条动画
nextTick(() => {
if (recordingWaveBtnRef.value) {
recordingWaveBtnRef.value.startAnimation();
}
});
};
// 处理语音按钮长按结束
const handleVoiceTouchEnd = () => {
manager.stop();
// 停止音频条动画
if (recordingWaveBtnRef.value) {
recordingWaveBtnRef.value.stopAnimation();
}
visibleWaveBtn.value = false;
};
// 处理发送原语音
const initRecord = () => {
manager.onRecognize = (res) => {
let text = res.result;
inputMessage.value = text;
};
// 识别结束事件
manager.onStop = (res) => {
console.log(res, 37);
let text = res.result;
if (text == "") {
console.log("没有说话");
return;
}
inputMessage.value = text;
// 在语音识别完成后发送消息
emit("send", text);
};
};
// 监听键盘高度变化
onMounted(() => {
// 监听键盘弹起
uni.onKeyboardHeightChange((res) => {
keyboardHeight.value = res.height;
if (res.height) {
emit("keyboardShow", res.height);
} else {
emit("keyboardHide");
}
});
initRecord();
});
const sendMessage = () => {
if (props.isSessionActive) {
// 如果会话进行中,调用停止请求函数
if (props.stopRequest) {
props.stopRequest();
}
} else {
// 否则发送新消息
if (!inputMessage.value.trim()) return;
emit("send", inputMessage.value);
// 发送后保持焦点(可选)
if (props.holdKeyboard && textareaRef.value) {
nextTick(() => {
textareaRef.value.focus();
});
}
}
};
const handleFocus = () => {
isFocused.value = true;
emit("noHideKeyboard");
};
const handleBlur = () => {
isFocused.value = false;
};
const handleTouchStart = () => {
emit("noHideKeyboard");
};
const handleTouchEnd = () => {
emit("noHideKeyboard");
};
// 手动聚焦输入框
const focusInput = () => {
if (textareaRef.value) {
textareaRef.value.focus();
}
};
// 手动失焦输入框
const blurInput = () => {
if (textareaRef.value) {
textareaRef.value.blur();
}
};
// 暴露方法给父组件
defineExpose({ focusInput });
</script>
<style scoped lang="scss">
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,84 @@
.area-input {
display: flex;
align-items: center;
border-radius: 22px;
background-color: #ffffff;
box-shadow: 0px 0px 20px 0px rgba(52, 25, 204, 0.05);
margin: 0 12px;
margin-bottom: 8px;
.input-container-voice {
display: flex;
align-items: center;
justify-content: center;
align-self: flex-end;
width: 44px;
height: 44px;
image {
width: 22px;
height: 22px;
}
}
.input-button-container {
flex: 1;
position: relative;
}
.hold-to-talk-button {
width: 100%;
height: 44px;
color: #333333;
font-size: 16px;
display: flex;
justify-content: center;
align-items: center;
background-color: #ffffff;
transition: all 0.2s ease;
user-select: none;
-webkit-user-select: none;
}
.input-container-send {
display: flex;
align-items: center;
justify-content: center;
align-self: flex-end;
width: 44px;
height: 44px;
.input-container-send-btn {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
image {
width: 28px;
height: 28px;
}
}
.textarea {
flex: 1;
box-sizing: border-box;
width: 100%;
max-height: 92px;
min-height: 22px;
font-size: 16px;
line-height: 22px;
margin: 6px 0;
&::placeholder {
color: #cccccc;
line-height: normal;
}
&:focus {
outline: none;
}
}
}

View File

@@ -0,0 +1,809 @@
<template>
<view class="chat-container" @touchend="handleTouchEnd">
<!-- 顶部的背景 -->
<ChatTopBgImg class="chat-container-bg"></ChatTopBgImg>
<view class="chat-content">
<!-- 顶部自定义导航栏 -->
<view
class="nav-bar-container"
:style="{
paddingTop: statusBarHeight + 'px',
}"
>
<ChatTopNavBar @openDrawer="openDrawer"></ChatTopNavBar>
</view>
<!-- 消息列表可滚动区域 -->
<scroll-view
:scroll-top="scrollTop"
scroll-y
:scroll-with-animation="true"
class="area-msg-list"
@scroll="handleScroll"
@scrolltolower="handleScrollToLower"
>
<!-- welcome栏 -->
<ChatTopWelcome
class="chat-container-top-bannar"
:initPageImages="mainPageDataModel.initPageImages"
:welcomeContent="mainPageDataModel.welcomeContent"
>
</ChatTopWelcome>
<view
class="area-msg-list-content"
v-for="item in chatMsgList"
:key="item.msgId"
:id="item.msgId"
>
<template v-if="item.msgType === MessageRole.AI">
<ChatCardAI
class="message-item-ai"
:key="`ai-${item.msgId}-${item.msg ? item.msg.length : 0}`"
:text="item.msg || ''"
:isLoading="item.isLoading"
>
<template #content v-if="item.toolCall">
<QuickBookingComponent
v-if="
item.toolCall.componentName === CompName.quickBookingCard
"
/>
<DiscoveryCardComponent
v-else-if="
item.toolCall.componentName === CompName.discoveryCard
"
/>
<CreateServiceOrder
v-else-if="
item.toolCall.componentName === CompName.createWorkOrderCard
"
/>
<Feedback
v-else-if="
item.toolCall.componentName === CompName.feedbackCard
"
:toolCall="item.toolCall"
/>
<DetailCardCompontent
v-else-if="
item.toolCall.componentName ===
CompName.pictureAndCommodityCard
"
:toolCall="item.toolCall"
/>
<AddCarCrad
v-else-if="
item.toolCall.componentName ===
CompName.enterLicensePlateCard
"
:toolCall="item.toolCall"
/>
</template>
<template #footer>
<!-- 这个是底部 -->
<AttachListComponent
v-if="item.question"
:question="item.question"
@replySent="handleReply"
/>
</template>
</ChatCardAI>
</template>
<template v-else-if="item.msgType === MessageRole.ME">
<ChatCardMine class="message-item-mine" :text="item.msg">
</ChatCardMine>
</template>
<template v-else>
<ChatCardOther class="message-item-other" :text="item.msg">
<ChatMoreTips
@replySent="handleReply"
:itemList="mainPageDataModel.guideWords"
/>
<ActivityListComponent
v-if="
mainPageDataModel.activityList &&
mainPageDataModel.activityList.length > 0
"
:activityList="mainPageDataModel.activityList"
/>
<RecommendPostsComponent
v-if="
mainPageDataModel.recommendTheme &&
mainPageDataModel.recommendTheme.length > 0
"
:recommendThemeList="mainPageDataModel.recommendTheme"
/>
</ChatCardOther>
</template>
</view>
</scroll-view>
<!-- 输入框区域 -->
<view class="footer-area">
<ChatQuickAccess @replySent="handleReplyInstruct" />
<ChatInputArea
ref="inputAreaRef"
v-model="inputMessage"
:holdKeyboard="holdKeyboard"
:is-session-active="isSessionActive"
:stop-request="stopRequest"
@send="sendMessageAction"
@noHideKeyboard="handleNoHideKeyboard"
@keyboardShow="handleKeyboardShow"
@keyboardHide="handleKeyboardHide"
/>
</view>
</view>
</view>
</template>
<script setup>
import { onMounted, nextTick, onUnmounted, ref, defineEmits, watch } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
SCROLL_TO_BOTTOM,
RECOMMEND_POSTS_TITLE,
SEND_COMMAND_TEXT,
NOTICE_EVENT_LOGOUT,
} from "@/constant/constant";
import { WSS_URL } from "@/request/base/baseUrl";
import { MessageRole, MessageType, CompName } from "@/model/ChatModel";
import ChatTopWelcome from "../ChatTopWelcome/index.vue";
import ChatTopBgImg from "../ChatTopBgImg/index.vue";
import ChatTopNavBar from "../ChatTopNavBar/index.vue";
import ChatCardAI from "../ChatCardAi/index.vue";
import ChatCardMine from "../ChatCardMine/index.vue";
import ChatCardOther from "../ChatCardOther/index.vue";
import ChatQuickAccess from "../ChatQuickAccess/index.vue";
import ChatMoreTips from "../ChatMoreTips/index.vue";
import ChatInputArea from "../ChatInputArea/index.vue";
import QuickBookingComponent from "../../module/QuickBookingComponent/index.vue";
import DiscoveryCardComponent from "../../module/DiscoveryCardComponent/index.vue";
import ActivityListComponent from "../../module/ActivityListComponent/index.vue";
import RecommendPostsComponent from "../../module/RecommendPostsComponent/index.vue";
import AttachListComponent from "../../module/AttachListComponent/index.vue";
import DetailCardCompontent from "../../module/DetailCardCompontent/index.vue";
import CreateServiceOrder from "@/components/CreateServiceOrder/index.vue";
import Feedback from "@/components/Feedback/index.vue";
import AddCarCrad from "@/components/AddCarCrad/index.vue";
import { mainPageData } from "@/request/api/MainPageDataApi";
import {
conversationMsgList,
recentConversation,
} from "@/request/api/ConversationApi";
import WebSocketManager from "@/utils/WebSocketManager";
import TypewriterManager from "@/utils/TypewriterManager";
import { IdUtils } from "@/utils";
import { checkToken } from "@/hooks/useGoLogin";
import { useAppStore } from "@/store";
const appStore = useAppStore();
/// 导航栏相关
const statusBarHeight = ref(20);
/// 输入框组件引用
const inputAreaRef = ref(null);
const holdKeyboardTimer = ref(null);
/// focus时点击页面的时候不收起键盘
const holdKeyboard = ref(false);
/// 是否在键盘弹出,点击界面时关闭键盘
const holdKeyboardFlag = ref(true);
/// 是否显示键盘
const isKeyboardShow = ref(false);
///(控制滚动位置)
const scrollTop = ref(99999);
// 用户滚动状态控制
const isUserScrolling = ref(false);
/// 会话列表
const chatMsgList = ref([]);
/// 输入口的输入消息
const inputMessage = ref("");
/// agentId 首页接口中获取
const agentId = ref("1");
/// 会话ID 历史数据接口中获取
const conversationId = ref("");
/// 首页的数据
const mainPageDataModel = ref({});
// 会话进行中标志
const isSessionActive = ref(false);
/// 指令
let commonType = "";
// WebSocket 相关
let webSocketManager = null;
/// WebSocket 连接状态
let webSocketConnectStatus = false;
// 打字机管理器
let typewriterManager = null;
// 当前会话的消息ID用于保持发送和终止的messageId一致
let currentSessionMessageId = null;
// 打开抽屉
const emits = defineEmits(["openDrawer"]);
const openDrawer = () => emits("openDrawer");
/// =============事件函数↓================
const handleTouchEnd = () => {
clearTimeout(holdKeyboardTimer.value);
holdKeyboardTimer.value = setTimeout(() => {
// 键盘弹出时点击界面则关闭键盘
if (holdKeyboardFlag.value && isKeyboardShow.value) {
uni.hideKeyboard();
}
holdKeyboardFlag.value = true;
}, 100);
};
// 点击输入框、发送按钮时,不收键盘
const handleNoHideKeyboard = () => (holdKeyboardFlag.value = false);
// 键盘弹起事件
const handleKeyboardShow = () => {
isKeyboardShow.value = true;
holdKeyboard.value = true;
// 键盘弹起时调整聊天内容的底部边距并滚动到底部
setTimeout(() => {
scrollToBottom();
}, 150);
};
// 键盘收起事件
const handleKeyboardHide = () => {
isKeyboardShow.value = false;
holdKeyboard.value = false;
};
// 处理用户滚动事件
const handleScroll = (e) => {
// 标记用户正在滚动
};
// 处理滚动到底部事件
const handleScrollToLower = () => {};
// 滚动到底部 - 优化版本,确保打字机效果始终可见
const scrollToBottom = () => {
nextTick(() => {
// 使用更大的值确保滚动到真正的底部
scrollTop.value = 99999;
// 强制触发滚动更新增加延迟确保DOM更新完成
setTimeout(() => {
scrollTop.value = scrollTop.value + Math.random();
}, 10);
});
};
// 延时滚动
const setTimeoutScrollToBottom = () => setTimeout(() => scrollToBottom(), 100);
// 发送普通消息
const handleReply = (text) => {
// 重置消息状态准备接收新的AI回复
resetMessageState();
sendMessage(text);
setTimeoutScrollToBottom();
};
// 是发送指令
const handleReplyInstruct = async (item) => {
await checkToken();
if (item.type === "MyOrder") {
// 订单
uni.navigateTo({
url: "/pages-order/order/list",
});
return;
}
commonType = item.type;
// 重置消息状态准备接收新的AI回复
resetMessageState();
sendMessage(item.title, true);
setTimeoutScrollToBottom();
};
// 输入区的发送消息事件
const sendMessageAction = (inputText) => {
console.log("输入消息:", inputText);
if (!inputText.trim()) return;
handleNoHideKeyboard();
// 重置消息状态准备接收新的AI回复
resetMessageState();
sendMessage(inputText);
// 发送消息后保持键盘状态
if (holdKeyboard.value && inputAreaRef.value) {
setTimeout(() => {
inputAreaRef.value.focusInput();
}, 100);
}
setTimeoutScrollToBottom();
};
/// 添加通知
const addNoticeListener = () => {
uni.$on(NOTICE_EVENT_LOGOUT, () => {
resetConfig();
uni.showToast({
title: "退出登录成功",
});
});
uni.$on(SCROLL_TO_BOTTOM, () => {
setTimeout(() => {
scrollToBottom();
}, 200);
});
uni.$on(RECOMMEND_POSTS_TITLE, (value) => {
console.log("RECOMMEND_POSTS_TITLE:", value);
if (value && value.length > 0) {
handleReply(value);
}
});
uni.$on(SEND_COMMAND_TEXT, (value) => {
console.log("SEND_COMMAND_TEXT:", value);
if (value && value.length > 0) {
commonType = "Command.quickBooking";
sendMessage(value, true);
setTimeoutScrollToBottom();
}
});
};
/// =============生命周期函数↓================
onLoad(() => {
uni.getSystemInfo({
success: (res) => {
statusBarHeight.value = res.statusBarHeight || 20;
},
});
});
// token存在初始化数据
const initHandler = () => {
console.log("initHandler");
if (!appStore.hasToken) return;
loadRecentConversation();
///loadConversationMsgList();
initWebSocket();
};
// 绑定成功监听token变化,初始化
watch(
() => appStore.hasToken,
(newValue) => {
if (newValue) {
console.log("token存在初始化数据");
initHandler();
}
}
);
onMounted(() => {
try {
getMainPageData();
addNoticeListener();
initTypewriterManager();
// 有token时加载最近会话、最近消息、初始化socket
initHandler();
} catch (error) {
console.error("页面初始化错误:", error);
}
});
/// =============页面配置↓================
// 获取最近一次的会话id
const loadRecentConversation = async () => {
const res = await recentConversation();
if (res.code === 0) {
conversationId.value = res.data.conversationId;
}
};
// 加载历史消息的数据
let historyCurrentPageNum = 1;
const loadConversationMsgList = async () => {
const args = {
pageNum: historyCurrentPageNum++,
pageSize: 10,
conversationId: conversationId.value,
};
const res = await conversationMsgList(args);
};
// 获取首页数据
const getMainPageData = async () => {
/// 从个渠道获取如二维,没有的时候就返回首页的数据
const sceneId = appStore.sceneId || "";
const res = await mainPageData({ sceneId });
if (res.code === 0) {
initData();
mainPageDataModel.value = res.data;
agentId.value = res.data.agentId;
setTimeoutScrollToBottom();
}
};
/// =============对话↓================
// 初始化WebSocket
const initWebSocket = () => {
// 清理旧实例
if (webSocketManager) {
webSocketManager.destroy();
}
// 使用配置的WebSocket服务器地址
const token = uni.getStorageSync("token");
const wsUrl = `${WSS_URL}?access_token=${token}`;
// 初始化WebSocket管理器
webSocketManager = new WebSocketManager({
wsUrl: wsUrl,
reconnectInterval: 3000, // 重连间隔
maxReconnectAttempts: 5, // 最大重连次数
heartbeatInterval: 30000, // 心跳间隔
// 连接成功回调
onOpen: (event) => {
// 重置会话状态
webSocketConnectStatus = true;
isSessionActive.value = true;
},
// 连接断开回调
onClose: (event) => {
console.error("WebSocket连接断开:", event);
webSocketConnectStatus = false;
// 停止当前会话
isSessionActive.value = false;
// 停止打字机效果
if (typewriterManager) {
typewriterManager.stopTypewriter();
}
},
// 错误回调
onError: (error) => {
webSocketConnectStatus = false;
isSessionActive.value = false;
console.error("WebSocket错误:", error);
},
// 消息回调
onMessage: (data) => {
handleWebSocketMessage(data);
},
// 获取会话ID回调 (用于心跳检测)
getConversationId: () => conversationId.value,
// 获取代理ID回调 (用于心跳检测)
getAgentId: () => agentId.value,
});
// 初始化连接
webSocketManager
.connect()
.then(() => {
webSocketConnectStatus = true;
})
.catch((error) => {
console.error("WebSocket连接失败:", error);
});
};
// 处理WebSocket消息
const handleWebSocketMessage = (data) => {
const aiMsgIndex = chatMsgList.value.length - 1;
if (!chatMsgList.value[aiMsgIndex] || aiMsgIndex < 0) {
return;
}
// 确保消息内容是字符串类型
if (data.content && typeof data.content !== "string") {
data.content = String(data.content);
}
// 处理content分片内容
if (data.content) {
// 使用打字机管理器添加内容
if (typewriterManager) {
typewriterManager.addContent(data.content);
}
// 确保新内容到达时页面保持在底部
setTimeoutScrollToBottom();
}
// 处理完成状态
if (data.finish) {
// 等待打字机完成后处理其他数据
const waitForTypingComplete = () => {
const status = typewriterManager
? typewriterManager.getStatus()
: { isTyping: false };
if (status.isTyping) {
setTimeout(waitForTypingComplete, 50);
return;
}
const msg = chatMsgList.value[aiMsgIndex].msg;
console.log("全量消息内容:", msg);
if (!msg || msg === "加载中" || msg.startsWith("加载中")) {
chatMsgList.value[aiMsgIndex].msg = "未获取到内容,请重试";
chatMsgList.value[aiMsgIndex].isLoading = false;
if (data.toolCall) {
chatMsgList.value[aiMsgIndex].msg = "";
}
}
// 处理toolCall
if (data.toolCall) {
chatMsgList.value[aiMsgIndex].toolCall = data.toolCall;
}
// 处理question
if (data.question && data.question.length > 0) {
chatMsgList.value[aiMsgIndex].question = data.question;
}
// 重置会话状态
isSessionActive.value = false;
};
waitForTypingComplete();
}
};
// 初始化打字机管理器
const initTypewriterManager = () => {
if (typewriterManager) {
typewriterManager.destroy();
}
typewriterManager = new TypewriterManager({
typingSpeed: 30,
cursorText: "",
});
// 设置回调函数
typewriterManager.setCallbacks({
// 每个字符打字时的回调
onCharacterTyped: (displayedContent) => {
scrollToBottom();
},
// 内容更新时的回调
onContentUpdate: (content) => {
const aiMsgIndex = chatMsgList.value.length - 1;
if (aiMsgIndex >= 0 && chatMsgList.value[aiMsgIndex]) {
chatMsgList.value[aiMsgIndex].isLoading = false;
chatMsgList.value[aiMsgIndex].msg = content;
}
},
// 打字完成时的回调
onTypingComplete: (finalContent) => {
const aiMsgIndex = chatMsgList.value.length - 1;
if (aiMsgIndex >= 0 && chatMsgList.value[aiMsgIndex]) {
chatMsgList.value[aiMsgIndex].isLoading = false;
chatMsgList.value[aiMsgIndex].msg = finalContent;
}
// 打字完成后最后一次滚动到底部
setTimeoutScrollToBottom();
},
});
};
// 重置消息状态
const resetMessageState = () => {
if (typewriterManager) {
typewriterManager.reset();
}
};
// 初始化数据 首次数据加载的时候
const initData = () => {
const msg = {
msgId: `msg_${0}`,
msgType: MessageRole.OTHER,
msg: "",
};
chatMsgList.value.push(msg);
};
// 发送消息的参数拼接
const sendMessage = async (message, isInstruct = false) => {
console.log("发送的消息:", message);
await checkToken();
if (!webSocketConnectStatus) {
uni.showToast({
title: "当前网络异常,请稍后重试",
icon: "none",
});
return;
}
if (isSessionActive.value) {
uni.showToast({
title: "请等待当前回复完成",
icon: "none",
});
return;
}
isSessionActive.value = true;
const newMsg = {
msgId: `msg_${chatMsgList.value.length}`,
msgType: MessageRole.ME,
msg: message,
msgContent: {
type: MessageType.TEXT,
text: message,
},
};
chatMsgList.value.push(newMsg);
inputMessage.value = "";
sendChat(message, isInstruct);
console.log("发送的新消息:", JSON.stringify(newMsg));
};
// 通用WebSocket消息发送函数
const sendWebSocketMessage = (messageType, messageContent, options = {}) => {
const args = {
conversationId: conversationId.value,
agentId: agentId.value,
messageType: String(messageType), // 消息类型 0-对话 1-指令 2-中断停止 3-心跳检测
messageContent: messageContent,
messageId: currentSessionMessageId,
};
try {
webSocketManager.sendMessage(args);
console.log(`WebSocket消息已发送 [类型:${messageType}]:`, args);
return true;
} catch (error) {
console.error("发送WebSocket消息失败:", error);
isSessionActive.value = false;
return false;
}
};
// 发送获取AI聊天消息
const sendChat = (message, isInstruct = false) => {
if (!webSocketManager || !webSocketManager.isConnected()) {
console.error("WebSocket未连接");
isSessionActive.value = false;
return;
}
const messageType = isInstruct ? 1 : 0;
const messageContent = isInstruct ? commonType : message;
currentSessionMessageId = IdUtils.generateMessageId();
// 重置消息状态,为新消息做准备
resetMessageState();
// 插入AI消息
const aiMsg = {
msgId: `msg_${chatMsgList.value.length}`,
msgType: MessageRole.AI,
msg: "加载中",
isLoading: true,
msgContent: {
type: MessageType.TEXT,
url: "",
},
};
chatMsgList.value.push(aiMsg);
const aiMsgIndex = chatMsgList.value.length - 1;
// 发送消息
const success = sendWebSocketMessage(messageType, messageContent);
if (!success) {
chatMsgList.value[aiMsgIndex].msg = "发送消息失败,请重试";
chatMsgList.value[aiMsgIndex].isLoading = false;
isSessionActive.value = false;
resetMessageState();
}
};
// 停止请求函数
const stopRequest = () => {
console.log("停止请求");
// 发送中断消息给服务器 (messageType=2)
sendWebSocketMessage(2, "stop_request", { silent: true });
// 停止打字机效果并保留当前内容
if (typewriterManager) {
// 获取当前已显示的内容
const currentStatus = typewriterManager.getStatus();
const currentDisplayedContent = currentStatus.displayedContent;
// 使用新的方法停止并保留当前内容
typewriterManager.stopAndKeepCurrent();
// 更新最后一条AI消息的状态
const aiMsgIndex = chatMsgList.value.length - 1;
if (
chatMsgList.value[aiMsgIndex] &&
chatMsgList.value[aiMsgIndex].msgType === MessageRole.AI
) {
chatMsgList.value[aiMsgIndex].isLoading = false;
// 如果有已显示的内容,使用已显示的内容,否则显示停止消息
if (
currentDisplayedContent &&
currentDisplayedContent.trim() &&
!currentDisplayedContent.startsWith("加载中")
) {
chatMsgList.value[aiMsgIndex].msg = currentDisplayedContent;
} else {
chatMsgList.value[aiMsgIndex].msg = "请求已停止";
}
}
}
// 重置会话状态(但不重置消息状态,保留已显示内容)
isSessionActive.value = false;
console.log("请求已停止,状态已重置");
setTimeoutScrollToBottom();
};
// 组件销毁时清理资源
onUnmounted(() => {
uni.$off(SCROLL_TO_BOTTOM);
uni.$off(RECOMMEND_POSTS_TITLE);
uni.$off(SEND_COMMAND_TEXT);
uni.$off(NOTICE_EVENT_LOGOUT);
resetConfig();
});
const resetConfig = () => {
// 清理WebSocket连接
if (webSocketManager) {
webSocketManager.destroy();
webSocketManager = null;
}
// 清理打字机管理器
if (typewriterManager) {
typewriterManager.destroy();
typewriterManager = null;
}
// 重置消息状态
resetMessageState();
// 清理定时器
if (holdKeyboardTimer.value) {
clearTimeout(holdKeyboardTimer.value);
holdKeyboardTimer.value = null;
}
};
</script>
<style lang="scss" scoped>
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,155 @@
.chat-container {
width: 100vw;
height: 100vh;
background-color: #e9f3f7;
display: flex;
flex-direction: column;
overflow: hidden !important;
position: relative;
/* 确保在键盘弹起时布局正确 */
box-sizing: border-box;
.chat-container-bg {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 0;
height: 270px;
background: linear-gradient(180deg, #42adf9 0%, #6cd1ff 51%, #e9f3f7 99%);
}
.chat-content {
width: 100vw;
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
z-index: 1;
overflow: hidden;
}
.chat-container-top-bannar {
width: 100vw;
flex-shrink: 0;
touch-action: none;
}
.area-msg-list {
width: 100vw;
flex: 1;
overflow-y: auto;
min-height: 0;
height: 0;
padding: 4px 0 0;
overscroll-behavior: contain; /* 阻止滚动穿透 */
-webkit-overflow-scrolling: touch;
display: flex;
flex-direction: column;
.message-item-ai {
display: flex;
justify-content: flex-start;
}
.message-item-mine {
display: flex;
justify-content: flex-end;
}
.message-item-other {
display: flex;
justify-content: center;
}
}
}
.footer-area {
width: 100vw;
flex-shrink: 0;
padding: 4px 0 20px 0; /* 直接设置20px底部安全距离 */
background-color: #e9f3f7;
touch-action: pan-x;
overflow-x: auto;
overflow-y: hidden;
min-height: fit-content;
/* 安卓键盘适配 - 使用相对定位配合adjustPan */
position: relative;
z-index: 1;
transition: padding-bottom 0.3s ease;
/* 确保输入区域始终可见 */
// transform: translateZ(0);
// -webkit-transform: translateZ(0);
}
.area-input {
display: flex;
align-items: center;
border-radius: 22px;
background-color: #ffffff;
box-shadow: 0px 0px 20px 0px rgba(52, 25, 204, 0.05);
margin: 0 12px;
.input-container-voice {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
flex-shrink: 0;
align-self: flex-end;
image {
width: 22px;
height: 22px;
}
}
.input-container-send {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
flex-shrink: 0;
align-self: flex-end;
image {
width: 28px;
height: 28px;
}
}
.textarea {
flex: 1;
max-height: 92px;
min-height: 22px;
font-size: 16px;
line-height: 22px;
margin-bottom: 2px;
align-items: center;
}
}
// 打字机光标闪烁动画
.typing-cursor {
display: inline-block;
color: #42adf9;
font-weight: bold;
font-size: 1.2em;
animation: blink 1s infinite;
margin-left: 2px;
}
@keyframes blink {
0%,
50% {
opacity: 1;
}
51%,
100% {
opacity: 0;
}
}

View File

@@ -0,0 +1,18 @@
<template>
<view>
<zero-markdown-view :markdown="text" :aiMode="true"></zero-markdown-view>
</view>
</template>
<script setup>
import { defineProps } from "vue";
defineProps({
text: {
type: String,
default: "",
},
});
</script>
<style scoped></style>

View File

@@ -0,0 +1,43 @@
<template>
<view class="more-tips">
<view class="more-tips-scroll">
<view
class="more-tips-item"
v-for="(item, index) in itemList"
:key="index"
>
<view class="more-tips-item-title" @click="sendReply(item)">
{{ item }}
</view>
</view>
</view>
</view>
</template>
<script setup>
import { defineProps } from "vue";
const emits = defineEmits(["replySent"]);
defineProps({
itemList: {
type: Array,
default: [
"定温泉票",
"定酒店",
"优惠套餐",
"亲子玩法",
"了解交通",
"看看酒店",
"看看美食",
],
},
});
const sendReply = (text) => {
emits("replySent", text);
};
</script>
<style lang="scss" scoped>
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,35 @@
.more-tips {
width: 100%;
&-scroll {
display: flex;
flex-direction: row;
overflow-x: auto;
white-space: nowrap;
-webkit-overflow-scrolling: touch;
padding-bottom: 12px;
box-sizing: border-box;
}
.more-tips-item {
border-radius: 8px;
margin: 4px;
box-shadow: 0 2px 5px 0px rgba(0, 0, 0, 0.1);
background-color: #ffffff;
padding: 2px 12px;
display: flex;
flex-direction: column;
flex-shrink: 0;
white-space: nowrap;
position: relative;
.more-tips-item-title {
font-weight: 500;
font-size: 12px;
color: #00a6ff;
line-height: 24px;
text-align: center;
white-space: nowrap;
}
}
}

View File

@@ -0,0 +1,71 @@
<template>
<view class="quick-access">
<view class="quick-access-scroll">
<view
class="quick-access-item"
v-for="(item, index) in itemList"
:key="index"
@click="sendReply(item)"
>
<image
class="quick-access-item-bg"
src="/static/quick/quick_icon_bg.png"
mode="aspectFill"
></image>
<view class="quick-access-item-title">
<image :src="item.icon"></image>
<text>{{ item.title }}</text>
</view>
<text class="quick-access-item-content">{{ item.content }}</text>
</view>
</view>
</view>
</template>
<script setup>
import { onMounted, ref } from "vue";
const itemList = ref([]);
const emits = defineEmits(["replySent"]);
const sendReply = (item) => {
emits("replySent", item); // 向父组件传递数据
};
onMounted(() => {
initData();
});
const initData = () => {
itemList.value = [
{
icon: "/static/quick/quick_icon_yuding.png",
title: "快速预定",
content: "预定门票、房间、餐食",
type: "Command.quickBooking",
},
{
icon: "/static/quick/quick_icon_find.png",
title: "探索发现",
content: "探索玩法、出片佳地",
type: "Command.discovery",
},
{
icon: "/static/quick/quick_icon_order.png",
title: "订单/工单",
content: "我的订单/工单",
type: "MyOrder",
},
{
icon: "/static/quick/quick_icon_call.png",
title: "反馈意见",
content: "有意见告诉朵朵",
type: "Command.feedbackCard",
},
];
};
</script>
<style lang="scss" scoped>
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,70 @@
.quick-access {
width: 100%;
&-scroll {
display: flex;
flex-direction: row;
overflow-x: auto;
white-space: nowrap;
-webkit-overflow-scrolling: touch;
}
.quick-access-item {
flex: 0 0 104px;
border-radius: 8px;
margin: 4px 4px 8px 4px;
box-shadow: 0 2px 5px 0px rgba(0, 0, 0, 0.1);
padding: 12px;
display: inline-flex;
flex-direction: column;
position: relative;
&:first-child {
margin-left: 12px;
}
&:last-child {
margin-right: 12px;
}
.quick-access-item-bg {
position: absolute;
top: 0;
left: 0;
z-index: 0;
border-radius: 8px;
width: 128px;
height: 56px;
}
.quick-access-item-title {
display: flex;
align-items: center;
z-index: 1;
image {
width: 16px;
height: 16px;
margin-right: 4px;
}
text {
font-family: PingFang SC, PingFang SC;
font-weight: 500;
font-size: 12px;
color: #201f32;
line-height: 16px;
}
}
.quick-access-item-content {
z-index: 1;
margin-top: 4px;
font-family: PingFang SC, PingFang SC;
font-weight: 400;
font-size: 10px;
color: #678cad;
line-height: 18px;
}
}
}

View File

@@ -0,0 +1,9 @@
<template>
<view class="top-bg"> </view>
</template>
<script></script>
<style lang="scss" scoped>
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,11 @@
.top-bg {
width: 100%;
height: 270px;
overflow: hidden;
background: linear-gradient(180deg, #42adf9 0%, #6cd1ff 51%, #e9f3f7 99%);
.top-bg-img {
width: 100%;
height: 100%;
}
}

View File

@@ -0,0 +1,37 @@
<template>
<view class="nav-bar">
<view class="nav-item" @click="showDrawer('showLeft')">
<uni-icons type="bars" size="24" color="#333"></uni-icons>
</view>
<uni-drawer ref="showLeft" mode="left" :width="320">
<DrawerHome @closeDrawer="closeDrawer('showLeft')" />
</uni-drawer>
</view>
</template>
<script setup>
import { ref } from "vue";
import DrawerHome from "../../drawer/DrawerHome/index.vue";
import { checkToken } from "@/hooks/useGoLogin";
const showLeft = ref(false);
// 打开窗口
const showDrawer = async (e) => {
await checkToken();
showLeft.value.open();
// 发送抽屉显示事件
uni.$emit("drawerShow");
};
// 关闭窗口
const closeDrawer = (e) => {
showLeft.value.close();
// 发送抽屉隐藏事件
uni.$emit("drawerHide");
};
</script>
<style lang="scss" scoped>
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,16 @@
.nav-bar {
display: flex;
align-items: center;
height: 44px;
padding: 0 15px;
.nav-item {
width: 24px;
height: 24px;
margin-right: 10px;
}
.nav-item-icon {
width: 100%;
height: 100%;
}
}

View File

@@ -0,0 +1,53 @@
<template>
<view class="top-bg-content">
<view class="top-item">
<!-- :style="backgroundStyle" -->
<image
class="top-item-left"
:src="initPageImages.welcomeImageUrl"
mode="aspectFit"
></image>
<image
class="top-item-right"
:src="initPageImages.logoImageUrl"
mode="aspectFit"
></image>
</view>
<ChatCardAI v-if="welcomeContent.length" :text="welcomeContent" />
</view>
</template>
<script setup>
import { defineProps, computed } from "vue";
import ChatCardAI from "../ChatCardAi/index.vue";
const props = defineProps({
initPageImages: {
type: Object,
default: {
backgroundImageUrl: "",
logoImageUrl: "",
welcomeImageUrl: "",
},
},
welcomeContent: {
type: String,
default:
"查信息、预定下单、探索玩法、呼叫服务、我通通可以满足,快试试问我问题吧!",
},
});
// 计算背景样式
const backgroundStyle = computed(() => {
return {
backgroundImage: `url(${props.initPageImages.backgroundImageUrl})`,
backgroundSize: "cover",
backgroundPosition: "center",
backgroundRepeat: "no-repeat",
};
});
</script>
<style lang="scss" scoped>
@use "./styles/index.scss";
</style>

View File

@@ -0,0 +1,25 @@
.top-bg-content {
display: flex;
justify-content: flex-end;
align-items: stretch;
flex-direction: column;
}
.top-item {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
padding: 0 32px;
margin-bottom: -6px;
}
.top-item-left {
width: 118px;
height: 52px;
}
.top-item-right {
width: 130px;
height: 130px;
}