yearning
12 小时以前 3f96c9c6502243b06efd4bb34a189e72e3a5557c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import {
  Button,
  Card,
  Descriptions,
  Form,
  Grid,
  Input,
  Radio,
  Select,
  Spin,
  Tag,
  Typography,
} from "antd";
import { DoubleLeftOutlined, DoubleRightOutlined } from "@ant-design/icons";
import { api } from "../api";
import {
  attemptDetailPath,
  readScoreListQuery,
  type ScoreListQuery,
} from "../scoreQueryParams";
import "./AttemptReviewPage.css";
 
const { useBreakpoint } = Grid;
const { Title } = Typography;
 
const SECTION_CN = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
 
type Q = {
  external_item_id: string;
  part_name?: string;
  item_order?: number;
  title_html?: string;
  detail_json?: string;
  reference_answer?: string;
  user_answer?: string;
  is_correct: boolean;
  score: number;
  max_score?: number;
};
 
type Part = { part_name: string; questions: Q[] };
 
type Attempt = {
  attempt_id: string;
  examinee_name?: string;
  id_card?: string;
  score: number;
  paper_total_score?: number;
  paper_name?: string;
  subject_name?: string;
  room_id?: string;
  seat_number?: string;
  start_time?: string;
  end_time?: string;
  parts: Part[];
};
 
type FlatItem = { key: string; part: string; q: Q; idx: number; displayNo: number };
 
function stripHtml(html: string) {
  return html.replace(/<[^>]+>/g, "");
}
 
function isAnswered(q: Q) {
  return Boolean(q.user_answer?.trim());
}
 
function bubbleClassName(q: Q, isActive: boolean) {
  const classes = ["attempt-review__bubble"];
  if (!isAnswered(q)) classes.push("attempt-review__bubble--unanswered");
  else if (q.is_correct) classes.push("attempt-review__bubble--correct");
  else classes.push("attempt-review__bubble--wrong");
  if (isActive) classes.push("attempt-review__bubble--active");
  return classes.join(" ");
}
 
function parseOptions(detail_json?: string) {
  if (!detail_json) return [];
  try {
    const o = JSON.parse(detail_json);
    const qs = o?.item?.questions;
    if (Array.isArray(qs) && qs[0]?.options) return qs[0].options;
  } catch {
    /* ignore */
  }
  return [];
}
 
function scrollChildIntoContainer(container: HTMLElement, el: HTMLElement) {
  const cRect = container.getBoundingClientRect();
  const eRect = el.getBoundingClientRect();
  const nextTop = container.scrollTop + (eRect.top - cRect.top);
  container.scrollTo({ top: Math.max(0, nextTop), behavior: "auto" });
}
 
function QuestionIndex({
  parts,
  flat,
  activeKey,
  collapsed,
  onToggleCollapse,
  onJump,
  mobile,
}: {
  parts: Part[];
  flat: FlatItem[];
  activeKey: string | null;
  collapsed: boolean;
  onToggleCollapse: () => void;
  onJump: (key: string) => void;
  mobile?: boolean;
}) {
  const [typeFilter, setTypeFilter] = useState<string>("all");
 
  const visibleParts = useMemo(() => {
    if (typeFilter === "all") return parts;
    return parts.filter((p) => p.part_name === typeFilter);
  }, [parts, typeFilter]);
 
  return (
    <aside
      className={[
        "attempt-review__index",
        mobile ? "attempt-review__index-mobile" : "",
        collapsed && !mobile ? "attempt-review__index--collapsed" : "",
      ]
        .filter(Boolean)
        .join(" ")}
      aria-label="题目索引"
    >
      <div className="attempt-review__index-toolbar">
        {!mobile && (
          <Button
            type="text"
            size="small"
            icon={collapsed ? <DoubleRightOutlined /> : <DoubleLeftOutlined />}
            onClick={onToggleCollapse}
            aria-label={collapsed ? "展开索引侧栏" : "收起索引侧栏"}
          />
        )}
      </div>
      {collapsed && !mobile ? (
        <div className="attempt-review__index-collapsed-label">题目索引</div>
      ) : (
        <>
          <div className="attempt-review__index-filter">
            <Radio.Group
              size="small"
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
              className="attempt-review__type-radio"
            >
              <Radio.Button value="all">全部</Radio.Button>
              {parts.map((p) => (
                <Radio.Button key={p.part_name} value={p.part_name}>{p.part_name}</Radio.Button>
              ))}
            </Radio.Group>
          </div>
          <div className="attempt-review__index-body">
            {visibleParts.map((p) => {
              const sectionIdx = parts.findIndex((x) => x.part_name === p.part_name);
              const sectionLabel = `${SECTION_CN[sectionIdx] ?? sectionIdx + 1}、${p.part_name}`;
              return (
                <section key={p.part_name} className="attempt-review__section">
                  <h4 className="attempt-review__section-title">{sectionLabel}</h4>
                  <div className="attempt-review__bubble-grid">
                    {p.questions.map((q, i) => {
                      const meta = flat.find((f) => f.key === q.external_item_id);
                      const no = meta?.displayNo ?? (q.item_order ?? i) + 1;
                      const isActive = activeKey === q.external_item_id;
                      return (
                        <button
                          key={q.external_item_id}
                          type="button"
                          className={bubbleClassName(q, isActive)}
                          onClick={() => onJump(q.external_item_id)}
                          title={`第 ${no} 题`}
                        >
                          {no}
                        </button>
                      );
                    })}
                  </div>
                </section>
              );
            })}
          </div>
        </>
      )}
    </aside>
  );
}
 
