ExamAdmin.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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}/mobile/exam/card?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: { joinRoom, leaveRoom, client },
  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. setCurrentDate(question.date);
  91. setCurrentPrice(String(question.price));
  92. // 获取答题记录
  93. const answers = await answerManagement.getAnswers(
  94. classroom,
  95. ''
  96. );
  97. const processedAnswers = answers.map(answer => ({
  98. ...answer,
  99. profitAmount: answer.profitAmount || 0,
  100. profitPercent: answer.profitPercent || 0,
  101. holdingStock: answer.holdingStock || '0',
  102. holdingCash: answer.holdingCash || '0'
  103. }));
  104. setAnswers(processedAnswers);
  105. setDailyAnswers(prev => ({
  106. ...prev,
  107. [question.date]: processedAnswers
  108. }));
  109. }
  110. } catch (err) {
  111. console.error('初始化答题数据失败:', err);
  112. setError('初始化答题数据失败');
  113. } finally {
  114. setLoading(false);
  115. }
  116. };
  117. // 结算函数
  118. const handleSettlement = async () => {
  119. if (!classroom || answers.length === 0) return;
  120. setLoading(true);
  121. try {
  122. await answerManagement.sendSettleExam(classroom);
  123. message.success('结算成功');
  124. } catch (error) {
  125. console.error('结算失败:', error);
  126. message.error('结算失败');
  127. } finally {
  128. setLoading(false);
  129. }
  130. };
  131. const handleSubmit = async () => {
  132. if (!classroom || answers.length === 0) return;
  133. try {
  134. await answerManagement.cleanupRoom(classroom);
  135. message.success('答案提交成功');
  136. setAnswers([]);
  137. setDailyAnswers({});
  138. setCurrentDate('');
  139. setCurrentPrice('0');
  140. } catch (error: any) {
  141. console.error('提交答案失败:', error);
  142. message.error(error?.message || '提交答案失败');
  143. }
  144. };
  145. const handleRestart = async () => {
  146. if (!classroom) return;
  147. try {
  148. await answerManagement.cleanupRoom(classroom);
  149. setAnswers([]);
  150. setDailyAnswers({});
  151. setCurrentDate('');
  152. setCurrentPrice('0');
  153. message.success('已重新开始');
  154. } catch (error) {
  155. console.error('重新开始失败:', error);
  156. message.error('重新开始失败');
  157. }
  158. };
  159. const columns = [
  160. {
  161. title: '昵称',
  162. dataIndex: 'userId',
  163. key: 'userId',
  164. },
  165. {
  166. title: '日期',
  167. dataIndex: 'date',
  168. key: 'date',
  169. render: (text: string) => text ? dayjs(text).format('YYYY-MM-DD') : '-',
  170. },
  171. {
  172. title: '持股',
  173. dataIndex: 'holdingStock',
  174. key: 'holdingStock',
  175. },
  176. {
  177. title: '持币',
  178. dataIndex: 'holdingCash',
  179. key: 'holdingCash',
  180. },
  181. {
  182. title: '价格',
  183. dataIndex: 'price',
  184. key: 'price',
  185. render: (text: string | undefined) => text ? parseFloat(text).toFixed(2) : '-',
  186. },
  187. {
  188. title: '收益(元)',
  189. dataIndex: 'profitAmount',
  190. key: 'profitAmount',
  191. render: (text: number | undefined) => text !== undefined ? text.toFixed(2) : '-',
  192. },
  193. {
  194. title: '盈亏率',
  195. dataIndex: 'profitPercent',
  196. key: 'profitPercent',
  197. render: (text: number | undefined) => text !== undefined ? `${text.toFixed(2)}%` : '-',
  198. }
  199. ];
  200. const resultColumns: ColumnType[] = [
  201. {
  202. title: '昵称',
  203. dataIndex: 'userId',
  204. key: 'userId',
  205. },
  206. {
  207. title: '累计盈亏(元)',
  208. dataIndex: 'totalProfitAmount',
  209. key: 'totalProfitAmount',
  210. render: (text: number | undefined) => text !== undefined ? text.toFixed(2) : '-',
  211. },
  212. {
  213. title: '累计盈亏率',
  214. dataIndex: 'totalProfitPercent',
  215. key: 'totalProfitPercent',
  216. render: (text: number | undefined) => text !== undefined ? `${text.toFixed(2)}%` : '-',
  217. },
  218. ];
  219. const dailyAnswersColumns = [
  220. {
  221. title: '日期',
  222. dataIndex: 'date',
  223. key: 'date',
  224. render: (text: string) => dayjs(text).format('YYYY-MM-DD'),
  225. },
  226. {
  227. title: '答题人数',
  228. key: 'count',
  229. render: (_: any, record: { date: string }) => dailyAnswers[record.date]?.length || 0,
  230. },
  231. {
  232. title: '持股人数',
  233. key: 'holdingStockCount',
  234. render: (_: any, record: { date: string }) =>
  235. dailyAnswers[record.date]?.filter((a: any) => a.holdingStock === '1').length || 0,
  236. },
  237. {
  238. title: '持币人数',
  239. key: 'holdingCashCount',
  240. render: (_: any, record: { date: string }) =>
  241. dailyAnswers[record.date]?.filter((a: any) => a.holdingCash === '1').length || 0,
  242. }
  243. ];
  244. // 计算累计结果的函数
  245. const calculateCumulativeResults = (dailyAnswers: {[key: string]: Answer[]}): CumulativeResult[] => {
  246. const userResults = new Map<string, CumulativeResult>();
  247. // 按日期排序
  248. const sortedDates = Object.keys(dailyAnswers).sort((a: string, b: string) =>
  249. new Date(a).getTime() - new Date(b).getTime()
  250. );
  251. sortedDates.forEach(date => {
  252. const answers = dailyAnswers[date] || [];
  253. answers.forEach((answer: Answer) => {
  254. const userId = answer.userId;
  255. // 直接使用服务端计算好的收益数据
  256. const profitAmount = answer.profitAmount || 0;
  257. const profitPercent = answer.profitPercent || 0;
  258. if (!userResults.has(userId)) {
  259. userResults.set(userId, {
  260. userId,
  261. totalProfitAmount: 0,
  262. totalProfitPercent: 0
  263. });
  264. }
  265. const currentResult = userResults.get(userId)!;
  266. currentResult.totalProfitAmount += profitAmount;
  267. currentResult.totalProfitPercent += profitPercent;
  268. userResults.set(userId, currentResult);
  269. });
  270. });
  271. return Array.from(userResults.values());
  272. };
  273. const items = [
  274. {
  275. key: 'current',
  276. label: '当前答题情况',
  277. children: <CurrentAnswers answers={answers} columns={columns} />,
  278. },
  279. {
  280. key: 'daily',
  281. label: '每日答题统计',
  282. children: <DailyStatistics dailyAnswers={dailyAnswers} columns={dailyAnswersColumns} />,
  283. },
  284. {
  285. key: 'cumulative',
  286. label: '累计结果',
  287. children: <CumulativeResults
  288. results={calculateCumulativeResults(dailyAnswers)}
  289. columns={resultColumns}
  290. />,
  291. },
  292. ];
  293. // 加入/离开房间
  294. useEffect(() => {
  295. if (!classroom) return;
  296. joinRoom(classroom);
  297. initExamData();
  298. return () => {
  299. leaveRoom(classroom);
  300. };
  301. }, [classroom, joinRoom, leaveRoom]);
  302. // 监听答题消息并更新答案
  303. useEffect(() => {
  304. if (!classroom || !currentDate || !client) return;
  305. const handleAnswerMessage = async () => {
  306. try {
  307. const answers = await answerManagement.getAnswers(
  308. classroom as string,
  309. currentDate
  310. );
  311. const processedAnswers = answers.map(answer => ({
  312. ...answer,
  313. profitAmount: answer.profitAmount || 0,
  314. profitPercent: answer.profitPercent || 0,
  315. holdingStock: answer.holdingStock || '0',
  316. holdingCash: answer.holdingCash || '0'
  317. }));
  318. setAnswers(processedAnswers);
  319. setDailyAnswers(prev => ({
  320. ...prev,
  321. [currentDate]: processedAnswers
  322. }));
  323. } catch (error) {
  324. console.error('获取答案失败:', error);
  325. }
  326. };
  327. client.on('exam:answerUpdated', handleAnswerMessage);
  328. return () => {
  329. if (!client) return;
  330. client.off('exam:answerUpdated', handleAnswerMessage);
  331. };
  332. }, [classroom, currentDate, answerManagement, client]);
  333. // 监听当前问题变化
  334. useEffect(() => {
  335. if (!client ) return;
  336. const handleQuestionUpdate = (question:QuizState ) => {
  337. setCurrentDate(question.date);
  338. setCurrentPrice(String(question.price));
  339. };
  340. client.on('exam:question', handleQuestionUpdate);
  341. return () => {
  342. client.off('exam:question', handleQuestionUpdate);
  343. };
  344. }, [client]);
  345. return (
  346. <div className="p-6">
  347. <div className="mb-6 flex justify-between items-center">
  348. <div>
  349. <h2 className="text-2xl font-bold">答题卡管理</h2>
  350. <div className="mt-2 text-gray-600">
  351. <span className="mr-4">教室号: {classroom}</span>
  352. <span className="mr-4">当前日期: {currentDate}</span>
  353. <span>当前价格: {currentPrice}</span>
  354. </div>
  355. </div>
  356. </div>
  357. {/* 主要内容区域 */}
  358. <div className="mb-6">
  359. <Tabs
  360. activeKey={activeTab}
  361. onChange={setActiveTab}
  362. items={items}
  363. />
  364. </div>
  365. {/* 底部按钮组 */}
  366. <div className="flex items-center space-x-4 mb-8">
  367. <Button onClick={handleSettlement} disabled={answers.length === 0}>
  368. 结算
  369. </Button>
  370. <Button type="primary" onClick={handleSubmit} disabled={answers.length === 0}>
  371. 收卷
  372. </Button>
  373. <Input
  374. value={mark}
  375. onChange={(e) => setMark(e.target.value)}
  376. placeholder="标记"
  377. style={{ width: 200 }}
  378. />
  379. <Button onClick={() => message.info('标记已保存')}>查看</Button>
  380. <Button onClick={handleRestart}>重开</Button>
  381. </div>
  382. {/* 二维码区域 */}
  383. <QRCodeSection classroom={classroom || ''} />
  384. </div>
  385. );
  386. }