import { useState, useMemo, useCallback, useRef, useEffect } from 'react' import Taro, { useDidShow } from '@tarojs/taro' import { View, Text, ScrollView, Input } from '@tarojs/components' import { Icon } from '@antmjs/vantui' import { chatList } from '@/mock/messages' import { conversations } from '@/mock/conversations' import type { ChatMessage } from '@/mock/conversations' import './index.less' /** 角色标签映射 */ const ROLE_LABEL: Record = { rider: '骑手', merchant: '商家', user: '同学', } function getStatusBarH(): number { try { return Taro.getSystemInfoSync().statusBarHeight || 20 } catch { return 20 } } function getSafeBottom(): number { try { const info = Taro.getSystemInfoSync() return (info.screenHeight - info.safeArea!.bottom) || 0 } catch { return 0 } } export default function ChatPage() { const id = String(Taro.getCurrentInstance().router?.params?.id || '') /* ---- 查找聊天对象 ---- */ const partner = useMemo(() => chatList.find((c) => c.id === id), [id]) /* ---- 对话消息 ---- */ const [messages, setMessages] = useState([]) const [inputValue, setInputValue] = useState('') const statusBarH = useMemo(getStatusBarH, []) const safeBottom = useMemo(getSafeBottom, []) // 初始化消息 useDidShow(() => { if (id && conversations[id]) { setMessages(conversations[id]) } }) /* ---- 事件 ---- */ const handleBack = useCallback(() => { Taro.navigateBack() }, []) const handleSend = useCallback(() => { const text = inputValue.trim() if (!text) return const now = new Date() const time = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}` const newMsg: ChatMessage = { id: `m${Date.now()}`, sender: 'me', content: text, time, } setMessages((prev) => [...prev, newMsg]) setInputValue('') // 模拟对方自动回复(1.5 秒后) if (partner) { setTimeout(() => { const autoReply: ChatMessage = { id: `m${Date.now() + 1}`, sender: 'other', content: '好的,收到你的消息了~', time: `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes() + 1).padStart(2, '0')}`, } setMessages((prev) => [...prev, autoReply]) }, 1500) } }, [inputValue, partner]) if (!partner) { return ( 未知用户 对话不存在 ) } const roleLabel = partner.role ? ROLE_LABEL[partner.role] : '' return ( {/* ===== 导航栏 ===== */} {partner.name} {roleLabel && {roleLabel}} {/* ===== 消息列表 ===== */} {messages.map((msg) => ( {msg.content} {msg.time} ))} {/* ===== 底部输入栏 ===== */} setInputValue(String(e.detail.value))} confirmType='send' onConfirm={handleSend} /> 发送 ) }