useMessages.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. "use client";
  2. import { useCallback, useEffect, useMemo, useState } from "react";
  3. import {
  4. fetchConversationDetail,
  5. updateConversationContact,
  6. UpdateConversationContactPayload,
  7. UpdateConversationContactResult,
  8. } from "../../agent/services/conversationApi";
  9. import {
  10. fetchMessages,
  11. markMessagesRead,
  12. sendMessage,
  13. } from "../../agent/services/messageApi";
  14. import {
  15. ConversationDetail,
  16. ConversationSummary,
  17. MessageItem,
  18. MessagesReadPayload,
  19. ChatWebSocketPayload,
  20. VisitorStatusUpdatePayload,
  21. } from "../../agent/types";
  22. import { useWebSocket } from "./useWebSocket";
  23. import { WSMessage } from "@/lib/websocket";
  24. import { buildMessagePreview } from "@/utils/format";
  25. interface UseMessagesOptions {
  26. conversationId: number | null;
  27. agentId: number | null;
  28. updateConversation: (
  29. conversationId: number,
  30. updater: (conversation: ConversationSummary) => ConversationSummary,
  31. options?: { skipResort?: boolean }
  32. ) => void;
  33. refreshConversations?: () => void; // 刷新对话列表(用于新对话的情况)
  34. hasConversation?: (conversationId: number) => boolean; // 检查对话是否存在
  35. }
  36. export function useMessages({
  37. conversationId,
  38. agentId,
  39. updateConversation,
  40. refreshConversations,
  41. hasConversation,
  42. }: UseMessagesOptions) {
  43. // 消息列表、请求状态、访客详情等基础状态
  44. const [messages, setMessages] = useState<MessageItem[]>([]);
  45. const [loadingMessages, setLoadingMessages] = useState(false);
  46. const [sending, setSending] = useState(false);
  47. const [conversationDetail, setConversationDetail] =
  48. useState<ConversationDetail | null>(null);
  49. const [includeAIMessages, setIncludeAIMessages] = useState(false); // 是否包含 AI 消息(默认不包含)
  50. const refreshConversationDetail = useCallback(
  51. async (id: number) => {
  52. const detail = await fetchConversationDetail(id);
  53. setConversationDetail(detail);
  54. // 同时更新对话列表中的 last_seen_at(用于判断在线状态)
  55. if (detail) {
  56. updateConversation(id, (conv) => ({
  57. ...conv,
  58. last_seen_at: detail.last_seen_at ?? conv.last_seen_at ?? null,
  59. }));
  60. }
  61. },
  62. [updateConversation]
  63. );
  64. const updateContactInfo = useCallback(
  65. async (
  66. payload: UpdateConversationContactPayload
  67. ): Promise<UpdateConversationContactResult> => {
  68. if (!conversationId) {
  69. throw new Error("未选中会话,无法更新访客信息");
  70. }
  71. const result = await updateConversationContact(conversationId, payload);
  72. setConversationDetail((prev) =>
  73. prev
  74. ? {
  75. ...prev,
  76. email: result.email,
  77. phone: result.phone,
  78. notes: result.notes,
  79. }
  80. : prev
  81. );
  82. if (!conversationDetail) {
  83. refreshConversationDetail(conversationId);
  84. }
  85. return result;
  86. },
  87. [conversationDetail, conversationId, refreshConversationDetail]
  88. );
  89. const handleMarkMessagesRead = useCallback(
  90. async (id: number, readerIsAgent: boolean) => {
  91. const result = await markMessagesRead(id, readerIsAgent);
  92. if (!result || result.message_ids.length === 0) {
  93. return;
  94. }
  95. const messageIdSet = new Set(result.message_ids);
  96. setMessages((prev) =>
  97. prev.map((msg) =>
  98. messageIdSet.has(msg.id)
  99. ? {
  100. ...msg,
  101. is_read: true,
  102. read_at: result.read_at ?? msg.read_at ?? null,
  103. }
  104. : msg
  105. )
  106. );
  107. if (readerIsAgent) {
  108. updateConversation(id, (conversation) => ({
  109. ...conversation,
  110. unread_count: result.unread_count,
  111. last_message:
  112. conversation.last_message &&
  113. messageIdSet.has(conversation.last_message.id)
  114. ? {
  115. ...conversation.last_message,
  116. is_read: true,
  117. read_at:
  118. result.read_at ?? conversation.last_message.read_at ?? null,
  119. }
  120. : conversation.last_message,
  121. }));
  122. setConversationDetail((prev) =>
  123. prev ? { ...prev, unread_count: result.unread_count } : prev
  124. );
  125. } else {
  126. updateConversation(
  127. id,
  128. (conversation) => ({
  129. ...conversation,
  130. last_message:
  131. conversation.last_message &&
  132. messageIdSet.has(conversation.last_message.id)
  133. ? {
  134. ...conversation.last_message,
  135. is_read: true,
  136. read_at:
  137. result.read_at ??
  138. conversation.last_message.read_at ??
  139. null,
  140. }
  141. : conversation.last_message,
  142. }),
  143. { skipResort: true }
  144. );
  145. setConversationDetail((prev) =>
  146. prev ? { ...prev, last_seen_at: result.read_at ?? prev.last_seen_at ?? null } : prev
  147. );
  148. }
  149. },
  150. [updateConversation]
  151. );
  152. const loadMessages = useCallback(
  153. async (id: number, includeAI: boolean = includeAIMessages) => {
  154. setLoadingMessages(true);
  155. try {
  156. const data = await fetchMessages(id, includeAI);
  157. setMessages(data);
  158. // 注意:不再自动标记访客消息为已读,而是通过滚动检测来处理
  159. } catch (error) {
  160. console.error("拉取消息失败:", error);
  161. } finally {
  162. setLoadingMessages(false);
  163. }
  164. },
  165. [includeAIMessages]
  166. );
  167. useEffect(() => {
  168. if (!conversationId || !agentId) {
  169. setMessages([]);
  170. setConversationDetail(null);
  171. return;
  172. }
  173. loadMessages(conversationId, includeAIMessages);
  174. refreshConversationDetail(conversationId);
  175. }, [conversationId, agentId, includeAIMessages, loadMessages, refreshConversationDetail]);
  176. const handleSendMessage = useCallback(
  177. async (content: string, fileInfo?: { file_url: string; file_type: string; file_name: string; file_size: number; mime_type: string }) => {
  178. if (!conversationId || !agentId || sending) {
  179. return;
  180. }
  181. // 验证:必须有内容或文件
  182. if (!content.trim() && !fileInfo) {
  183. return;
  184. }
  185. setSending(true);
  186. try {
  187. await sendMessage({
  188. conversationId,
  189. content: content.trim(),
  190. senderId: agentId,
  191. fileUrl: fileInfo?.file_url,
  192. fileType: fileInfo?.file_type as "image" | "document" | undefined,
  193. fileName: fileInfo?.file_name,
  194. fileSize: fileInfo?.file_size,
  195. mimeType: fileInfo?.mime_type,
  196. });
  197. } catch (error) {
  198. console.error(error);
  199. throw error;
  200. } finally {
  201. setSending(false);
  202. }
  203. },
  204. [agentId, conversationId, sending]
  205. );
  206. const handleNewMessage = useCallback(
  207. (message: MessageItem) => {
  208. // 检查对话是否存在
  209. const conversationExists = hasConversation
  210. ? hasConversation(message.conversation_id)
  211. : true; // 如果没有提供检查方法,假设对话存在
  212. // 先更新对话列表(无论是否是当前对话,都需要更新未读数、最后消息等)
  213. // 这样即使客服没有选中这个对话,也能看到新消息的提示
  214. updateConversation(message.conversation_id, (conversation) => {
  215. const preview = buildMessagePreview(message.content);
  216. const isSystemMessage =
  217. (message.message_type ?? "user_message") === "system_message";
  218. const isVisitorMessage = !message.sender_is_agent && !isSystemMessage;
  219. const isCurrentConversation = message.conversation_id === conversationId;
  220. const nextUnread = isVisitorMessage
  221. ? isCurrentConversation
  222. ? 0
  223. : (conversation.unread_count ?? 0) + 1
  224. : conversation.unread_count ?? 0;
  225. return {
  226. ...conversation,
  227. updated_at: message.created_at,
  228. unread_count: nextUnread,
  229. last_message: {
  230. id: message.id,
  231. content: preview,
  232. sender_is_agent: message.sender_is_agent,
  233. message_type: message.message_type ?? "user_message",
  234. is_read: Boolean(message.is_read),
  235. read_at: message.read_at ?? null,
  236. created_at: message.created_at,
  237. },
  238. };
  239. });
  240. // 如果对话不存在(新对话),延迟刷新对话列表以添加新对话
  241. // 使用 setTimeout 延迟刷新,避免频繁刷新,并且给 updateConversation 时间完成
  242. if (!conversationExists && refreshConversations) {
  243. setTimeout(() => {
  244. refreshConversations();
  245. }, 500);
  246. }
  247. // 只处理当前对话的消息(添加到消息列表)
  248. if (message.conversation_id !== conversationId) {
  249. return;
  250. }
  251. // 根据 includeAIMessages 状态过滤 AI 消息
  252. // 如果隐藏 AI 消息(includeAIMessages === false)且消息的 chat_mode === "ai",则不添加到消息列表
  253. const messageChatMode = message.chat_mode || "human"; // 兼容历史数据,默认为 human
  254. const shouldHideAIMessage = !includeAIMessages && messageChatMode === "ai";
  255. setMessages((prev) => {
  256. const exists = prev.some((item) => item.id === message.id);
  257. if (exists) {
  258. // 消息已存在,需要根据 includeAIMessages 决定是否保留
  259. if (shouldHideAIMessage) {
  260. // 如果应该隐藏 AI 消息,则从列表中移除
  261. return prev.filter((msg) => msg.id !== message.id);
  262. }
  263. // 消息已存在,更新消息内容(包括已读状态)
  264. return prev.map((msg) =>
  265. msg.id === message.id
  266. ? {
  267. ...msg,
  268. ...message,
  269. // 如果消息已被标记为已读,保持已读状态;否则保持原状态
  270. // 这样可以避免丢失已读状态
  271. is_read: message.is_read ?? msg.is_read ?? false,
  272. read_at: message.read_at ?? msg.read_at ?? null,
  273. }
  274. : msg
  275. );
  276. }
  277. // 新消息:如果要隐藏 AI 消息且这是 AI 消息,则不添加
  278. if (shouldHideAIMessage) {
  279. return prev;
  280. }
  281. // 新消息:添加到列表末尾
  282. return [...prev, message];
  283. });
  284. // 注意:不再自动标记访客消息为已读,而是通过滚动检测来处理
  285. // 不再调用 refreshConversationDetail,避免不必要的重新加载和状态丢失
  286. },
  287. [conversationId, updateConversation, refreshConversations, hasConversation, includeAIMessages]
  288. );
  289. const handleMessagesReadBroadcast = useCallback(
  290. (payload: MessagesReadPayload, eventConversationId?: number) => {
  291. const messageIds: number[] = Array.isArray(payload?.message_ids)
  292. ? payload.message_ids
  293. : [];
  294. if (!Array.isArray(messageIds) || messageIds.length === 0) {
  295. return;
  296. }
  297. const readAt: string | undefined = payload?.read_at;
  298. const readerIsAgent: boolean = Boolean(payload?.reader_is_agent);
  299. const conversation_id: number | undefined =
  300. payload?.conversation_id ?? eventConversationId;
  301. if (!conversation_id) {
  302. return;
  303. }
  304. // 对于客服端:只有当 reader_is_agent === false 时(访客读取了客服的消息),
  305. // 才更新客服消息(sender_is_agent === true)的已读状态
  306. if (readerIsAgent) {
  307. return;
  308. }
  309. const idSet = new Set(messageIds);
  310. // 更新消息列表中的已读状态(只更新当前对话中的消息,且只更新客服自己的消息)
  311. if (conversation_id === conversationId) {
  312. setMessages((prev) => {
  313. // 检查是否有需要更新的消息
  314. const hasUpdates = prev.some(
  315. (msg) => idSet.has(msg.id) && msg.sender_is_agent && !msg.is_read
  316. );
  317. if (!hasUpdates) {
  318. // 没有需要更新的消息,直接返回原列表
  319. return prev;
  320. }
  321. // 更新消息列表
  322. return prev.map((msg) =>
  323. // 只更新客服自己的消息(sender_is_agent === true)的已读状态
  324. idSet.has(msg.id) && msg.sender_is_agent
  325. ? {
  326. ...msg,
  327. is_read: true,
  328. read_at: readAt ?? msg.read_at ?? null,
  329. }
  330. : msg
  331. );
  332. });
  333. }
  334. const unreadCount =
  335. typeof payload?.unread_count === "number"
  336. ? payload.unread_count
  337. : undefined;
  338. updateConversation(conversation_id, (conversation) => {
  339. const lastMessage =
  340. conversation.last_message &&
  341. idSet.has(conversation.last_message.id)
  342. ? {
  343. ...conversation.last_message,
  344. is_read: true,
  345. read_at:
  346. readAt ?? conversation.last_message.read_at ?? null,
  347. }
  348. : conversation.last_message;
  349. return {
  350. ...conversation,
  351. last_message: lastMessage,
  352. unread_count:
  353. readerIsAgent && unreadCount !== undefined
  354. ? unreadCount
  355. : conversation.unread_count,
  356. };
  357. });
  358. if (conversation_id === conversationId) {
  359. setConversationDetail((prev) => {
  360. if (!prev) {
  361. return prev;
  362. }
  363. if (readerIsAgent && unreadCount !== undefined) {
  364. return { ...prev, unread_count: unreadCount };
  365. }
  366. if (!readerIsAgent) {
  367. return {
  368. ...prev,
  369. last_seen_at: readAt ?? prev.last_seen_at ?? null,
  370. };
  371. }
  372. return prev;
  373. });
  374. }
  375. },
  376. [conversationId, updateConversation]
  377. );
  378. const onWebSocketMessage = useCallback(
  379. (event: WSMessage<ChatWebSocketPayload>) => {
  380. if (!event) {
  381. return;
  382. }
  383. if (event.type === "new_message" && event.data) {
  384. const data = event.data as MessageItem;
  385. if (typeof data.conversation_id === "number") {
  386. handleNewMessage(data);
  387. }
  388. } else if (event.type === "messages_read") {
  389. handleMessagesReadBroadcast(
  390. event.data as MessagesReadPayload,
  391. event.conversation_id
  392. );
  393. } else if (event.type === "visitor_status_update") {
  394. // 处理访客状态更新事件
  395. const payload = event.data as VisitorStatusUpdatePayload;
  396. if (payload?.conversation_id) {
  397. if (payload.is_online === true) {
  398. // 在线:更新为当前时间(实时更新在线状态)
  399. updateConversation(payload.conversation_id, (conv) => ({
  400. ...conv,
  401. last_seen_at: new Date().toISOString(),
  402. }));
  403. // 如果当前正在查看这个对话,也更新对话详情
  404. if (payload.conversation_id === conversationId) {
  405. setConversationDetail((prev) =>
  406. prev
  407. ? {
  408. ...prev,
  409. last_seen_at: new Date().toISOString(),
  410. }
  411. : prev
  412. );
  413. }
  414. } else {
  415. // 离线:刷新对话详情以获取最新的 last_seen_at(后端会在离线时更新 last_seen_at)
  416. // refreshConversationDetail 会自动更新对话列表的 last_seen_at
  417. refreshConversationDetail(payload.conversation_id);
  418. }
  419. }
  420. }
  421. },
  422. [
  423. conversationId,
  424. handleMessagesReadBroadcast,
  425. handleNewMessage,
  426. refreshConversationDetail,
  427. updateConversation,
  428. ]
  429. );
  430. useWebSocket<ChatWebSocketPayload>({
  431. conversationId,
  432. enabled: Boolean(conversationId),
  433. isVisitor: false, // 客服端设置为 false
  434. agentId: agentId ?? undefined, // 传递客服ID,用于创建系统消息
  435. onMessage: onWebSocketMessage,
  436. onError: (error) => {
  437. // 静默处理错误,避免影响用户体验
  438. },
  439. onClose: () => {
  440. // 静默处理关闭,避免影响用户体验
  441. },
  442. });
  443. // 切换 AI 消息显示/隐藏
  444. const toggleAIMessages = useCallback(async () => {
  445. const newValue = !includeAIMessages;
  446. setIncludeAIMessages(newValue);
  447. // 如果当前有选中的对话,重新加载消息(从服务器获取完整消息列表,确保过滤正确)
  448. if (conversationId) {
  449. await loadMessages(conversationId, newValue);
  450. }
  451. }, [includeAIMessages, conversationId, loadMessages]);
  452. const controls = useMemo(
  453. () => ({
  454. messages,
  455. loadingMessages,
  456. sending,
  457. conversationDetail,
  458. refreshConversationDetail,
  459. refreshMessages: loadMessages,
  460. sendMessage: handleSendMessage,
  461. markMessagesAsRead: handleMarkMessagesRead,
  462. updateContactInfo,
  463. includeAIMessages,
  464. toggleAIMessages,
  465. }),
  466. [
  467. conversationDetail,
  468. handleMarkMessagesRead,
  469. handleSendMessage,
  470. loadMessages,
  471. loadingMessages,
  472. messages,
  473. refreshConversationDetail,
  474. sending,
  475. updateContactInfo,
  476. includeAIMessages,
  477. toggleAIMessages,
  478. ]
  479. );
  480. return controls;
  481. }