ExamAdmin.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. import React, { useState, useEffect } from 'react';
  2. import { useSearchParams } from 'react-router';
  3. import { Table, Button, message, Input, QRCode, Modal, Tabs } from 'antd';
  4. // import type { ColumnType } from 'antd/es/table';
  5. import type { GetProp , TableProps} from 'antd';
  6. import dayjs from 'dayjs';
  7. import { useSocketClient } from './hooks/useSocketClient.ts';
  8. import type {
  9. QuizState,
  10. ExamSocketRoomMessage
  11. } from './types.ts';
  12. import type { Answer, CumulativeResult } from './types.ts';
  13. type ColumnType = GetProp<TableProps,'columns'>[number]
  14. // 当前答题情况组件
  15. function CurrentAnswers({ answers, columns }: { answers: Answer[], columns: any[] }) {
  16. return (
  17. <div>
  18. <Table
  19. columns={columns}
  20. dataSource={answers}
  21. rowKey={(record) => `${record.userId}-${record.date}`}
  22. pagination={false}
  23. />
  24. </div>
  25. );
  26. }
  27. // 每日统计组件
  28. function DailyStatistics({ dailyAnswers, columns }: { dailyAnswers: {[key: string]: Answer[]}, columns: any[] }) {
  29. return (
  30. <div>
  31. <Table
  32. columns={columns}
  33. dataSource={Object.keys(dailyAnswers).map(date => ({ date }))}
  34. rowKey="date"
  35. pagination={false}
  36. />
  37. </div>
  38. );
  39. }
  40. // 累计结果组件
  41. function CumulativeResults({ results, columns }: { results: CumulativeResult[], columns: any[] }) {
  42. return (
  43. <div>
  44. <Table
  45. columns={columns}
  46. dataSource={results}
  47. rowKey="userId"
  48. pagination={false}
  49. />
  50. </div>
  51. );
  52. }
  53. // 二维码组件
  54. function QRCodeSection({ classroom }: { classroom: string }) {
  55. return (
  56. <div className="text-center">
  57. <div className="text-gray-600 mb-2">扫码参与训练</div>
  58. <div className="inline-block p-4 bg-white rounded-lg shadow-md">
  59. <QRCode value={`${globalThis.location.origin}/exam?classroom=${classroom}`} />
  60. </div>
  61. </div>
  62. );
  63. }
  64. export default function ExamAdmin() {
  65. const [searchParams] = useSearchParams();
  66. const classroom = searchParams.get('classroom');
  67. const {
  68. socketRoom,
  69. answerManagement,
  70. currentQuestion,
  71. setCurrentQuestion,
  72. // calculateCumulativeResults
  73. } = useSocketClient(classroom as string);
  74. const [answers, setAnswers] = useState<Answer[]>([]);
  75. const [dailyAnswers, setDailyAnswers] = useState<{[key: string]: Answer[]}>({});
  76. const [currentDate, setCurrentDate] = useState('');
  77. const [currentPrice, setCurrentPrice] = useState('0');
  78. const [mark, setMark] = useState('');
  79. const [activeTab, setActiveTab] = useState('current');
  80. const [loading, setLoading] = useState(false);
  81. const [error, setError] = useState<string | null>(null);
  82. const initExamData = async () => {
  83. if (!classroom) return;
  84. setLoading(true);
  85. setError(null);
  86. try {
  87. // 获取当前问题
  88. const question = await answerManagement.getCurrentQuestion(classroom);
  89. if (question) {
  90. setCurrentQuestion(question);
  91. // 获取答题记录
  92. const answers = await answerManagement.getAnswers(
  93. classroom,
  94. ''
  95. );
  96. const processedAnswers = answers.map(answer => ({
  97. ...answer,
  98. profitAmount: answer.profitAmount || 0,
  99. profitPercent: answer.profitPercent || 0,
  100. holdingStock: answer.holdingStock || '0',
  101. holdingCash: answer.holdingCash || '0'
  102. }));
  103. setAnswers(processedAnswers);
  104. setDailyAnswers(prev => ({
  105. ...prev,
  106. [question.date]: processedAnswers
  107. }));
  108. }
  109. } catch (err) {
  110. console.error('初始化答题数据失败:', err);
  111. setError('初始化答题数据失败');
  112. } finally {
  113. setLoading(false);
  114. }
  115. };
  116. // 加入/离开房间
  117. useEffect(() => {
  118. if (!classroom) return;
  119. socketRoom.joinRoom(classroom);
  120. initExamData();
  121. return () => {
  122. socketRoom.leaveRoom(classroom);
  123. };
  124. }, [classroom, socketRoom.joinRoom, socketRoom.leaveRoom]);
  125. // 监听答题消息并更新答案
  126. useEffect(() => {
  127. if (!classroom || !currentDate || !socketRoom.client) return;
  128. const handleAnswerMessage = async () => {
  129. try {
  130. const answers = await answerManagement.getAnswers(
  131. classroom as string,
  132. currentDate
  133. );
  134. const processedAnswers = answers.map(answer => ({
  135. ...answer,
  136. profitAmount: answer.profitAmount || 0,
  137. profitPercent: answer.profitPercent || 0,
  138. holdingStock: answer.holdingStock || '0',
  139. holdingCash: answer.holdingCash || '0'
  140. }));
  141. setAnswers(processedAnswers);
  142. setDailyAnswers(prev => ({
  143. ...prev,
  144. [currentDate]: processedAnswers
  145. }));
  146. } catch (error) {
  147. console.error('获取答案失败:', error);
  148. }
  149. };
  150. socketRoom.client.on('exam:answer', handleAnswerMessage);
  151. return () => {
  152. if (!socketRoom.client) return;
  153. socketRoom.client.off('exam:answer', handleAnswerMessage);
  154. };
  155. }, [classroom, currentDate, answerManagement, socketRoom]);
  156. // // 更新答案状态
  157. // useEffect(() => {
  158. // if (cachedAnswers && cachedAnswers.length > 0) {
  159. // setAnswers(cachedAnswers);
  160. // }
  161. // }, [cachedAnswers]);
  162. // // 更新每日答题情况
  163. // useEffect(() => {
  164. // if (currentDate && cachedAnswers) {
  165. // setDailyAnswers((prev: {[key: string]: Answer[]}) => ({
  166. // ...prev,
  167. // [currentDate]: cachedAnswers
  168. // }));
  169. // }
  170. // }, [currentDate, cachedAnswers]);
  171. useEffect(() => {
  172. if (currentQuestion) {
  173. console.log('currentQuestion', currentQuestion);
  174. setCurrentDate(currentQuestion.date);
  175. setCurrentPrice(String(currentQuestion.price));
  176. }
  177. }, [currentQuestion]);
  178. // 添加结算函数
  179. const handleSettlement = async () => {
  180. if (!classroom || answers.length === 0) return;
  181. try {
  182. await answerManagement.sendNextQuestion(classroom, {
  183. date: currentDate,
  184. price: currentPrice
  185. });
  186. message.success('结算成功');
  187. } catch (error) {
  188. console.error('结算失败:', error);
  189. message.error('结算失败');
  190. }
  191. };
  192. const handleSubmit = async () => {
  193. if (!classroom || answers.length === 0) return;
  194. try {
  195. await answerManagement.cleanupRoom(classroom, currentDate);
  196. message.success('答案提交成功');
  197. setAnswers([]);
  198. } catch (error: any) {
  199. console.error('提交答案失败:', error);
  200. message.error(error?.message || '提交答案失败');
  201. }
  202. };
  203. const handleRestart = async () => {
  204. if (!classroom) return;
  205. try {
  206. await answerManagement.cleanupRoom(classroom);
  207. setAnswers([]);
  208. setDailyAnswers({});
  209. setCurrentDate('');
  210. setCurrentPrice('0');
  211. message.success('已重新开始');
  212. } catch (error) {
  213. console.error('重新开始失败:', error);
  214. message.error('重新开始失败');
  215. }
  216. };
  217. const columns = [
  218. {
  219. title: '昵称',
  220. dataIndex: 'userId',
  221. key: 'userId',
  222. },
  223. {
  224. title: '日期',
  225. dataIndex: 'date',
  226. key: 'date',
  227. render: (text: string) => text ? dayjs(text).format('YYYY-MM-DD') : '-',
  228. },
  229. {
  230. title: '持股',
  231. dataIndex: 'holdingStock',
  232. key: 'holdingStock',
  233. },
  234. {
  235. title: '持币',
  236. dataIndex: 'holdingCash',
  237. key: 'holdingCash',
  238. },
  239. {
  240. title: '价格',
  241. dataIndex: 'price',
  242. key: 'price',
  243. render: (text: string | undefined) => text ? parseFloat(text).toFixed(2) : '-',
  244. },
  245. {
  246. title: '收益(元)',
  247. dataIndex: 'profitAmount',
  248. key: 'profitAmount',
  249. render: (text: number | undefined) => text !== undefined ? text.toFixed(2) : '-',
  250. },
  251. {
  252. title: '盈亏率',
  253. dataIndex: 'profitPercent',
  254. key: 'profitPercent',
  255. render: (text: number | undefined) => text !== undefined ? `${text.toFixed(2)}%` : '-',
  256. }
  257. ];
  258. const resultColumns: ColumnType[] = [
  259. {
  260. title: '昵称',
  261. dataIndex: 'userId',
  262. key: 'userId',
  263. },
  264. {
  265. title: '累计盈亏(元)',
  266. dataIndex: 'totalProfitAmount',
  267. key: 'totalProfitAmount',
  268. render: (text: number | undefined) => text !== undefined ? text.toFixed(2) : '-',
  269. },
  270. {
  271. title: '累计盈亏率',
  272. dataIndex: 'totalProfitPercent',
  273. key: 'totalProfitPercent',
  274. render: (text: number | undefined) => text !== undefined ? `${text.toFixed(2)}%` : '-',
  275. },
  276. ];
  277. const dailyAnswersColumns = [
  278. {
  279. title: '日期',
  280. dataIndex: 'date',
  281. key: 'date',
  282. render: (text: string) => dayjs(text).format('YYYY-MM-DD'),
  283. },
  284. {
  285. title: '答题人数',
  286. key: 'count',
  287. render: (_: any, record: { date: string }) => dailyAnswers[record.date]?.length || 0,
  288. },
  289. {
  290. title: '持股人数',
  291. key: 'holdingStockCount',
  292. render: (_: any, record: { date: string }) =>
  293. dailyAnswers[record.date]?.filter((a: any) => a.holdingStock === '1').length || 0,
  294. },
  295. {
  296. title: '持币人数',
  297. key: 'holdingCashCount',
  298. render: (_: any, record: { date: string }) =>
  299. dailyAnswers[record.date]?.filter((a: any) => a.holdingCash === '1').length || 0,
  300. }
  301. ];
  302. // 计算累计结果的函数
  303. const calculateCumulativeResults = (dailyAnswers: {[key: string]: Answer[]}): CumulativeResult[] => {
  304. const userResults = new Map<string, CumulativeResult>();
  305. // 按日期排序
  306. const sortedDates = Object.keys(dailyAnswers).sort((a: string, b: string) =>
  307. new Date(a).getTime() - new Date(b).getTime()
  308. );
  309. sortedDates.forEach(date => {
  310. const answers = dailyAnswers[date] || [];
  311. answers.forEach((answer: Answer) => {
  312. const userId = answer.userId;
  313. // 直接使用服务端计算好的收益数据
  314. const profitAmount = answer.profitAmount || 0;
  315. const profitPercent = answer.profitPercent || 0;
  316. if (!userResults.has(userId)) {
  317. userResults.set(userId, {
  318. userId,
  319. totalProfitAmount: 0,
  320. totalProfitPercent: 0
  321. });
  322. }
  323. const currentResult = userResults.get(userId)!;
  324. currentResult.totalProfitAmount += profitAmount;
  325. currentResult.totalProfitPercent += profitPercent;
  326. userResults.set(userId, currentResult);
  327. });
  328. });
  329. return Array.from(userResults.values());
  330. };
  331. const items = [
  332. {
  333. key: 'current',
  334. label: '当前答题情况',
  335. children: <CurrentAnswers answers={answers} columns={columns} />,
  336. },
  337. {
  338. key: 'daily',
  339. label: '每日答题统计',
  340. children: <DailyStatistics dailyAnswers={dailyAnswers} columns={dailyAnswersColumns} />,
  341. },
  342. {
  343. key: 'cumulative',
  344. label: '累计结果',
  345. children: <CumulativeResults
  346. results={calculateCumulativeResults(dailyAnswers)}
  347. columns={resultColumns}
  348. />,
  349. },
  350. ];
  351. return (
  352. <div className="p-6">
  353. <div className="mb-6 flex justify-between items-center">
  354. <div>
  355. <h2 className="text-2xl font-bold">答题卡管理</h2>
  356. <div className="mt-2 text-gray-600">
  357. <span className="mr-4">教室号: {classroom}</span>
  358. <span className="mr-4">当前日期: {currentDate}</span>
  359. <span>当前价格: {currentPrice}</span>
  360. </div>
  361. </div>
  362. </div>
  363. {/* 主要内容区域 */}
  364. <div className="mb-6">
  365. <Tabs
  366. activeKey={activeTab}
  367. onChange={setActiveTab}
  368. items={items}
  369. />
  370. </div>
  371. {/* 底部按钮组 */}
  372. <div className="flex items-center space-x-4 mb-8">
  373. <Button onClick={handleSettlement} disabled={answers.length === 0}>
  374. 结算
  375. </Button>
  376. <Button type="primary" onClick={handleSubmit} disabled={answers.length === 0}>
  377. 收卷
  378. </Button>
  379. <Input
  380. value={mark}
  381. onChange={(e) => setMark(e.target.value)}
  382. placeholder="标记"
  383. style={{ width: 200 }}
  384. />
  385. <Button onClick={() => message.info('标记已保存')}>查看</Button>
  386. <Button onClick={handleRestart}>重开</Button>
  387. </div>
  388. {/* 二维码区域 */}
  389. <QRCodeSection classroom={classroom || ''} />
  390. </div>
  391. );
  392. }