This commit is contained in:
lik
2026-06-08 12:01:40 +08:00
parent 010cf160a0
commit 894a9881d7
51 changed files with 2667 additions and 740 deletions

View File

@@ -1,66 +1,237 @@
// pages/ai/index.js
const AIChatSocket = require('../../utils/chatmsg.js')
Page({
/**
* 页面的初始数据
*/
data: {
messages: [],
inputValue: '',
isTyping: false,
scrollToMessage: '',
quickQuestions: [
'今日待处理订单有哪些?',
'最近客户反馈统计',
'如何修改服务价格?',
'陪诊员排班情况'
]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(options) {
messageIdCounter: 0,
socket: null,
onLoad() {
this.loadChatHistory()
this.initSocket()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
if (this.socket) {
this.socket.close()
this.socket = null
}
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
initSocket() {
this.socket = new AIChatSocket()
this.socket.onOpen(() => {
console.log('[AIChat] Socket opened')
})
this.socket.onMessage((data) => {
if (data && data.type === 'ai') {
this.handleAIReply(data)
} else if (data && data.type === 'system') {
console.log('[AIChat] System:', data.content)
}
})
this.socket.onError((err) => {
console.error('[AIChat] WebSocket error', err)
this.handleAIError('网络连接失败,请检查网络设置')
})
this.socket.onClose((res) => {
console.log('[AIChat] Socket closed', res)
})
this.socket.connect().catch((err) => {
console.error('[AIChat] Connect failed', err)
})
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
handleAIReply(data) {
let messages = null
if (this.data.messages.length > 0) {
let lastMessage = this.data.messages[this.data.messages.length - 1]
if (lastMessage.type === 'ai' && lastMessage._serverId === data.id) {
lastMessage.content += data.content || ''
messages = this.data.messages
}
}
if (!messages) {
const aiResponse = {
id: `msg_${++this.messageIdCounter}`,
_serverId: data.id,
type: 'ai',
contentType: 'text',
content: data.content || '',
time: this.formatTime(new Date())
}
if (data.sessionId) {
wx.setStorageSync('admin_ai_session_id', data.sessionId)
}
messages = [...this.data.messages, aiResponse]
}
this.setData({
messages: messages,
isTyping: false
})
this.saveChatHistory(messages)
this.scrollToBottom()
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
loadChatHistory() {
try {
const history = wx.getStorageSync('admin_ai_chat_history')
if (history && history.length > 0) {
this.setData({ messages: history })
this.scrollToBottom()
}
} catch (e) {
console.log('加载聊天记录失败', e)
}
},
saveChatHistory(messages) {
try {
wx.setStorageSync('admin_ai_chat_history', messages)
} catch (e) {
console.log('保存聊天记录失败', e)
}
},
onInputChange(e) {
const value = e.detail.value
this.setData({
inputValue: value,
canSend: !!value.trim()
})
},
onQuickQuestionTap(e) {
const question = e.currentTarget.dataset.question
this.setData({ inputValue: question, canSend: true })
this.sendMessage()
},
sendMessage() {
const content = this.data.inputValue.trim()
if (!content) return
const userMessage = {
id: `msg_${++this.messageIdCounter}`,
type: 'user',
contentType: 'text',
content: content,
time: this.formatTime(new Date())
}
const messages = [...this.data.messages, userMessage]
this.setData({
messages: messages,
inputValue: '',
canSend: false,
isTyping: true
})
this.saveChatHistory(messages)
this.scrollToBottom()
this.sendToAI(content)
},
sendToAI(content, type = 'chat') {
const app = getApp()
const user = app.globalData.user
if (!this.socket) {
this.handleAIError('网络连接失败,请检查网络设置')
return
}
if (!this.socket.isConnected) {
this.socket.connect().then(() => {
this._doSend(type, content, user, app)
}).catch((err) => {
console.error('[AIChat] Reconnect failed', err)
this.handleAIError('网络连接失败,请检查网络设置')
})
} else {
this._doSend(type, content, user, app)
}
},
_doSend(type, content, user, app) {
this.socket.send({
type: type,
content: content,
userId: user ? user._id : '',
token: user ? user.security.token : '',
appId: app.globalData.appId || '',
agent: 'escort-admin'
})
},
handleAIError(errorMessage) {
const errorResponse = {
id: `msg_${++this.messageIdCounter}`,
type: 'ai',
contentType: 'text',
content: errorMessage,
time: this.formatTime(new Date())
}
const messages = [...this.data.messages, errorResponse]
this.setData({
messages: messages,
isTyping: false
})
this.saveChatHistory(messages)
this.scrollToBottom()
},
scrollToBottom() {
setTimeout(() => {
const lastMessage = this.data.messages[this.data.messages.length - 1]
if (lastMessage) {
this.setData({
scrollToMessage: `msg-${lastMessage.id}`
})
}
}, 100)
},
formatTime(date) {
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${hours}:${minutes}`
},
clearChat() {
wx.showModal({
title: '确认清空',
content: '确定要清空所有聊天记录吗?',
success: (res) => {
if (res.confirm) {
this.sendToAI('clear', 'clear')
this.setData({ messages: [] })
wx.removeStorageSync('admin_ai_chat_history')
wx.removeStorageSync('admin_ai_session_id')
}
}
})
}
})
})

View File

@@ -1,3 +1,9 @@
{
"usingComponents": {}
}
"navigationBarTitleText": "AI助手",
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "black",
"backgroundColor": "#ffffff",
"usingComponents": {
"t-chat-markdown": "tdesign-miniprogram/chat-markdown/chat-markdown"
}
}

View File

@@ -1,2 +1,66 @@
<!--pages/ai/index.wxml-->
<text>pages/ai/index.wxml</text>
<view class="chat-container">
<scroll-view class="message-list" scroll-y scroll-into-view="{{scrollToMessage}}" scroll-with-animation>
<view class="quick-questions" wx:if="{{messages.length === 0}}">
<view class="welcome-text">您好我是您的AI助手有什么可以帮您</view>
<view class="quick-list">
<view class="quick-item" wx:for="{{quickQuestions}}" wx:key="*this" data-question="{{item}}" bindtap="onQuickQuestionTap">
{{item}}
</view>
</view>
</view>
<view class="message-item {{item.type}}" wx:for="{{messages}}" wx:key="id" id="msg-{{item.id}}">
<view class="avatar {{item.type}}-avatar">
<text class="avatar-text">{{item.type === 'user' ? '我' : 'AI'}}</text>
</view>
<view class="message-content">
<view class="message-bubble {{item.type}}-bubble">
<t-chat-markdown
wx:if="{{item.contentType === 'text' && item.type === 'ai'}}"
class="message-markdown"
content="{{item.content}}"
/>
<text class="message-text" wx:elif="{{item.contentType === 'text'}}">{{item.content}}</text>
</view>
<text class="message-time" wx:if="{{item.time}}">{{item.time}}</text>
</view>
</view>
<view class="typing-indicator" wx:if="{{isTyping}}">
<view class="avatar ai-avatar">
<text class="avatar-text">AI</text>
</view>
<view class="typing-bubble">
<view class="dot"></view>
<view class="dot"></view>
<view class="dot"></view>
</view>
</view>
</scroll-view>
<view class="chat-footer">
<view class="chat-toolbar" wx:if="{{messages.length > 0}}">
<view class="chat-toolbar-action" bindtap="clearChat">
<text>清空记录</text>
</view>
</view>
<view class="input-area">
<input
class="chat-input"
type="text"
placeholder="请输入您的问题..."
value="{{inputValue}}"
bindinput="onInputChange"
confirm-type="send"
bindconfirm="sendMessage"
adjust-position="{{true}}"
cursor-spacing="20"
hold-keyboard="{{true}}"
/>
<view class="send-btn {{canSend ? 'active' : ''}}" bindtap="sendMessage">
<text class="send-text">发送</text>
</view>
</view>
</view>
</view>

View File

@@ -1 +1,367 @@
/* pages/ai/index.wxss */
page {
background-color: #f5f6fa;
color: #1a1a2e;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}
.chat-container {
display: flex;
flex-direction: column;
height: 100vh;
background-color: #f5f6fa;
}
.chat-header {
display: flex;
align-items: center;
justify-content: space-between;
height: 88rpx;
padding: 0 24rpx;
background-color: #ffffff;
border-bottom: 1rpx solid #e5e7eb;
flex-shrink: 0;
}
.chat-header-title {
font-size: 30rpx;
font-weight: 600;
color: #1a1a2e;
}
.message-list {
flex: 1;
padding: 20rpx;
padding-bottom: 200rpx;
box-sizing: border-box;
overflow: hidden;
}
.quick-questions {
display: flex;
flex-direction: column;
align-items: center;
padding: 40rpx 20rpx;
}
.welcome-text {
font-size: 32rpx;
color: #1a1a2e;
margin-bottom: 40rpx;
text-align: center;
font-weight: 500;
}
.quick-list {
display: flex;
flex-direction: column;
width: 100%;
gap: 20rpx;
}
.quick-item {
background-color: #ffffff;
border-radius: 16rpx;
padding: 24rpx 32rpx;
font-size: 28rpx;
color: #4c6ef5;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
text-align: center;
border: 1rpx solid #e5e7eb;
transition: all 0.2s ease;
}
.quick-item:active {
transform: scale(0.98);
background-color: rgba(76, 110, 245, 0.05);
}
.message-item {
display: flex;
flex-direction: column;
margin-bottom: 32rpx;
}
.message-item.ai {
align-items: flex-start;
}
.message-item.user {
align-items: flex-end;
}
.message-time {
font-size: 22rpx;
color: #9ca3af;
margin-top: 8rpx;
padding: 0 4rpx;
}
.message-item.ai .message-time {
text-align: left;
align-self: flex-start;
}
.message-item.user .message-time {
text-align: right;
align-self: flex-end;
}
.avatar {
width: 64rpx;
height: 64rpx;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
margin-bottom: 12rpx;
}
.user-avatar {
background: linear-gradient(135deg, #4c6ef5, #748ffc);
box-shadow: 0 4rpx 12rpx rgba(76, 110, 245, 0.25);
}
.ai-avatar {
background: linear-gradient(135deg, #20c997, #51cf66);
box-shadow: 0 4rpx 12rpx rgba(32, 201, 151, 0.25);
}
.avatar-text {
color: #fff;
font-size: 26rpx;
font-weight: 500;
}
.message-content {
display: flex;
flex-direction: column;
max-width: 95%;
}
.message-item.user .message-content {
align-items: flex-end;
}
.message-item.ai .message-content {
align-items: flex-start;
}
.message-bubble {
padding: 20rpx 24rpx;
border-radius: 16rpx;
font-size: 28rpx;
line-height: 1.6;
word-break: break-word;
max-width: 100%;
}
.user-bubble {
background: linear-gradient(135deg, #4c6ef5, #748ffc);
color: #fff;
border-bottom-right-radius: 4rpx;
box-shadow: 0 4rpx 12rpx rgba(76, 110, 245, 0.2);
margin-right: 4rpx;
}
.ai-bubble {
background-color: #ffffff;
color: #1a1a2e;
border-bottom-left-radius: 4rpx;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
border: 1rpx solid #e5e7eb;
margin-left: 4rpx;
}
/* Markdown 渲染区域 */
.message-markdown {
width: 100%;
font-size: 28rpx;
color: #1a1a2e;
line-height: 1.6;
}
/* 表格样式覆盖(防止过宽) */
.message-markdown .t-chat-markdown-table {
width: 100%;
max-width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
border: 1rpx solid #e5e7eb;
border-radius: 8rpx;
}
.message-markdown .t-chat-markdown-table__container {
display: table;
min-width: 100%;
max-width: max-content;
border-collapse: collapse;
white-space: normal;
table-layout: fixed;
word-break: break-word;
}
.message-markdown .t-chat-markdown-table__th,
.message-markdown .t-chat-markdown-table__td {
padding: 8rpx 12rpx;
font-size: 24rpx;
line-height: 1.4;
white-space: normal;
word-break: break-word;
word-wrap: break-word;
overflow-wrap: break-word;
max-width: 320rpx;
}
.message-markdown .t-chat-markdown-table__th {
background-color: #f5f6fa;
font-weight: 600;
color: #1a1a2e;
}
.message-markdown .t-chat-markdown-table__tr:nth-child(2n) {
background-color: #fafbfc;
}
/* 代码块样式覆盖 */
.message-markdown .t-chat-markdown-codespan,
.message-markdown .t-chat-markdown-code {
font-size: 24rpx;
word-break: break-all;
}
.typing-indicator {
display: flex;
flex-direction: column;
align-items: flex-start;
margin-bottom: 32rpx;
}
.typing-bubble {
display: flex;
align-items: center;
gap: 12rpx;
background-color: #ffffff;
padding: 24rpx 32rpx;
border-radius: 16rpx;
border-bottom-left-radius: 4rpx;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
border: 1rpx solid #e5e7eb;
}
.dot {
width: 16rpx;
height: 16rpx;
background-color: #9ca3af;
border-radius: 50%;
animation: bounce 1.4s infinite ease-in-out both;
}
.dot:nth-child(1) {
animation-delay: -0.32s;
}
.dot:nth-child(2) {
animation-delay: -0.16s;
}
@keyframes bounce {
0%, 80%, 100% {
transform: scale(0.6);
}
40% {
transform: scale(1);
}
}
.input-area {
display: flex;
align-items: center;
padding: 20rpx 24rpx;
background-color: #ffffff;
gap: 16rpx;
box-sizing: border-box;
}
.chat-footer {
position: fixed;
left: 0;
right: 0;
bottom: 0;
z-index: 10;
background-color: #ffffff;
}
.chat-toolbar {
display: flex;
align-items: right;
justify-content: right;
padding: 12rpx 24rpx;
background-color: #f5f6fa;
border-top: 1rpx solid #e5e7eb;
border-bottom: 1rpx solid #e5e7eb;
}
.chat-toolbar-action {
display: flex;
align-items: right;
justify-content: right;
padding: 6rpx 24rpx;
border-radius: 24rpx;
background-color: #ffffff;
border: 1rpx solid #e5e7eb;
transition: all 0.2s ease;
}
.chat-toolbar-action:active {
transform: scale(0.96);
background-color: rgba(76, 110, 245, 0.08);
border-color: #4c6ef5;
}
.chat-toolbar-action text {
font-size: 24rpx;
color: #6b7280;
}
.chat-input {
flex: 1;
height: 72rpx;
background-color: #f5f6fa;
border-radius: 36rpx;
padding: 0 28rpx;
font-size: 28rpx;
color: #1a1a2e;
border: 1rpx solid #e5e7eb;
}
.chat-input::placeholder {
color: #9ca3af;
}
.send-btn {
width: 120rpx;
height: 72rpx;
background-color: #e5e7eb;
border-radius: 36rpx;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
}
.send-btn.active {
background: linear-gradient(135deg, #4c6ef5, #748ffc);
box-shadow: 0 4rpx 12rpx rgba(76, 110, 245, 0.25);
}
.send-text {
color: #9ca3af;
font-size: 28rpx;
font-weight: 500;
transition: color 0.2s ease;
}
.send-btn.active .send-text {
color: #FFFFFF;
}