useMessages.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. }
  34. export function useMessages({
  35. conversationId,
  36. agentId,
  37. updateConversation,
  38. }: UseMessagesOptions) {
  39. // 消息列表、请求状态、访客详情等基础状态
  40. const [messages, setMessages] = useState<MessageItem[]>([]);
  41. const [loadingMessages, setLoadingMessages] = useState(false);
  42. const [sending, setSending] = useState(false);
  43. const [conversationDetail, setConversationDetail] =
  44. useState<ConversationDetail | null>(null);
  45. const refreshConversationDetail = useCallback(
  46. async (id: number) => {
  47. const detail = await fetchConversationDetail(id);
  48. setConversationDetail(detail);
  49. // 同时更新对话列表中的 last_seen_at(用于判断在线状态)
  50. if (detail) {
  51. updateConversation(id, (conv) => ({
  52. ...conv,
  53. last_seen_at: detail.last_seen_at ?? conv.last_seen_at ?? null,
  54. }));
  55. }
  56. },
  57. [updateConversation]
  58. );
  59. const updateContactInfo = useCallback(
  60. async (
  61. payload: UpdateConversationContactPayload
  62. ): Promise<UpdateConversationContactResult> => {
  63. if (!conversationId) {
  64. throw new Error("未选中会话,无法更新访客信息");
  65. }
  66. const result = await updateConversationContact(conversationId, payload);
  67. setConversationDetail((prev) =>
  68. prev
  69. ? {
  70. ...prev,
  71. email: result.email,
  72. phone: result.phone,
  73. notes: result.notes,
  74. }
  75. : prev
  76. );
  77. if (!conversationDetail) {
  78. refreshConversationDetail(conversationId);
  79. }
  80. return result;
  81. },
  82. [conversationDetail, conversationId, refreshConversationDetail]
  83. );
  84. const handleMarkMessagesRead = useCallback(
  85. async (id: number, readerIsAgent: boolean) => {
  86. const result = await markMessagesRead(id, readerIsAgent);
  87. if (!result || result.message_ids.length === 0) {
  88. return;
  89. }
  90. const messageIdSet = new Set(result.message_ids);
  91. setMessages((prev) =>
  92. prev.map((msg) =>
  93. messageIdSet.has(msg.id)
  94. ? {
  95. ...msg,
  96. is_read: true,
  97. read_at: result.read_at ?? msg.read_at ?? null,
  98. }
  99. : msg
  100. )
  101. );
  102. if (readerIsAgent) {
  103. updateConversation(id, (conversation) => ({
  104. ...conversation,
  105. unread_count: result.unread_count,
  106. last_message:
  107. conversation.last_message &&
  108. messageIdSet.has(conversation.last_message.id)
  109. ? {
  110. ...conversation.last_message,
  111. is_read: true,
  112. read_at:
  113. result.read_at ?? conversation.last_message.read_at ?? null,
  114. }
  115. : conversation.last_message,
  116. }));
  117. setConversationDetail((prev) =>
  118. prev ? { ...prev, unread_count: result.unread_count } : prev
  119. );
  120. } else {
  121. updateConversation(
  122. id,
  123. (conversation) => ({
  124. ...conversation,
  125. last_message:
  126. conversation.last_message &&
  127. messageIdSet.has(conversation.last_message.id)
  128. ? {
  129. ...conversation.last_message,
  130. is_read: true,
  131. read_at:
  132. result.read_at ??
  133. conversation.last_message.read_at ??
  134. null,
  135. }
  136. : conversation.last_message,
  137. }),
  138. { skipResort: true }
  139. );
  140. setConversationDetail((prev) =>
  141. prev ? { ...prev, last_seen_at: result.read_at ?? prev.last_seen_at ?? null } : prev
  142. );
  143. }
  144. },
  145. [updateConversation]
  146. );
  147. const loadMessages = useCallback(
  148. async (id: number) => {
  149. setLoadingMessages(true);
  150. try {
  151. const data = await fetchMessages(id);
  152. setMessages(data);
  153. // 注意:不再自动标记访客消息为已读,而是通过滚动检测来处理
  154. } catch (error) {
  155. console.error("拉取消息失败:", error);
  156. } finally {
  157. setLoadingMessages(false);
  158. }
  159. },
  160. []
  161. );
  162. useEffect(() => {
  163. if (!conversationId || !agentId) {
  164. setMessages([]);
  165. setConversationDetail(null);
  166. return;
  167. }
  168. loadMessages(conversationId);
  169. refreshConversationDetail(conversationId);
  170. }, [conversationId, agentId, loadMessages, refreshConversationDetail]);
  171. const handleSendMessage = useCallback(
  172. async (content: string) => {
  173. if (!conversationId || !agentId || !content.trim() || sending) {
  174. return;
  175. }
  176. setSending(true);
  177. try {
  178. await sendMessage({
  179. conversationId,
  180. content,
  181. senderId: agentId,
  182. });
  183. } catch (error) {
  184. console.error(error);
  185. throw error;
  186. } finally {
  187. setSending(false);
  188. }
  189. },
  190. [agentId, conversationId, sending]
  191. );
  192. const handleNewMessage = useCallback(
  193. (message: MessageItem) => {
  194. setMessages((prev) => {
  195. const exists = prev.some((item) => item.id === message.id);
  196. if (exists) {
  197. // 消息已存在,更新消息内容(包括已读状态)
  198. return prev.map((msg) =>
  199. msg.id === message.id
  200. ? {
  201. ...msg,
  202. ...message,
  203. // 如果消息已被标记为已读,保持已读状态
  204. is_read: message.is_read ?? msg.is_read,
  205. read_at: message.read_at ?? msg.read_at,
  206. }
  207. : msg
  208. );
  209. }
  210. return [...prev, message];
  211. });
  212. updateConversation(message.conversation_id, (conversation) => {
  213. const preview = buildMessagePreview(message.content);
  214. const isSystemMessage =
  215. (message.message_type ?? "user_message") === "system_message";
  216. const isVisitorMessage = !message.sender_is_agent && !isSystemMessage;
  217. const isCurrentConversation = message.conversation_id === conversationId;
  218. const nextUnread = isVisitorMessage
  219. ? isCurrentConversation
  220. ? 0
  221. : (conversation.unread_count ?? 0) + 1
  222. : conversation.unread_count ?? 0;
  223. return {
  224. ...conversation,
  225. updated_at: message.created_at,
  226. unread_count: nextUnread,
  227. last_message: {
  228. id: message.id,
  229. content: preview,
  230. sender_is_agent: message.sender_is_agent,
  231. message_type: message.message_type ?? "user_message",
  232. is_read: Boolean(message.is_read),
  233. read_at: message.read_at ?? null,
  234. created_at: message.created_at,
  235. },
  236. };
  237. });
  238. // 注意:不再自动标记访客消息为已读,而是通过滚动检测来处理
  239. if (message.conversation_id === conversationId) {
  240. refreshConversationDetail(message.conversation_id);
  241. }
  242. },
  243. [conversationId, refreshConversationDetail, updateConversation]
  244. );
  245. const handleMessagesReadBroadcast = useCallback(
  246. (payload: MessagesReadPayload, eventConversationId?: number) => {
  247. const messageIds: number[] = Array.isArray(payload?.message_ids)
  248. ? payload.message_ids
  249. : [];
  250. if (!Array.isArray(messageIds) || messageIds.length === 0) {
  251. return;
  252. }
  253. const readAt: string | undefined = payload?.read_at;
  254. const readerIsAgent: boolean = Boolean(payload?.reader_is_agent);
  255. const conversation_id: number | undefined =
  256. payload?.conversation_id ?? eventConversationId;
  257. if (!conversation_id) {
  258. return;
  259. }
  260. // 对于客服端:只有当 reader_is_agent === false 时(访客读取了客服的消息),
  261. // 才更新客服消息(sender_is_agent === true)的已读状态
  262. if (readerIsAgent) {
  263. return;
  264. }
  265. const idSet = new Set(messageIds);
  266. // 更新消息列表中的已读状态(只更新当前对话中的消息,且只更新客服自己的消息)
  267. if (conversation_id === conversationId) {
  268. setMessages((prev) => {
  269. // 检查是否有需要更新的消息
  270. const hasUpdates = prev.some(
  271. (msg) => idSet.has(msg.id) && msg.sender_is_agent && !msg.is_read
  272. );
  273. if (!hasUpdates) {
  274. // 没有需要更新的消息,直接返回原列表
  275. return prev;
  276. }
  277. // 更新消息列表
  278. return prev.map((msg) =>
  279. // 只更新客服自己的消息(sender_is_agent === true)的已读状态
  280. idSet.has(msg.id) && msg.sender_is_agent
  281. ? {
  282. ...msg,
  283. is_read: true,
  284. read_at: readAt ?? msg.read_at ?? null,
  285. }
  286. : msg
  287. );
  288. });
  289. }
  290. const unreadCount =
  291. typeof payload?.unread_count === "number"
  292. ? payload.unread_count
  293. : undefined;
  294. updateConversation(conversation_id, (conversation) => {
  295. const lastMessage =
  296. conversation.last_message &&
  297. idSet.has(conversation.last_message.id)
  298. ? {
  299. ...conversation.last_message,
  300. is_read: true,
  301. read_at:
  302. readAt ?? conversation.last_message.read_at ?? null,
  303. }
  304. : conversation.last_message;
  305. return {
  306. ...conversation,
  307. last_message: lastMessage,
  308. unread_count:
  309. readerIsAgent && unreadCount !== undefined
  310. ? unreadCount
  311. : conversation.unread_count,
  312. };
  313. });
  314. if (conversation_id === conversationId) {
  315. setConversationDetail((prev) => {
  316. if (!prev) {
  317. return prev;
  318. }
  319. if (readerIsAgent && unreadCount !== undefined) {
  320. return { ...prev, unread_count: unreadCount };
  321. }
  322. if (!readerIsAgent) {
  323. return {
  324. ...prev,
  325. last_seen_at: readAt ?? prev.last_seen_at ?? null,
  326. };
  327. }
  328. return prev;
  329. });
  330. }
  331. },
  332. [conversationId, updateConversation]
  333. );
  334. const onWebSocketMessage = useCallback(
  335. (event: WSMessage<ChatWebSocketPayload>) => {
  336. if (!event) {
  337. return;
  338. }
  339. if (event.type === "new_message" && event.data) {
  340. const data = event.data as MessageItem;
  341. if (typeof data.conversation_id === "number") {
  342. handleNewMessage(data);
  343. }
  344. } else if (event.type === "messages_read") {
  345. handleMessagesReadBroadcast(
  346. event.data as MessagesReadPayload,
  347. event.conversation_id
  348. );
  349. } else if (event.type === "visitor_status_update") {
  350. // 处理访客状态更新事件
  351. const payload = event.data as VisitorStatusUpdatePayload;
  352. if (payload?.conversation_id) {
  353. if (payload.is_online === true) {
  354. // 在线:更新为当前时间(实时更新在线状态)
  355. updateConversation(payload.conversation_id, (conv) => ({
  356. ...conv,
  357. last_seen_at: new Date().toISOString(),
  358. }));
  359. }
  360. // 刷新对话详情以获取最新的 last_seen_at(后端会在离线时更新 last_seen_at)
  361. // refreshConversationDetail 会自动更新对话列表的 last_seen_at
  362. refreshConversationDetail(payload.conversation_id);
  363. }
  364. }
  365. },
  366. [
  367. conversationId,
  368. handleMessagesReadBroadcast,
  369. handleNewMessage,
  370. refreshConversationDetail,
  371. updateConversation,
  372. ]
  373. );
  374. useWebSocket<ChatWebSocketPayload>({
  375. conversationId,
  376. enabled: Boolean(conversationId),
  377. isVisitor: false, // 客服端设置为 false
  378. onMessage: onWebSocketMessage,
  379. onError: (error) => console.error("WebSocket 连接错误:", error),
  380. onClose: () => console.log("WebSocket 连接已关闭"),
  381. });
  382. const controls = useMemo(
  383. () => ({
  384. messages,
  385. loadingMessages,
  386. sending,
  387. conversationDetail,
  388. refreshConversationDetail,
  389. refreshMessages: loadMessages,
  390. sendMessage: handleSendMessage,
  391. markMessagesAsRead: handleMarkMessagesRead,
  392. updateContactInfo,
  393. }),
  394. [
  395. conversationDetail,
  396. handleMarkMessagesRead,
  397. handleSendMessage,
  398. loadMessages,
  399. loadingMessages,
  400. messages,
  401. refreshConversationDetail,
  402. sending,
  403. updateContactInfo,
  404. ]
  405. );
  406. return controls;
  407. }