pages_messages.tsx 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import React, { useEffect } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import dayjs from 'dayjs';
  4. import 'dayjs/locale/zh-cn';
  5. import { BellIcon } from '@heroicons/react/24/outline';
  6. import { MessageStatus } from '../share/types.ts';
  7. import { io, Socket } from 'socket.io-client';
  8. // 添加通知页面组件
  9. import { MessageAPI } from './api/index.ts';
  10. import { useAuth } from "./hooks.tsx";
  11. export const NotificationsPage = () => {
  12. const { token , user} = useAuth();
  13. const queryClient = useQueryClient();
  14. const [socket, setSocket] = React.useState<Socket | null>(null);
  15. const [isSubscribed, setIsSubscribed] = React.useState(false);
  16. // 获取消息列表
  17. const { data: messages, isLoading } = useQuery({
  18. queryKey: ['messages'],
  19. queryFn: () => MessageAPI.getMessages(),
  20. });
  21. // 初始化Socket.IO连接
  22. useEffect(() => {
  23. if (!token || !user) return;
  24. const newSocket = io('/', {
  25. path: '/socket.io',
  26. transports: ['websocket'],
  27. withCredentials: true,
  28. query: {
  29. socket_token: token
  30. }
  31. });
  32. setSocket(newSocket);
  33. // 订阅消息频道
  34. newSocket.on('connect', () => {
  35. newSocket.emit('message:subscribe', `user_${user.id}`);
  36. setIsSubscribed(true);
  37. });
  38. // 处理实时消息
  39. newSocket.on('message:broadcasted', (newMessage) => {
  40. queryClient.setQueryData(['messages'], (oldData: any) => {
  41. if (!oldData) return oldData;
  42. return {
  43. ...oldData,
  44. data: [newMessage, ...oldData.data]
  45. };
  46. });
  47. // 更新未读计数
  48. queryClient.setQueryData(['unreadCount'], (oldData: any) => {
  49. if (!oldData) return oldData;
  50. return {
  51. ...oldData,
  52. count: oldData.count + 1
  53. };
  54. });
  55. });
  56. // 错误处理
  57. newSocket.on('error', (error) => {
  58. console.error('Socket error:', error);
  59. });
  60. return () => {
  61. if (newSocket) {
  62. newSocket.emit('message:unsubscribe', `user_${user.id}`);
  63. newSocket.disconnect();
  64. }
  65. };
  66. }, [queryClient, token]);
  67. // 获取未读消息数量
  68. const { data: unreadCount } = useQuery({
  69. queryKey: ['unreadCount'],
  70. queryFn: () => MessageAPI.getUnreadCount(),
  71. });
  72. // 标记消息为已读
  73. const markAsReadMutation = useMutation({
  74. mutationFn: (id: number) => MessageAPI.markAsRead(id),
  75. onSuccess: () => {
  76. queryClient.invalidateQueries({ queryKey: ['messages'] });
  77. queryClient.invalidateQueries({ queryKey: ['unreadCount'] });
  78. },
  79. });
  80. // 删除消息
  81. const deleteMutation = useMutation({
  82. mutationFn: (id: number) => MessageAPI.deleteMessage(id),
  83. onSuccess: () => {
  84. queryClient.invalidateQueries({ queryKey: ['messages'] });
  85. },
  86. });
  87. const handleMarkAsRead = (id: number) => {
  88. markAsReadMutation.mutate(id);
  89. };
  90. const handleDelete = (id: number) => {
  91. if (confirm('确定要删除这条消息吗?')) {
  92. deleteMutation.mutate(id);
  93. }
  94. };
  95. if (isLoading) {
  96. return (
  97. <div className="p-4">
  98. <h1 className="text-2xl font-bold mb-4">通知</h1>
  99. <div className="flex justify-center items-center h-40">
  100. <div className="w-8 h-8 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin"></div>
  101. </div>
  102. </div>
  103. );
  104. }
  105. return (
  106. <div className="p-4">
  107. <div className="flex items-center justify-between mb-4">
  108. <h1 className="text-2xl font-bold">通知</h1>
  109. {unreadCount && unreadCount.count > 0 ? (
  110. <div className="flex items-center">
  111. <BellIcon className="h-5 w-5 text-red-500 mr-1" />
  112. <span className="text-sm text-red-500">{unreadCount.count}条未读</span>
  113. </div>
  114. ) : null}
  115. </div>
  116. <div className="bg-white rounded-lg shadow divide-y">
  117. {messages?.data.map((message) => (
  118. <div key={message.id} className="p-4">
  119. <div className="flex justify-between items-start">
  120. <h3 className="font-medium">{message.title}</h3>
  121. <div className="flex space-x-2">
  122. {message.user_status === MessageStatus.UNREAD && (
  123. <button
  124. type="button"
  125. onClick={() => handleMarkAsRead(message.id)}
  126. className="text-xs text-blue-600 hover:text-blue-800"
  127. >
  128. 标记已读
  129. </button>
  130. )}
  131. <button
  132. type="button"
  133. onClick={() => handleDelete(message.id)}
  134. className="text-xs text-red-600 hover:text-red-800"
  135. >
  136. 删除
  137. </button>
  138. </div>
  139. </div>
  140. <p className="text-gray-500 text-sm mt-1">{message.content}</p>
  141. <p className="text-xs text-gray-400 mt-2">
  142. {dayjs(message.created_at).format('YYYY-MM-DD HH:mm')}
  143. </p>
  144. </div>
  145. ))}
  146. </div>
  147. </div>
  148. );
  149. };