Files
lucky_shop/pages_tool/ai-chat/index.vue

614 lines
16 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<view class="container" :style="wrapperPageStyle">
<!--自定义导航头部 -->
<view class="custom-navbar" ref="pageHeader" v-if="showCustomNavbar">
<view class="header-left">
<button class="back-btn" v-show="showBackButton" @click="goBack">
<text class="iconfont icon-back"></text>
</button>
<!-- 占位元素确保布局平衡 -->
<view v-show="!showBackButton" class="placeholder"></view>
</view>
<view class="header-center">
<text class="header-subtitle">在线为您服务</text>
</view>
<view class="header-right">
<button class="menu-btn" v-show="showMenuButton" @click="showMenu">
<text class="iconfont icon-ellipsis"></text>
</button>
<!-- 占位元素确保布局平衡 -->
<view v-show="!showMenuButton" class="placeholder"></view>
</view>
</view>
<!-- 聊天内容区域 -->
<view class="chat-content"
:style="wrapperChatContentStyle"
>
<!-- AI聊天组件 -->
<ai-chat-message
ref="chat"
:initial-messages="initialMessages"
:user-avatar="userAvatar"
:ai-avatar="aiAvatar"
@message-sent="onMessageSent"
@ai-response="onAIResponse"
@action-click="onActionClick"
@history-loaded="onHistoryLoaded"
@file-preview="onFilePreview"
@audio-play="onAudioPlay"
@audio-pause="onAudioPause"
@video-play="onVideoPlay"
@video-pause="onVideoPause"
@link-open="onLinkOpen"
@product-view="onProductView"
@input-change="onInputChange" />
</view>
</view>
</template>
<script>
import { mapGetters, mapMutations } from 'vuex'
import navigationHelper from '@/common/js/navigation';
import { EventSafety } from '@/common/js/event-safety';
export default {
data() {
return {
initialMessages: [
{
id: 1,
role: 'ai',
type: 'text',
content: '您好我是AI智能客服很高兴为您服务\n\n我可以帮您\n• 解答产品相关问题\n• 处理订单问题\n• 提供技术支持\n• 推荐相关商品\n\n请告诉我您需要什么帮助',
timestamp: Date.now() - 60000,
actions: [
{ type: 'like', icon: 'icon-dianzan1', text: '喜欢', count: 0 },
{ type: 'dislike', icon: 'icon-dianzan1', text: '不喜欢', count: 0 }
]
}
],
// --- 系统导航栏/状态栏相关 ---
navBarHeight: 44, // uni-page-head 系统导航栏默认高度为44px
statusBarHeight: 0, // 状态栏高度默认0
// --- 自定义导航栏 ---
showCustomNavbar: true, // 是否显示自定义导航栏
showBackButton: false, // 是否显示返回按钮
showMenuButton: true, // 是否显示设置菜单按钮
// --- 聊天内容区域 ---
scrollViewHeight: '0px',
// 事件处理器引用(用于清理)
safeEventHandlers: new Map()
}
},
computed: {
...mapGetters([
'globalAIKefuConfig'
]),
/// ---- 关于AI客服的配置支持远程配置 ----
userAvatar() {
return this.globalAIKefuConfig?.userAvatar || '/static/images/user-avatar.png'
},
aiAvatar() {
return this.globalAIKefuConfig?.aiAvatar || '/static/images/ai-avatar.png'
},
/// ---- others ----
containerHeight() {
return `calc(100vh - $ {this.navBarHeight + this.statusBarHeight}px)`
},
wrapperPageStyle() {
// #ifdef H5
return `top: $ {this.navBarHeight + 'px'};`
// #endif
// #ifdef MP-WEIXIN
return `top: -1px;` // 微信小程序需要上移1px, 否则与系统导航栏出现1px的空隙
// #endif
return ``
},
wrapperChatContentStyle() {
return {
height: this.containerHeight,
paddingTop: this.showCustomNavbar ? '0' : (this.navBarHeight + 'px')
}
}
},
async onLoad(options) {
// ✅ 新增:权限校验(关键!防止非 AI 类型进入)
const hasAccess = this.checkAccessPermission();
if (!hasAccess) {
// 如果校验失败,不继续初始化
return;
}
this. $langConfig.title('AI智能客服');
this.initChat();
},
async onReady() {
await this.initNavigation();
},
onShow() {
// 可在此补充逻辑(如刷新未读数)
},
onHide() {
// 页面隐藏时可暂停音频等
},
onUnload() {
this.cleanup();
},
methods: {
// ========== 安全事件处理 ==========
setupSafeEventListeners() {
const safeHandlers = {
serviceRequest: EventSafety.wrapEventHandler(
this.handleServiceRequest.bind(this),
{ onError: this.handleEventError.bind(this) }
),
navigationRequest: EventSafety.wrapEventHandler(
this.handleNavigationRequest.bind(this),
{ onError: this.handleEventError.bind(this) }
),
componentInteraction: EventSafety.wrapEventHandler(
this.handleComponentInteraction.bind(this),
{ onError: this.handleEventError.bind(this) }
)
}
this. $on('service.requestComponentInfo', safeHandlers.serviceRequest);
this. $on('navigation.requestInfo', safeHandlers.navigationRequest);
this. $on('component.interaction', safeHandlers.componentInteraction);
this.safeEventHandlers.set('serviceRequest', safeHandlers.serviceRequest);
this.safeEventHandlers.set('navigationRequest', safeHandlers.navigationRequest);
this.safeEventHandlers.set('componentInteraction', safeHandlers.componentInteraction);
},
setupNavigationEvents() {
uni.onWindowResize((res) => {
console.log('窗口大小变化:', res.size);
this.calculateScrollViewHeight();
});
},
// ========== 事件处理方法 ==========
async handleServiceRequest(event) {
console.log('处理服务请求:', EventSafety.extractEventData(event));
if (event.matches('.service-component') ||
event.detail?.componentType === 'service') {
await this.processServiceRequest(event);
}
},
async handleNavigationRequest(event) {
console.log('处理导航请求:', event.type);
this.emitNavigationInfo(event);
},
handleComponentInteraction(event) {
console.log('处理组件交互:', event.detail);
this.processComponentInteraction(event);
},
handleEventError(error, event) {
console.error('事件处理错误:', {
error: error.message,
eventType: event?.type,
component: this. $options.name
});
this.showError('操作失败,请重试');
},
// ========== 初始化页面 ==========
initChat() {
console.log('AI聊天页面初始化');
},
async initNavigation() {
try {
this.navBarHeight = await navigationHelper.getNavigationHeight(this, {forceRefresh: false});
this.statusBarHeight = navigationHelper.getStatusBarHeight();
this.calculateScrollViewHeight();
this.setupNavigationEvents();
} catch (error) {
console.error('初始化导航栏失败:', error);
this.setFallbackNavigationValues();
}
},
calculateScrollViewHeight() {
const safeArea = navigationHelper.getSafeAreaInsets();
const bottomInset = safeArea.bottom || 0;
const inputHeight = 120;
this.scrollViewHeight = `calc(100vh - $ {this.navBarHeight + this.statusBarHeight + inputHeight + bottomInset}px)`;
},
setFallbackNavigationValues() {
// #ifdef MP-WEIXIN
this.navBarHeight = 44;
this.statusBarHeight = 20;
// #endif
// #ifdef H5
this.navBarHeight = 44;
this.statusBarHeight = 0;
// #endif
// #ifdef APP-PLUS
this.navBarHeight = 88;
this.statusBarHeight = 44;
// #endif
},
cleanup() {
this.safeEventHandlers.forEach((handler, eventType) => {
this. $off(eventType, handler);
});
this.safeEventHandlers.clear();
console.log('组件清理完成');
},
showError(message) {
uni.showToast({
title: message,
icon: 'none',
duration: 2000
});
},
// 返回上一页
goBack() {
uni.navigateBack();
},
// 显示菜单
showMenu() {
uni.showActionSheet({
itemList: ['清空聊天', '导出记录', '设置', '帮助'],
success: (res) => {
switch (res.tapIndex) {
case 0:
this.clearChat();
break;
case 1:
this.exportChat();
break;
case 2:
this.showSettings();
break;
case 3:
this.showHelp();
break;
}
}
});
},
clearChat() {
uni.showModal({
title: '提示',
content: '确定要清空聊天记录吗?',
success: (res) => {
if (res.confirm) {
this. $refs.chat.clearMessages();
this. $refs.chat.addMessage({
id: Date.now(),
role: 'ai',
type: 'text',
content: '聊天记录已清空,有什么可以帮助您的吗?',
timestamp: Date.now()
});
}
}
});
},
exportChat() {
uni.showToast({
title: '功能开发中',
icon: 'none'
});
},
showSettings() {
uni.navigateTo({
url: '/pages/settings/index'
});
},
showHelp() {
const helpMessage = {
id: Date.now(),
role: 'ai',
type: 'markdown',
content: `# 使用帮助
## 基本功能
- **发送消息**: 在输入框中输入文字后发送
- **语音输入**: 点击麦克风图标进行语音输入
- **附件发送**: 点击+号可以发送图片、文件、位置
## 消息类型
- **文本消息**: 普通文字对话
- **Markdown**: 支持格式化的文档内容
- **文件**: 支持各种文件格式预览
- **音频**: 支持语音消息播放
- **视频**: 支持视频播放
- **链接**: 支持网页链接跳转
- **商品**: 支持商品卡片展示
## 操作功能
- **点赞/踩**: 对AI回复进行评价
- **复制**: 长按消息可复制内容
- **转发**: 支持消息转发功能`,
timestamp: Date.now()
};
this. $refs.chat.addMessage(helpMessage);
},
onMessageSent(message) {
console.log('用户发送消息:', message);
},
onAIResponse(message) {
console.log('AI回复消息:', message);
},
generateAIResponse(userMessage) {
const responses = [
'我理解您的需求,让我为您详细解答。',
'感谢您的提问,这是一个很好的问题。',
'根据您的问题,我建议您可以考虑以下几个方面:',
'这个问题很常见,让我为您提供一些解决方案。',
'我明白您的困惑,让我帮您分析一下。'
];
const randomResponse = responses[Math.floor(Math.random() * responses.length)];
const aiMessage = {
id: Date.now(),
role: 'ai',
type: 'text',
content: ` $ {randomResponse}\n\n您的问题" $ {userMessage.content}"我已经收到,正在为您处理中...`,
timestamp: Date.now(),
actions: [
{ type: 'like', count: 0 },
{ type: 'dislike', count: 0 }
]
};
this. $refs.chat.addMessage(aiMessage);
this. $emit('ai-response', aiMessage);
},
onActionClick({ action, message }) {
switch (action.type) {
case 'like':
uni.showToast({ title: '感谢您的反馈!', icon: 'success' });
break;
case 'dislike':
uni.showToast({ title: '我们会改进服务', icon: 'none' });
break;
}
},
onHistoryLoaded(messages) {
console.log('历史消息加载完成:', messages.length);
},
onFilePreview(message) {
uni.showToast({ title: '打开文件: ' + message.fileName, icon: 'none' });
},
onAudioPlay(message) {
console.log('音频播放:', message);
},
onAudioPause(message) {
console.log('音频暂停:', message);
},
onVideoPlay(message) {
console.log('视频播放:', message);
},
onVideoPause(message) {
console.log('视频暂停:', message);
},
onLinkOpen(message) {
uni.showModal({
title: '打开链接',
content: `确定要打开链接: $ {message.url} 吗?`,
success: (res) => {
if (res.confirm) {
// #ifdef H5
window.open(message.url, '_blank');
// #endif
// #ifdef APP-PLUS
plus.runtime.openURL(message.url);
// #endif
}
}
});
},
onProductView(message) {
uni.showToast({ title: '查看商品: ' + message.title, icon: 'none' });
},
onInputChange(value) {
console.log('输入内容:', value);
},
// ✅ 新增:权限校验(核心修复)
checkAccessPermission() {
const servicerConfig = this. $store.state.servicerConfig;
// 如果配置未加载延迟重试最多3次防白屏
if (!servicerConfig) {
console.warn('【AI客服】servicerConfig 未加载200ms后重试...');
setTimeout(() => {
this.checkAccessPermission();
}, 200);
return false;
}
let currentType = 'none';
// #ifdef MP-WEIXIN
currentType = servicerConfig?.weapp?.type || 'none';
// #endif
// #ifdef H5
currentType = servicerConfig?.h5?.type || 'none';
// #endif
if (currentType !== 'aikefu') {
uni.showToast({ title: '当前客服类型不支持此页面', icon: 'none' });
setTimeout(() => {
const pages = getCurrentPages();
if (pages.length > 1) {
uni.navigateBack();
} else {
// 回到首页(假设首页是 tab 页)
uni.switchTab({ url: '/pages/index/index' });
}
}, 1500);
return false;
}
return true;
}
}
}
</script>
<style lang="scss">
/* 引入图标字体 */
@import url('/common/css/iconfont.css');
/* 页面样式 */
.container {
display: flex;
flex-direction: column;
background-color: white; /* 白色 */
overflow: hidden;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
/* 自定义导航头部 */
.custom-navbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx 30rpx;
background-color: #c4e0ff; /* 浅蓝色 */
border-bottom: 2rpx solid #eeeeee;
.header-left {
flex: 0 0 auto;
display: flex;
align-items: center;
.back-btn {
width: 60rpx;
height: 60rpx;
border-radius: 50%;
background-color: #ffffff; /* 白色按钮 */
display: flex;
align-items: center;
justify-content: center;
.iconfont {
font-size: 32rpx;
color: #666;
}
}
.placeholder {
width: 120rpx;
height: 60rpx;
}
}
.header-center {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
gap: 20rpx;
.header-title {
font-size: 36rpx;
font-weight: bold;
color: #333;
}
.header-subtitle {
font-size: 24rpx;
color: #999;
}
}
.header-right {
flex: 0 0 auto;
display: flex;
align-items: center;
.menu-btn {
width: 60rpx;
height: 60rpx;
border-radius: 50%;
background-color: #ffffff; /* 白色按钮 */
display: flex;
align-items: center;
justify-content: center;
.iconfont {
font-size: 32rpx;
color: #666;
}
}
.placeholder {
width: 120rpx;
height: 60rpx;
}
}
}
/* 聊天内容区域 */
.chat-content {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
/* 底部tabBar占位样式 */
.page-bottom {
width: 100%;
background-color: transparent;
}
</style>