type ScoreListItem = {
  attempt_id: string;
  name: string;
  id_card: string;
  subject_name: string;
  score: number;
};
 
const ROSTER_PAGE_SIZE = 40;
 
function AttemptRoster({
  activeAttemptId,
  listQuery,
  onSelectAttempt,
  onSearch,
}: {
  activeAttemptId: string;
  listQuery: ScoreListQuery;
  onSelectAttempt: (attemptId: string) => void;
  onSearch: (filters: Pick<ScoreListQuery, "name" | "id_card" | "subject">) => void;
}) {
  const [form] = Form.useForm<Pick<ScoreListQuery, "name" | "id_card" | "subject">>();
  const [subjects, setSubjects] = useState<string[]>([]);
  const [items, setItems] = useState<ScoreListItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    name: listQuery.name,
    id_card: listQuery.id_card,
    subject: listQuery.subject,
  });
  const scrollRef = useRef<HTMLDivElement>(null);
  const loadingMoreRef = useRef(false);
 
  useEffect(() => {
    form.setFieldsValue({
      name: listQuery.name,
      id_card: listQuery.id_card,
      subject: listQuery.subject,
    });
    setFilters({
      name: listQuery.name,
      id_card: listQuery.id_card,
      subject: listQuery.subject,
    });
  }, [listQuery.name, listQuery.id_card, listQuery.subject, form]);
 
  useEffect(() => {
    api.get<{ items: string[] }>("/api/subjects").then((r) => setSubjects(r.data.items));
  }, []);
 
  const fetchPage = useCallback(
    async (p: number, append: boolean) => {
      if (loadingMoreRef.current) return;
      loadingMoreRef.current = true;
      setLoading(true);
      try {
        const { data: res } = await api.get("/api/scores", {
          params: { page: p, page_size: ROSTER_PAGE_SIZE, ...filters },
        });
        setTotal(res.total);
        setPage(p);
        setItems((prev) => (append ? [...prev, ...res.items] : res.items));
      } finally {
        setLoading(false);
        loadingMoreRef.current = false;
      }
    },
    [filters]
  );
 
  useEffect(() => {
    fetchPage(1, false);
  }, [fetchPage]);
 
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onScroll = () => {
      if (loadingMoreRef.current || loading) return;
      if (items.length >= total) return;
      if (el.scrollHeight - el.scrollTop - el.clientHeight < 64) {
        fetchPage(page + 1, true);
      }
    };
    el.addEventListener("scroll", onScroll);
    return () => el.removeEventListener("scroll", onScroll);
  }, [loading, items.length, total, page, fetchPage]);
 
  useEffect(() => {
    const el = scrollRef.current?.querySelector<HTMLElement>(
      `[data-attempt-id="${activeAttemptId}"]`
    );
    el?.scrollIntoView({ block: "nearest" });
  }, [activeAttemptId, items]);
 
  return (
    <aside className="attempt-review__roster">
      <Form
        form={form}
        className="attempt-review__roster-form"
        size="small"
        layout="horizontal"
        labelAlign="right"
        colon={false}
        labelCol={{ flex: "0 0 52px" }}
        wrapperCol={{ flex: "1 1 0" }}
        onFinish={(v) => onSearch(v)}
      >
        <Form.Item name="name" label="姓名" className="attempt-review__roster-field">
          <Input allowClear />
        </Form.Item>
        <Form.Item name="id_card" label="证件号" className="attempt-review__roster-field">
          <Input allowClear />
        </Form.Item>
        <Form.Item name="subject" label="科目" className="attempt-review__roster-field">
          <Select allowClear options={subjects.map((s) => ({ value: s, label: s }))} />
        </Form.Item>
        <Button type="primary" htmlType="submit" block size="small">查询</Button>
      </Form>
      <div ref={scrollRef} className="attempt-review__roster-list">
        {items.map((row) => (
          <button
            key={row.attempt_id}
            type="button"
            data-attempt-id={row.attempt_id}
            className={[
              "attempt-review__roster-item",
              row.attempt_id === activeAttemptId ? "attempt-review__roster-item--active" : "",
            ]
              .filter(Boolean)
              .join(" ")}
            onClick={() => {
              if (row.attempt_id !== activeAttemptId) onSelectAttempt(row.attempt_id);
            }}
          >
            <div className="attempt-review__roster-name">{row.name || "—"}</div>
            <div className="attempt-review__roster-meta">
              <span>{row.score} 分</span>
              <span className="attempt-review__roster-subject">{row.subject_name}</span>
            </div>
          </button>
        ))}
        {loading && <div className="attempt-review__roster-hint">加载中…</div>}
        {!loading && items.length === 0 && <div className="attempt-review__roster-hint">无数据</div>}
        {!loading && items.length > 0 && items.length >= total && (
          <div className="attempt-review__roster-hint">已加载全部</div>
        )}
      </div>
    </aside>
  );
}
 
