2
0

useSocketClient.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. import { useEffect, useState, useCallback } from 'react';
  2. import { useQuery, useQueryClient } from '@tanstack/react-query';
  3. import { io, Socket } from 'socket.io-client';
  4. import type {
  5. QuizContent,
  6. QuizState,
  7. ExamSocketMessage,
  8. ExamSocketRoomMessage,
  9. Answer,
  10. CumulativeResult
  11. } from '../types.ts';
  12. interface FullExamSocketMessage extends Omit<ExamSocketMessage, 'timestamp'> {
  13. id: string;
  14. from: string;
  15. timestamp: string;
  16. }
  17. import { useAuth } from "../../../hooks.tsx";
  18. // 工具函数:统一错误处理
  19. const handleAsyncOperation = async <T>(
  20. operation: () => Promise<T>,
  21. errorMessage: string
  22. ): Promise<T> => {
  23. try {
  24. return await operation();
  25. } catch (error) {
  26. console.error(`${errorMessage}:`, error);
  27. throw error;
  28. }
  29. };
  30. // 计算收益的辅助函数
  31. interface ProfitResult {
  32. profitAmount: number; // 金额收益
  33. profitPercent: number; // 百分比收益
  34. }
  35. function calculateProfit(currentPrice: number, previousPrice: number, holdingStock: string): ProfitResult {
  36. if (holdingStock === '1') {
  37. const profitAmount = currentPrice - previousPrice;
  38. const profitPercent = ((currentPrice - previousPrice) / previousPrice) * 100;
  39. return { profitAmount, profitPercent };
  40. }
  41. return { profitAmount: 0, profitPercent: 0 };
  42. }
  43. // 提前声明函数
  44. function getAnswers(client: Socket | null, roomId: string, questionId: string): Promise<Answer[]> {
  45. if (!client) return Promise.resolve([]);
  46. return new Promise((resolve) => {
  47. client.emit('exam:getAnswers', { roomId, questionId }, (answers: Answer[]) => {
  48. resolve(answers || []);
  49. });
  50. });
  51. }
  52. export function useSocketClient(roomId: string | null) {
  53. const { token } = useAuth();
  54. const queryClient = useQueryClient();
  55. const [socket, setSocket] = useState<Socket | null>(null);
  56. // const [currentQuestion, setCurrentQuestion] = useState<QuizState | null>(null);
  57. const [lastMessage, setLastMessage] = useState<ExamSocketRoomMessage | null>(null);
  58. // 初始化socket连接
  59. const { data: client } = useQuery({
  60. queryKey: ['socket-client', token],
  61. queryFn: async () => {
  62. if (!token) return null;
  63. const newSocket = io('/', {
  64. path: '/socket.io',
  65. transports: ['websocket'],
  66. withCredentials: true,
  67. query: {
  68. socket_token: token
  69. },
  70. reconnection: true,
  71. reconnectionAttempts: 5,
  72. reconnectionDelay: 1000,
  73. });
  74. newSocket.on('connect', () => {
  75. console.log('Socket connected');
  76. });
  77. newSocket.on('disconnect', () => {
  78. console.log('Socket disconnected');
  79. });
  80. newSocket.on('error', (error) => {
  81. console.error('Socket error:', error);
  82. });
  83. setSocket(newSocket);
  84. return newSocket;
  85. },
  86. enabled: !!token && !!roomId,
  87. staleTime: Infinity,
  88. gcTime: 0,
  89. retry: 3,
  90. });
  91. // 加入房间
  92. const joinRoom = useCallback(async (roomId: string) => {
  93. if (client) {
  94. client.emit('exam:join', { roomId });
  95. }
  96. }, [client]);
  97. // 离开房间
  98. const leaveRoom = useCallback(async (roomId: string) => {
  99. if (client) {
  100. client.emit('exam:leave', { roomId });
  101. }
  102. }, [client]);
  103. // 发送房间消息
  104. const sendRoomMessage = useCallback(async (roomId: string, message: ExamSocketMessage) => {
  105. if (client) {
  106. client.emit('exam:message', { roomId, message });
  107. }
  108. }, [client]);
  109. // 监听房间消息
  110. const onRoomMessage = useCallback((callback: (data: ExamSocketRoomMessage) => void) => {
  111. if (client) {
  112. client.on('exam:message', (data) => {
  113. setLastMessage(data);
  114. callback(data);
  115. });
  116. }
  117. }, [client]);
  118. // // 监听当前问题变化
  119. // useEffect(() => {
  120. // if (!client || !roomId) return;
  121. // const handleQuestionUpdate = (question:QuizState ) => {
  122. // setCurrentQuestion(question);
  123. // };
  124. // client.on('exam:question', handleQuestionUpdate);
  125. // return () => {
  126. // client.off('exam:question', handleQuestionUpdate);
  127. // };
  128. // }, [client, roomId]);
  129. // // 监听用户答案变化
  130. // useEffect(() => {
  131. // if (!client || !roomId) return;
  132. // const handleAnswersUpdate = async () => {
  133. // const answers = await getAnswers(client, roomId, 'current_state');
  134. // setUserAnswers(answers);
  135. // };
  136. // client.on('exam:answers', handleAnswersUpdate);
  137. // return () => {
  138. // client.off('exam:answers', handleAnswersUpdate);
  139. // };
  140. // }, [client, roomId]);
  141. // 存储答案
  142. const storeAnswer = useCallback(async (roomId: string, questionId: string, userId: string, answer: QuizContent, callback?: (success: Answer[]) => void) => {
  143. if (!client) return;
  144. return handleAsyncOperation(async () => {
  145. // 获取历史价格数据
  146. const pricesData = await new Promise<any>((resolve) => {
  147. client.emit('exam:getPrices', { roomId }, resolve);
  148. });
  149. if (!pricesData) {
  150. // 存储初始答案
  151. const initialAnswer: Answer = {
  152. ...answer,
  153. userId,
  154. holdingStock: '0',
  155. holdingCash: '0',
  156. profitAmount: 0,
  157. profitPercent: 0,
  158. totalProfitAmount: 0,
  159. totalProfitPercent: 0
  160. };
  161. client.emit('exam:storeAnswer', {
  162. roomId,
  163. questionId,
  164. userId,
  165. answer: initialAnswer
  166. }, (success: boolean) => {
  167. callback?.([initialAnswer]);
  168. });
  169. return;
  170. }
  171. // 获取该用户的所有历史答案
  172. const dates = Object.keys(pricesData).sort();
  173. const allUserAnswers = await getUserAnswers(roomId, userId);
  174. const userAnswers = allUserAnswers
  175. .filter((a: Answer) => a.date !== answer.date)
  176. .filter((a: Answer) => dates.includes(a.date || ''))
  177. .map((a: Answer) => ({
  178. ...a,
  179. price: pricesData[a.date || '']?.price || '0'
  180. }))
  181. .sort((a: Answer, b: Answer) => new Date(a.date || '').getTime() - new Date(b.date || '').getTime());
  182. let totalProfitAmount = 0;
  183. let totalProfitPercent = 0;
  184. if (userAnswers.length > 0) {
  185. const prevAnswer = userAnswers[userAnswers.length - 1];
  186. const { profitAmount, profitPercent } = calculateProfit(
  187. parseFloat(String(answer.price)),
  188. parseFloat(String(prevAnswer.price)),
  189. prevAnswer.holdingStock as string
  190. );
  191. totalProfitAmount = (prevAnswer.totalProfitAmount || 0) + profitAmount;
  192. totalProfitPercent = (prevAnswer.totalProfitPercent || 0) + profitPercent;
  193. }
  194. // 存储带有收益信息的答案
  195. const answerWithProfit: Answer = {
  196. ...answer,
  197. userId,
  198. profitAmount: userAnswers.length > 0 ? totalProfitAmount - (userAnswers[userAnswers.length - 1].totalProfitAmount || 0) : 0,
  199. profitPercent: userAnswers.length > 0 ? totalProfitPercent - (userAnswers[userAnswers.length - 1].totalProfitPercent || 0) : 0,
  200. totalProfitAmount,
  201. totalProfitPercent
  202. };
  203. client.emit('exam:storeAnswer', {
  204. roomId,
  205. questionId,
  206. userId,
  207. answer: answerWithProfit
  208. }, (success: boolean) => {
  209. callback?.([...userAnswers, answerWithProfit]);
  210. });
  211. }, '存储答案失败');
  212. }, [client]);
  213. // 清理房间数据
  214. const cleanupRoom = useCallback(async (roomId: string, questionId?: string) => {
  215. if (!client) return;
  216. await handleAsyncOperation(async () => {
  217. if (questionId) {
  218. client.emit('exam:cleanup', { roomId, questionId });
  219. } else {
  220. client.emit('exam:cleanup', { roomId });
  221. }
  222. }, '清理房间数据失败');
  223. }, [client]);
  224. // 发送下一题
  225. const sendNextQuestion = useCallback(async (roomId: string, state: QuizState) => {
  226. if (!client) return;
  227. return handleAsyncOperation(async () => {
  228. const message: FullExamSocketMessage = {
  229. id: `question-${Date.now()}`,
  230. type: 'question',
  231. from: 'system',
  232. timestamp: Date.now().toString(),
  233. content: {
  234. date: state.date,
  235. price: state.price,
  236. holdingStock: '0',
  237. holdingCash: '0',
  238. userId: 'system'
  239. }
  240. };
  241. // 存储当前问题状态
  242. await storeAnswer(roomId, 'current_state', 'system', {
  243. date: state.date,
  244. price: state.price,
  245. holdingStock: '0',
  246. holdingCash: '0',
  247. userId: 'system'
  248. });
  249. // 存储价格历史记录
  250. client.emit('exam:storePrice', {
  251. roomId,
  252. date: state.date,
  253. price: state.price
  254. });
  255. await sendRoomMessage(roomId, message);
  256. }, '发送题目失败');
  257. }, [client, sendRoomMessage, storeAnswer]);
  258. // 获取历史价格
  259. const getPriceHistory = useCallback(async (roomId: string, date: string): Promise<string> => {
  260. if (!client) return '0';
  261. return handleAsyncOperation(async () => {
  262. return new Promise((resolve) => {
  263. client.emit('exam:getPrice', { roomId, date }, (price: string) => {
  264. resolve(price || '0');
  265. });
  266. });
  267. }, '获取历史价格失败');
  268. }, [client]);
  269. // 获取答案 (封装为useCallback)
  270. const getAnswersCallback = useCallback((roomId: string, questionId: string): Promise<Answer[]> => {
  271. if (!client) return Promise.resolve([]);
  272. return handleAsyncOperation(async () => {
  273. return getAnswers(client, roomId, questionId);
  274. }, '获取答案失败');
  275. }, [client]);
  276. // 清理socket连接
  277. useEffect(() => {
  278. return () => {
  279. if (socket) {
  280. socket.disconnect();
  281. }
  282. };
  283. }, [socket]);
  284. // 导出所有功能作为单个对象
  285. const socketRoom = {
  286. client,
  287. joinRoom,
  288. leaveRoom,
  289. sendRoomMessage,
  290. onRoomMessage
  291. };
  292. // 获取用户答案
  293. const getUserAnswers = useCallback(async (roomId: string, userId: string): Promise<Answer[]> => {
  294. if (!client || !roomId || !userId) return Promise.resolve([]);
  295. return handleAsyncOperation(async () => {
  296. return new Promise((resolve) => {
  297. client.emit('exam:getUserAnswers', { roomId, userId }, (answers: Answer[]) => {
  298. resolve(answers || []);
  299. });
  300. });
  301. }, '获取用户答案失败');
  302. }, [client]);
  303. const getCurrentQuestion = useCallback(async (roomId: string): Promise<QuizState> => {
  304. if (!client) return Promise.reject(new Error('Socket not connected'));
  305. return handleAsyncOperation(async () => {
  306. return new Promise((resolve, reject) => {
  307. client.emit('exam:currentQuestion', { roomId }, (question: QuizState) => {
  308. if (!question) {
  309. reject(new Error('No current question available'));
  310. return;
  311. }
  312. resolve(question);
  313. });
  314. });
  315. }, '获取当前问题失败');
  316. }, [client])
  317. const answerManagement = {
  318. storeAnswer,
  319. getAnswers: getAnswersCallback,
  320. cleanupRoom,
  321. sendNextQuestion,
  322. getPriceHistory,
  323. getUserAnswers,
  324. getCurrentQuestion
  325. };
  326. // 计算累计结果
  327. // const calculateCumulativeResults = useCallback((answers: Answer[]): CumulativeResult[] => {
  328. // const userResults = new Map<string, CumulativeResult>();
  329. // answers.forEach((answer) => {
  330. // const userId = answer.userId;
  331. // if (!userResults.has(userId)) {
  332. // userResults.set(userId, {
  333. // userId,
  334. // totalProfitAmount: answer.totalProfitAmount || 0,
  335. // totalProfitPercent: answer.totalProfitPercent || 0
  336. // });
  337. // }
  338. // });
  339. // return Array.from(userResults.values());
  340. // }, []);
  341. return {
  342. socketRoom,
  343. answerManagement,
  344. // calculateCumulativeResults,
  345. // currentQuestion,
  346. // setCurrentQuestion,
  347. lastMessage,
  348. ...socketRoom,
  349. ...answerManagement
  350. };
  351. }