useSocketClient.ts 11 KB

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