export default function AttemptReviewPage() {
  const { attemptId } = useParams();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const listQuery = readScoreListQuery(searchParams);
  const [data, setData] = useState<Attempt | null>(null);
  const [detailLoading, setDetailLoading] = useState(true);
  const [activeKey, setActiveKey] = useState<string | null>(null);
  const [indexCollapsed, setIndexCollapsed] = useState(false);
  const detailScrollRef = useRef<HTMLDivElement>(null);
  const screens = useBreakpoint();
  const isWide = !!screens.lg;
 
  const selectAttempt = useCallback(
    (id: string) => {
      if (id === attemptId) return;
      navigate(attemptDetailPath(id, listQuery), { replace: true, preventScrollReset: true });
    },
    [attemptId, listQuery, navigate]
  );
 
  const searchRoster = useCallback(
    (filters: Pick<ScoreListQuery, "name" | "id_card" | "subject">) => {
      navigate(
        attemptDetailPath(attemptId!, { ...filters, page: 1, page_size: listQuery.page_size }),
        { replace: true, preventScrollReset: true }
      );
    },
    [attemptId, listQuery.page_size, navigate]
  );
 
  useEffect(() => {
    if (!attemptId) return;
    let cancelled = false;
    setDetailLoading(true);
    setActiveKey(null);
    detailScrollRef.current?.scrollTo(0, 0);
    api
      .get<Attempt>(`/api/attempts/${attemptId}`)
      .then((r) => {
        if (!cancelled) setData(r.data);
      })
      .finally(() => {
        if (!cancelled) setDetailLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [attemptId]);
 
  useEffect(() => {
    const prev = document.documentElement.style.overflow;
    const prevBody = document.body.style.overflow;
    document.documentElement.style.overflow = "hidden";
    document.body.style.overflow = "hidden";
    return () => {
      document.documentElement.style.overflow = prev;
      document.body.style.overflow = prevBody;
    };
  }, []);
 
  const flat = useMemo(() => {
    if (!data) return [];
    const out: FlatItem[] = [];
    let n = 0;
    data.parts.forEach((p) =>
      p.questions.forEach((q, i) => {
        n += 1;
        out.push({
          key: q.external_item_id,
          part: p.part_name,
          q,
          idx: n,
          displayNo: (q.item_order ?? i) + 1,
        });
      })
    );
    return out;
  }, [data]);
 
  const jumpTo = useCallback((key: string) => {
    setActiveKey(key);
    requestAnimationFrame(() => {
      const container = detailScrollRef.current;
      const el = document.getElementById(`q-${key}`);
      if (!container || !el) return;
      scrollChildIntoContainer(container, el);
    });
  }, []);
 
  useEffect(() => {
    const container = detailScrollRef.current;
    if (!container || !data || flat.length === 0) return;
 
    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((e) => e.isIntersecting)
          .sort((a, b) => (a.boundingClientRect.top ?? 0) - (b.boundingClientRect.top ?? 0));
        const id = visible[0]?.target.id;
        if (id?.startsWith("q-")) {
          setActiveKey(id.replace("q-", ""));
        }
      },
      { root: container, rootMargin: "-8px 0px -70% 0px", threshold: 0 }
    );
 
    flat.forEach(({ key }) => {
      const el = document.getElementById(`q-${key}`);
      if (el) observer.observe(el);
    });
    return () => observer.disconnect();
  }, [data, flat]);
 
  const indexPanel = data ? (
    <QuestionIndex
      parts={data.parts}
      flat={flat}
      activeKey={activeKey}
      collapsed={indexCollapsed}
      onToggleCollapse={() => setIndexCollapsed((c) => !c)}
      onJump={jumpTo}
      mobile={!isWide}
    />
  ) : null;
 
  const detailPanel = data ? (
    <div className="attempt-review__detail-inner">
      {data.parts.map((p) => (
        <div key={p.part_name} id={`part-${p.part_name}`}>
          <Title level={5}>{p.part_name}</Title>
          {p.questions.map((q, i) => (
            <div key={q.external_item_id} id={`q-${q.external_item_id}`} className="attempt-review__question-anchor">
              <Card
                size="small"
                className="attempt-review__question-card"
                title={`第 ${(q.item_order ?? i) + 1} 题`}
              >
                <div dangerouslySetInnerHTML={{ __html: q.title_html || "" }} />
                <ul>
                  {parseOptions(q.detail_json).map((opt: { identifier: string; text: string }) => (
                    <li key={opt.identifier}>{opt.identifier}. {stripHtml(opt.text)}</li>
                  ))}
                </ul>
                <p>考生答案:{q.user_answer || "—"}</p>
                <p>参考答案:{q.reference_answer || "—"}</p>
                <p>
                  {q.is_correct ? <Tag color="success">正确</Tag> : <Tag color="error">错误</Tag>}
                  得分:{q.score} / {q.max_score ?? 1}
                </p>
              </Card>
            </div>
          ))}
        </div>
      ))}
    </div>
  ) : null;
 
  const centerRight = (
    <div className="attempt-review__center-right">
      {detailLoading && (
        <div className="attempt-review__center-right-mask" aria-busy="true">
          <Spin />
        </div>
      )}
      {data && (
        <Card className="attempt-review__header" size="small">
          <Descriptions column={{ xs: 1, sm: 2 }} size="small">
            <Descriptions.Item label="姓名">{data.examinee_name}</Descriptions.Item>
            <Descriptions.Item label="证件号">{data.id_card}</Descriptions.Item>
            <Descriptions.Item label="科目">{data.subject_name}</Descriptions.Item>
            <Descriptions.Item label="总分">{data.score} / {data.paper_total_score}</Descriptions.Item>
            <Descriptions.Item label="试卷">{data.paper_name}</Descriptions.Item>
            <Descriptions.Item label="考场">{data.room_id} {data.seat_number}</Descriptions.Item>
            <Descriptions.Item label="考试时间">{data.start_time} ~ {data.end_time}</Descriptions.Item>
          </Descriptions>
        </Card>
      )}
      {!data && detailLoading && (
        <div className="attempt-review__center-right-placeholder">
          <Spin />
        </div>
      )}
      {data && (
        <>
          {!isWide && <div className="attempt-review__index-mobile-wrap">{indexPanel}</div>}
          <div className="attempt-review__index-detail-row">
            {isWide && (
              <div
                className={
                  indexCollapsed
                    ? "attempt-review__index-col attempt-review__index-col--collapsed"
                    : "attempt-review__index-col"
                }
              >
                {indexPanel}
              </div>
            )}
            <div ref={detailScrollRef} className="attempt-review__detail">
              {detailPanel}
            </div>
          </div>
        </>
      )}
    </div>
  );
 
  return (
    <div className="attempt-review">
      <div className="attempt-review__split">
        {isWide && attemptId && (
          <div className="attempt-review__roster-col">
            <AttemptRoster
              activeAttemptId={attemptId}
              listQuery={listQuery}
              onSelectAttempt={selectAttempt}
              onSearch={searchRoster}
            />
          </div>
        )}
        {centerRight}
      </div>
    </div>
  );
}