import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { AlertCircle, Check, CheckCheck, ImagePlus, Loader2, MessageCircleMore, RefreshCw, Search, Send, Smile, UserRound, Wifi, WifiOff, } from 'lucide-react'; import { AccountDetail, ChatMessage, ChatSession } from '../types'; import { getAccountDetails, getAccountRuntimeStatuses, getChatMessagePage, getChatMessages, getChatSessionPage, getChatSessions, markChatRead, sendChatImage, sendChatMessage, } from '../services/api'; import { emojiURL, renderXianyuText, xianyuEmojis } from '../chatEmojis'; type SessionsByAccount = Record; const accountStorageKey = 'ydisks.chat.account.v1'; const formatClock = (value: number): string => { if (!value) return ''; const date = new Date(value < 10_000_000_000 ? value * 1000 : value); const today = new Date(); if (date.toDateString() === today.toDateString()) { return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }); } return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }); }; const messageTime = (value: number): string => { const date = new Date(value < 10_000_000_000 ? value * 1000 : value); return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }); }; const Chat: React.FC = () => { const [accounts, setAccounts] = useState([]); const [activeAccountID, setActiveAccountID] = useState(''); const [sessionsByAccount, setSessionsByAccount] = useState({}); const [activeChatID, setActiveChatID] = useState(''); const [messages, setMessages] = useState([]); const [search, setSearch] = useState(''); const [unreadOnly, setUnreadOnly] = useState(false); const [draft, setDraft] = useState(''); const [loading, setLoading] = useState(true); const [messagesLoading, setMessagesLoading] = useState(false); const [olderLoading, setOlderLoading] = useState(false); const [hasOlder, setHasOlder] = useState(false); const [historyCursor, setHistoryCursor] = useState(); const [contactCursors, setContactCursors] = useState>({}); const [hasMoreContacts, setHasMoreContacts] = useState>({}); const [contactsLoading, setContactsLoading] = useState(false); const [emojiOpen, setEmojiOpen] = useState(false); const [sending, setSending] = useState(false); const [error, setError] = useState(''); const [liveState, setLiveState] = useState<'connecting' | 'online' | 'offline'>('connecting'); const activeAccountRef = useRef(''); const activeChatRef = useRef(''); const scrollRef = useRef(null); const scrollContextRef = useRef({ accountID: '', chatID: '' }); const shouldScrollToBottomRef = useRef(true); const skipNextMessageScrollRef = useRef(false); const imageInputRef = useRef(null); const refreshedAccountsRef = useRef(new Set()); useEffect(() => { activeAccountRef.current = activeAccountID; }, [activeAccountID]); useEffect(() => { activeChatRef.current = activeChatID; }, [activeChatID]); const reloadSessions = async (accountID: string) => { const page = await getChatSessionPage(accountID, undefined, undefined, true); setSessionsByAccount(current => ({ ...current, [accountID]: page.sessions })); setContactCursors(current => ({ ...current, [accountID]: page.next_cursor })); setHasMoreContacts(current => ({ ...current, [accountID]: page.has_more })); return page.sessions; }; useEffect(() => { let cancelled = false; const load = async () => { setLoading(true); try { const [details, statuses] = await Promise.all([getAccountDetails(), getAccountRuntimeStatuses()]); const withRuntime = details.map(account => ({ ...account, runtime_state: statuses[account.id]?.state || (account.enabled ? 'connecting' : 'disabled'), runtime_connected: statuses[account.id]?.connected === true, })); const enabled = withRuntime.filter(account => account.enabled); const sessionPages = await Promise.all(enabled.map(async account => [account.id, await getChatSessionPage(account.id)] as const)); if (cancelled) return; setAccounts(enabled); setSessionsByAccount(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.sessions]))); setContactCursors(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.next_cursor]))); setHasMoreContacts(Object.fromEntries(sessionPages.map(([id, page]) => [id, page.has_more]))); const stored = window.localStorage.getItem(accountStorageKey) || ''; const first = enabled.some(account => account.id === stored) ? stored : enabled[0]?.id || ''; setActiveAccountID(first); } catch (loadError) { if (!cancelled) setError(loadError instanceof Error ? loadError.message : '加载聊天数据失败'); } finally { if (!cancelled) setLoading(false); } }; void load(); return () => { cancelled = true; }; }, []); useEffect(() => { let disposed = false; let timer = 0; let controller: AbortController | null = null; const poll = async () => { controller = new AbortController(); try { const statuses = await getAccountRuntimeStatuses({ signal: controller.signal, timeoutMs: 10_000 }); if (!disposed) { setAccounts(current => current.map(account => ({ ...account, runtime_state: statuses[account.id]?.state || account.runtime_state, runtime_connected: statuses[account.id]?.connected ?? account.runtime_connected, }))); } } catch { // The app WebSocket has its own visible state; a transient status poll // failure does not invalidate the loaded conversations. } finally { if (!disposed) timer = window.setTimeout(poll, 3_000); } }; timer = window.setTimeout(poll, 3_000); return () => { disposed = true; window.clearTimeout(timer); controller?.abort(); }; }, []); useEffect(() => { if (!activeAccountID) return; window.localStorage.setItem(accountStorageKey, activeAccountID); const sessions = sessionsByAccount[activeAccountID] || []; setActiveChatID(current => sessions.some(session => session.chat_id === current) ? current : sessions[0]?.chat_id || ''); }, [activeAccountID, sessionsByAccount]); useEffect(() => { if (!activeAccountID || refreshedAccountsRef.current.has(activeAccountID)) return; refreshedAccountsRef.current.add(activeAccountID); void reloadSessions(activeAccountID).catch(loadError => { setError(loadError instanceof Error ? loadError.message : '同步会话失败'); }); }, [activeAccountID]); useEffect(() => { if (!activeAccountID || !activeChatID) { setMessages([]); return; } const controller = new AbortController(); setMessagesLoading(true); void Promise.all([ getChatMessagePage(activeAccountID, activeChatID, undefined, undefined, { signal: controller.signal }), markChatRead(activeAccountID, activeChatID), ]).then(([page]) => { setMessages(page.messages); setHasOlder(page.has_more); setHistoryCursor(page.next_cursor); if (page.session) { setSessionsByAccount(current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(session => session.chat_id === page.session?.chat_id ? page.session! : session) })); } setSessionsByAccount(current => ({ ...current, [activeAccountID]: (current[activeAccountID] || []).map(session => session.chat_id === activeChatID ? { ...session, unread_count: 0 } : session), })); }).catch(loadError => { if (!controller.signal.aborted) setError(loadError instanceof Error ? loadError.message : '加载消息失败'); }).finally(() => { if (!controller.signal.aborted) setMessagesLoading(false); }); return () => controller.abort(); }, [activeAccountID, activeChatID]); const loadOlderMessages = async () => { if (!activeAccountID || !activeChatID || olderLoading || !hasOlder) return; const container = scrollRef.current; const previousHeight = container?.scrollHeight || 0; skipNextMessageScrollRef.current = true; setOlderLoading(true); setError(''); try { const oldestID = messages[0]?.id; const page = await getChatMessagePage(activeAccountID, activeChatID, historyCursor, oldestID); setMessages(current => { const keys = new Set(current.map(message => message.message_key)); return [...page.messages.filter(message => !keys.has(message.message_key)), ...current]; }); setHasOlder(page.has_more); setHistoryCursor(page.next_cursor); requestAnimationFrame(() => { if (container) container.scrollTop += container.scrollHeight - previousHeight; }); } catch (loadError) { skipNextMessageScrollRef.current = false; setError(loadError instanceof Error ? loadError.message : '加载历史消息失败'); } finally { setOlderLoading(false); } }; useEffect(() => { let disposed = false; let reconnectTimer = 0; let retry = 0; let socket: WebSocket | null = null; const connect = () => { if (disposed) return; setLiveState('connecting'); const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; socket = new WebSocket(`${protocol}//${window.location.host}/api/chat/ws`); socket.onopen = () => { retry = 0; setLiveState('online'); }; socket.onmessage = event => { try { const payload = JSON.parse(event.data); const message = payload.message as ChatMessage | undefined; if (!message) return; const accountID = message.account_id; setSessionsByAccount(current => { const rows = current[accountID] || []; const found = rows.some(row => row.chat_id === message.chat_id); if (!found) { void reloadSessions(accountID); return current; } return { ...current, [accountID]: rows.map(row => row.chat_id === message.chat_id ? { ...row, last_message: message.content, last_message_at: message.sent_at, unread_count: message.direction === 'incoming' && (activeAccountRef.current !== accountID || activeChatRef.current !== message.chat_id) ? row.unread_count + 1 : row.unread_count, } : row).sort((a, b) => b.last_message_at - a.last_message_at), }; }); if (activeAccountRef.current === accountID && activeChatRef.current === message.chat_id) { setMessages(current => { const index = current.findIndex(item => item.message_key === message.message_key); if (index >= 0) return current.map((item, i) => i === index ? message : item); return [...current, message]; }); if (message.direction === 'incoming') void markChatRead(accountID, message.chat_id); } } catch { // Ignore malformed non-chat frames and recover from authoritative REST state. } }; socket.onclose = () => { if (disposed) return; setLiveState('offline'); const delay = Math.min(15_000, 1_000 * 2 ** Math.min(retry++, 4)); reconnectTimer = window.setTimeout(connect, delay); }; socket.onerror = () => socket?.close(); }; connect(); return () => { disposed = true; window.clearTimeout(reconnectTimer); socket?.close(); }; }, []); const handleMessageScroll = () => { const container = scrollRef.current; if (!container) return; const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight; shouldScrollToBottomRef.current = distanceFromBottom <= 48; }; useLayoutEffect(() => { const contextChanged = scrollContextRef.current.accountID !== activeAccountID || scrollContextRef.current.chatID !== activeChatID; scrollContextRef.current = { accountID: activeAccountID, chatID: activeChatID }; if (contextChanged) shouldScrollToBottomRef.current = true; const container = scrollRef.current; if (!container) return; if (skipNextMessageScrollRef.current) { skipNextMessageScrollRef.current = false; return; } if (messagesLoading || shouldScrollToBottomRef.current) container.scrollTop = container.scrollHeight; }, [activeAccountID, activeChatID, messages, messagesLoading]); const activeAccount = accounts.find(account => account.id === activeAccountID); const activeSessions = sessionsByAccount[activeAccountID] || []; const selectedSession = activeSessions.find(session => session.chat_id === activeChatID); const filteredSessions = useMemo(() => { const keyword = search.trim().toLowerCase(); return activeSessions.filter(session => { if (unreadOnly && session.unread_count <= 0) return false; if (!keyword) return true; return [session.buyer_name, session.buyer_id, session.item_title, session.last_message] .some(value => (value || '').toLowerCase().includes(keyword)); }); }, [activeSessions, search, unreadOnly]); const unreadForAccount = (accountID: string) => (sessionsByAccount[accountID] || []).reduce((sum, session) => sum + session.unread_count, 0); const loadMoreContacts = async () => { if (!activeAccountID || contactsLoading || !hasMoreContacts[activeAccountID]) return; setContactsLoading(true); setError(''); try { const page = await getChatSessionPage(activeAccountID, contactCursors[activeAccountID], undefined, true); setSessionsByAccount(current => ({ ...current, [activeAccountID]: page.sessions })); setContactCursors(current => ({ ...current, [activeAccountID]: page.next_cursor })); setHasMoreContacts(current => ({ ...current, [activeAccountID]: page.has_more })); } catch (loadError) { setError(loadError instanceof Error ? loadError.message : '加载历史联系人失败'); } finally { setContactsLoading(false); } }; const handleSend = async () => { const text = draft.trim(); if (!text || !selectedSession || !activeAccountID || sending) return; setSending(true); setError(''); try { const result = await sendChatMessage({ account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id, buyer_name: selectedSession.buyer_name, item_id: selectedSession.item_id, item_title: selectedSession.item_title, text, }); setDraft(''); setMessages(current => current.some(item => item.message_key === result.message.message_key) ? current.map(item => item.message_key === result.message.message_key ? result.message : item) : [...current, result.message]); } catch (sendError) { setError(sendError instanceof Error ? sendError.message : '消息发送失败'); void getChatMessages(activeAccountID, selectedSession.chat_id).then(setMessages); } finally { setSending(false); } }; const handleImage = async (file?: File) => { if (!file || !selectedSession || !activeAccountID || sending) return; setSending(true); setError(''); try { const result = await sendChatImage({ account_id: activeAccountID, chat_id: selectedSession.chat_id, buyer_id: selectedSession.buyer_id, buyer_name: selectedSession.buyer_name, buyer_avatar_url: selectedSession.buyer_avatar_url, item_id: selectedSession.item_id, item_title: selectedSession.item_title, image: file, }); setMessages(current => current.some(item => item.message_key === result.message.message_key) ? current.map(item => item.message_key === result.message.message_key ? result.message : item) : [...current, result.message]); } catch (sendError) { setError(sendError instanceof Error ? sendError.message : '图片发送失败'); } finally { setSending(false); if (imageInputRef.current) imageInputRef.current.value = ''; } }; if (loading) return
; return (

在线聊天

复用账号实时连接,消息按账号完全隔离

{liveState === 'online' ? : } {liveState === 'online' ? '实时同步中' : liveState === 'connecting' ? '正在连接' : '连接已断开'}
{accounts.map(account => { const active = account.id === activeAccountID; const unread = unreadForAccount(account.id); const online = account.runtime_state === 'online'; return ( ); })}
{accounts.length === 0 ? (

暂无启用账号

先在账号管理中启用账号,聊天会话会自动出现。

) : (
{selectedSession ? ( <>
{selectedSession.buyer_name || selectedSession.buyer_id}
用户 ID:{selectedSession.buyer_id}
{activeAccount?.runtime_state === 'online' ? '账号在线' : '账号离线'}
{messagesLoading ?
: <> {hasOlder &&
} {messages.map(message => { const outgoing = message.direction === 'outgoing'; const system = message.message_type === 'system'; if (system) { return (
{renderXianyuText(message.content)}
{messageTime(message.sent_at)}
); } return (
{!outgoing &&
{selectedSession.buyer_avatar_url ? {selectedSession.buyer_name : }
}
{outgoing ? (activeAccount?.nickname || activeAccount?.remark || '我') : (selectedSession.buyer_name || message.sender_name || selectedSession.buyer_id)}
{message.message_type === 'image' ? ( 聊天图片 ) : message.message_type === 'video' ? (
{outgoing &&
{activeAccount?.avatar_url ? 我 : }
}
); })} }
{error &&
{error}
}
{emojiOpen &&
全部表情
{xianyuEmojis.map(([name,file]) => )}
}
void handleImage(event.target.files?.[0])} />