feat(小程序): 优化玩伴会话与家长发消息
This commit is contained in:
@@ -1,83 +1,162 @@
|
||||
import { View, Text, ScrollView, Image } from '@tarojs/components'
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { View, Text, ScrollView, Image, Input } from '@tarojs/components'
|
||||
import { useEffect, useState } from 'react'
|
||||
import Taro, { useRouter } from '@tarojs/taro'
|
||||
import { getMessages, getCharacter, ChatMessage, Character } from '../../../services/chat'
|
||||
import {
|
||||
getMessages,
|
||||
getCharacter,
|
||||
sendParentMessage,
|
||||
ChatMessage,
|
||||
Character,
|
||||
ConversationSource,
|
||||
PeerKind,
|
||||
} from '../../../services/chat'
|
||||
import './index.scss'
|
||||
|
||||
function normalizePeerKind(value?: string): PeerKind {
|
||||
if (value === 'child' || value === 'parent' || value === 'ai') return value
|
||||
return 'ai'
|
||||
}
|
||||
|
||||
function normalizeSource(value?: string): ConversationSource {
|
||||
return value === 'im' ? 'im' : 'ai'
|
||||
}
|
||||
|
||||
function normalizeNumericId(value?: string): number | null {
|
||||
const normalized = Number(value)
|
||||
if (!Number.isFinite(normalized) || normalized <= 0) return null
|
||||
return normalized
|
||||
}
|
||||
|
||||
function formatParticipantLabel(message: ChatMessage): string {
|
||||
const senderType = message.senderType || 'unknown'
|
||||
const senderId = message.senderId || '--'
|
||||
const name = message.senderName || ''
|
||||
|
||||
if (senderType === 'parent') {
|
||||
return name === '我' ? '我' : name || '家长'
|
||||
}
|
||||
if (senderType === 'child') {
|
||||
return name || `儿童ID ${senderId}`
|
||||
}
|
||||
if (senderType === 'device') {
|
||||
return name || `设备ID ${senderId}`
|
||||
}
|
||||
if (senderType === 'ai') {
|
||||
return name || 'AI'
|
||||
}
|
||||
return `${senderType} ${senderId}`
|
||||
}
|
||||
|
||||
export default function ChatDetail() {
|
||||
const router = useRouter()
|
||||
const { id } = router.params
|
||||
const conversationId = parseInt(id || '1')
|
||||
const params = router.params
|
||||
|
||||
const initialConversationId = normalizeNumericId(params.id) || 0
|
||||
const conversationSource = normalizeSource(params.source)
|
||||
const conversationPeerKind = normalizePeerKind(params.peerKind)
|
||||
const decodedRoleKey = decodeURIComponent(params.roleKey || '')
|
||||
const decodedName = decodeURIComponent(params.name || '玩伴')
|
||||
const decodedConversationTypeName = decodeURIComponent(params.conversationTypeName || '')
|
||||
const decodedPeerId = decodeURIComponent(params.peerId || '')
|
||||
const decodedDeviceId = decodeURIComponent(params.deviceId || '')
|
||||
const decodedChildName = decodeURIComponent(params.childName || '')
|
||||
const childId = normalizeNumericId(params.childId)
|
||||
const parentUserId = normalizeNumericId(params.parentUserId)
|
||||
const canSend = params.canSend === '1'
|
||||
|
||||
const [activeConversationId, setActiveConversationId] = useState(initialConversationId)
|
||||
const [character, setCharacter] = useState<Character>({
|
||||
id: conversationId,
|
||||
name: decodeURIComponent(router.params.name || 'AI 玩伴'),
|
||||
description: '温柔音色 / 开朗耐心',
|
||||
icon: '🎤'
|
||||
id: initialConversationId,
|
||||
name: decodedName,
|
||||
description: '交流记录',
|
||||
icon: '🤖',
|
||||
source: conversationSource,
|
||||
peerKind: conversationPeerKind,
|
||||
conversationTypeName: decodedConversationTypeName,
|
||||
childId,
|
||||
childName: decodedChildName,
|
||||
peerId: decodedPeerId,
|
||||
parentUserId,
|
||||
deviceId: decodedDeviceId,
|
||||
channelLabel: '--',
|
||||
canSend,
|
||||
})
|
||||
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([])
|
||||
const [playingId, setPlayingId] = useState<number | null>(null)
|
||||
const audioCtx = useRef<Taro.InnerAudioContext | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [inputText, setInputText] = useState('')
|
||||
const [sending, setSending] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
loadChatData()
|
||||
return () => {
|
||||
// 页面卸载时销毁音频
|
||||
audioCtx.current?.destroy()
|
||||
void loadChatData(activeConversationId)
|
||||
}, [activeConversationId, conversationSource, conversationPeerKind])
|
||||
|
||||
const loadChatData = async (conversationId: number) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const char = await getCharacter({
|
||||
conversationId,
|
||||
source: conversationSource,
|
||||
peerKind: conversationPeerKind,
|
||||
name: decodedName,
|
||||
roleKey: decodedRoleKey,
|
||||
conversationTypeName: decodedConversationTypeName,
|
||||
childId,
|
||||
childName: decodedChildName,
|
||||
peerId: decodedPeerId,
|
||||
parentUserId,
|
||||
deviceId: decodedDeviceId,
|
||||
canSend,
|
||||
})
|
||||
if (char) {
|
||||
setCharacter(char)
|
||||
Taro.setNavigationBarTitle({ title: char.name })
|
||||
}
|
||||
const msgs = await getMessages(conversationId, conversationSource, decodedConversationTypeName)
|
||||
setMessages(msgs)
|
||||
} catch (error: any) {
|
||||
console.error('[chat-detail] load failed:', error)
|
||||
Taro.showToast({
|
||||
title: error?.message || '加载失败,请稍后重试',
|
||||
icon: 'none',
|
||||
})
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [conversationId])
|
||||
|
||||
const loadChatData = async () => {
|
||||
const char = await getCharacter(conversationId)
|
||||
if (char) {
|
||||
setCharacter(char)
|
||||
Taro.setNavigationBarTitle({ title: char.name })
|
||||
}
|
||||
const msgs = await getMessages(conversationId)
|
||||
setMessages(msgs)
|
||||
}
|
||||
|
||||
const handlePlayAudio = (msg: ChatMessage) => {
|
||||
if (!msg.audioUrl) return
|
||||
|
||||
// 如果点的是正在播放的那条,就停止
|
||||
if (playingId === msg.id) {
|
||||
audioCtx.current?.stop()
|
||||
audioCtx.current?.destroy()
|
||||
audioCtx.current = null
|
||||
setPlayingId(null)
|
||||
return
|
||||
}
|
||||
|
||||
// 停掉上一条
|
||||
audioCtx.current?.stop()
|
||||
audioCtx.current?.destroy()
|
||||
|
||||
const ctx = Taro.createInnerAudioContext()
|
||||
ctx.src = msg.audioUrl
|
||||
ctx.autoplay = true
|
||||
ctx.onPlay(() => setPlayingId(msg.id))
|
||||
ctx.onEnded(() => {
|
||||
setPlayingId(null)
|
||||
ctx.destroy()
|
||||
audioCtx.current = null
|
||||
})
|
||||
ctx.onError(() => {
|
||||
setPlayingId(null)
|
||||
ctx.destroy()
|
||||
audioCtx.current = null
|
||||
Taro.showToast({ title: '播放失败', icon: 'none' })
|
||||
})
|
||||
audioCtx.current = ctx
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
audioCtx.current?.stop()
|
||||
audioCtx.current?.destroy()
|
||||
Taro.navigateBack()
|
||||
}
|
||||
|
||||
const handleSend = async () => {
|
||||
const normalizedContent = inputText.trim()
|
||||
if (!normalizedContent || sending) return
|
||||
if (!character.canSend || !character.childId) {
|
||||
Taro.showToast({ title: '当前会话不支持发送', icon: 'none' })
|
||||
return
|
||||
}
|
||||
|
||||
setSending(true)
|
||||
try {
|
||||
const response = await sendParentMessage(character.childId, normalizedContent)
|
||||
setInputText('')
|
||||
if (response.conversation_id && response.conversation_id !== activeConversationId) {
|
||||
setActiveConversationId(response.conversation_id)
|
||||
} else {
|
||||
await loadChatData(activeConversationId)
|
||||
}
|
||||
Taro.showToast({ title: '已发送', icon: 'success' })
|
||||
} catch (error: any) {
|
||||
console.error('[chat-detail] send failed:', error)
|
||||
Taro.showToast({
|
||||
title: error?.message || '发送失败,请重试',
|
||||
icon: 'none',
|
||||
})
|
||||
} finally {
|
||||
setSending(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<View className='chat-detail-page'>
|
||||
<View className='chat-header'>
|
||||
@@ -95,62 +174,72 @@ export default function ChatDetail() {
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<ScrollView className='chat-list' scrollY>
|
||||
{messages.map((msg, index) => (
|
||||
<View key={msg.id}>
|
||||
{(index === 0 || messages[index - 1].type !== msg.type ||
|
||||
messages[index - 1].time !== msg.time) && (
|
||||
<View className='time-divider'>
|
||||
<Text>{msg.time}</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{msg.type === 'user' ? (
|
||||
<View className='message-item user'>
|
||||
<View className='message-bubble'>
|
||||
{msg.isAudio ? (
|
||||
<View className='audio-message' onClick={() => handlePlayAudio(msg)}>
|
||||
<View className={`audio-icon ${playingId === msg.id ? 'playing' : ''}`}>
|
||||
{playingId === msg.id ? '⏸' : '▶'}
|
||||
</View>
|
||||
<View className='audio-info'>
|
||||
<Text className='audio-title'>录音文件</Text>
|
||||
<Text className='audio-duration'>{msg.audioDuration}</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<Text>{msg.content}</Text>
|
||||
)}
|
||||
</View>
|
||||
<View className='user-avatar'>
|
||||
<Text className='avatar-img'>👦</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<View className='message-item ai'>
|
||||
<View className='ai-avatar'>
|
||||
<Text className='robot-emoji'>{character.icon}</Text>
|
||||
</View>
|
||||
<View className='message-bubble'>
|
||||
{msg.isAudio ? (
|
||||
<View className='audio-message' onClick={() => handlePlayAudio(msg)}>
|
||||
<View className={`audio-icon orange ${playingId === msg.id ? 'playing' : ''}`}>
|
||||
{playingId === msg.id ? '⏸' : '▶'}
|
||||
</View>
|
||||
<View className='audio-info'>
|
||||
<Text className='audio-title'>录音文件</Text>
|
||||
<Text className='audio-duration'>{msg.audioDuration}</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<Text>{msg.content}</Text>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
<ScrollView className='chat-list' scrollY scrollWithAnimation>
|
||||
{loading ? (
|
||||
<View className='empty-chat'>
|
||||
<Text className='empty-chat-text'>加载中...</Text>
|
||||
</View>
|
||||
))}
|
||||
) : messages.length === 0 ? (
|
||||
<View className='empty-chat'>
|
||||
<Text className='empty-chat-text'>
|
||||
{character.canSend ? '还没有消息,发送第一条吧' : '这个会话还没有消息'}
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
messages.map((msg, index) => (
|
||||
<View key={msg.id}>
|
||||
{(index === 0 || messages[index - 1].time !== msg.time) && (
|
||||
<View className='time-divider'>
|
||||
<Text>{msg.time}</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{msg.type === 'user' ? (
|
||||
<View className='message-item user'>
|
||||
<View className='message-main'>
|
||||
<Text className='message-meta'>{formatParticipantLabel(msg)}</Text>
|
||||
<View className='message-bubble'>
|
||||
<Text>{msg.content}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View className='user-avatar'>
|
||||
<Text className='avatar-img'>{msg.senderType === 'parent' ? '👨' : '👦'}</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<View className='message-item peer'>
|
||||
<View className='peer-avatar'>
|
||||
<Text className='robot-emoji'>{msg.senderType === 'child' ? '🧒' : character.icon}</Text>
|
||||
</View>
|
||||
<View className='message-main'>
|
||||
<Text className='message-meta'>{formatParticipantLabel(msg)}</Text>
|
||||
<View className='message-bubble'>
|
||||
<Text>{msg.content}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
))
|
||||
)}
|
||||
</ScrollView>
|
||||
|
||||
{character.canSend && character.childId && (
|
||||
<View className='composer'>
|
||||
<Input
|
||||
className='composer-input'
|
||||
value={inputText}
|
||||
placeholder='输入要发给孩子的消息'
|
||||
maxlength={500}
|
||||
confirmType='send'
|
||||
onInput={(event) => setInputText(event.detail.value)}
|
||||
onConfirm={handleSend}
|
||||
/>
|
||||
<View className={`composer-send ${sending ? 'disabled' : ''}`} onClick={handleSend}>
|
||||
<Text className='composer-send-text'>{sending ? '发送中' : '发送'}</Text>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user