feat(training): 同步培训中心学习答题功能

新增首页和个人页入口,支持课程阅读、答题卡、草稿恢复、成绩解析、历史记录与重考。保留独立的 Debug 本地演示数据源及后端接入协议,并对齐列表动画和答题卡布局约定。

来源:xh_test 的 74c451c。验证:iPhone 11 真机 59 项相关测试全部通过;全量测试中的 8 个既有失败已在同步前版本复现。
This commit is contained in:
2026-10-13 15:54:31 +08:00
parent 736b5515c0
commit 8862ae5401
16 changed files with 2645 additions and 7 deletions
@@ -0,0 +1,188 @@
import SnapKit
import UIKit
/// 成绩概览、可展开解析和返回学习入口,历史记录只按最新任务状态提供重考。
@MainActor
final class TrainingResultViewController: TrainingBaseViewController {
private let taskID: String
private let attemptID: String
private let service: any TrainingServing
private var loadedTask: TrainingTask?
private var loadedAttempt: TrainingAttempt?
private var loadFailed = false
private var showsDetails = false
private let scrollView = UIScrollView()
private let contentStack = UIStackView()
private let footer = UIView()
private let actionButton = TrainingUI.button("完成,返回培训中心")
/// 使用记录 ID 读取最新本人任务,禁止通过后从旧失败记录继续重考。
init(taskID: String, attemptID: String, service: any TrainingServing) {
self.taskID = taskID
self.attemptID = attemptID
self.service = service
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() { TrainingUI.navigation(self, title: "考试结果") }
override func setupUI() {
view.backgroundColor = TrainingUI.background
contentStack.axis = .vertical
contentStack.spacing = 12
scrollView.addSubview(contentStack)
view.addSubview(scrollView)
footer.backgroundColor = .white
let line = UIView()
line.backgroundColor = TrainingUI.border
footer.addSubview(line)
line.snp.makeConstraints { $0.leading.trailing.top.equalToSuperview(); $0.height.equalTo(1) }
footer.addSubview(actionButton)
view.addSubview(footer)
actionButton.accessibilityIdentifier = "training.result.action"
}
override func setupConstraints() {
footer.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
actionButton.snp.makeConstraints {
$0.leading.trailing.equalToSuperview().inset(12)
$0.top.equalToSuperview().offset(10)
$0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-10)
}
scrollView.snp.makeConstraints { $0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide); $0.bottom.equalTo(footer.snp.top) }
contentStack.snp.makeConstraints {
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(UIEdgeInsets(top: 14, left: 13, bottom: 20, right: 13))
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-26)
}
}
override func bindActions() { actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) }
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); loadResult() }
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
private func loadResult() { Task { @MainActor in await reload() } }
/// 页面出现时重新读取记录,失败可重试,不展示上个任务成绩。
func reload() async {
actionButton.isEnabled = false
do {
let task = try await service.task(id: taskID)
guard let attempt = task.progress.attempts.first(where: { $0.id == attemptID }) else { throw TrainingError.notFound }
loadedTask = task
loadedAttempt = attempt
loadFailed = false
render(task: task, attempt: attempt)
} catch {
loadedTask = nil
loadedAttempt = nil
loadFailed = true
clearContent()
contentStack.addArrangedSubview(TrainingUI.text(error.localizedDescription, color: TrainingUI.muted))
setActionTitle("重新加载")
}
actionButton.isEnabled = true
}
private func clearContent() {
for child in contentStack.arrangedSubviews { contentStack.removeArrangedSubview(child); child.removeFromSuperview() }
}
private func setActionTitle(_ title: String) { var configuration = actionButton.configuration; configuration?.title = title; actionButton.configuration = configuration }
private func render(task: TrainingTask, attempt: TrainingAttempt) {
clearContent()
if attempt.isDemo { contentStack.addArrangedSubview(TrainingUI.demoNotice()) }
let summary = UIStackView()
summary.axis = .vertical
summary.spacing = 11
summary.alignment = .center
summary.backgroundColor = .white
summary.layer.cornerRadius = 11
summary.layer.borderWidth = 1
summary.layer.borderColor = TrainingUI.border.cgColor
summary.isLayoutMarginsRelativeArrangement = true
summary.layoutMargins = UIEdgeInsets(top: 25, left: 12, bottom: 25, right: 12)
let symbol = UIImageView(image: UIImage(systemName: attempt.passed ? "checkmark.circle.fill" : "info.circle.fill"))
symbol.tintColor = attempt.passed ? TrainingUI.success : UIColor(red: 237/255, green: 140/255, blue: 36/255, alpha: 1)
symbol.contentMode = .scaleAspectFit
symbol.snp.makeConstraints { $0.size.equalTo(54) }
summary.addArrangedSubview(symbol)
let title = TrainingUI.text(attempt.passed ? "考试通过,学习任务已完成" : "本次未通过,再接再厉", size: 16.5, weight: .bold)
title.textAlignment = .center
summary.addArrangedSubview(title)
let score = UIStackView(arrangedSubviews: [TrainingUI.text(attempt.scoreText, size: 46, weight: .bold, color: TrainingUI.primary), TrainingUI.text("/ 100 分", size: 13, color: TrainingUI.muted)])
score.alignment = .firstBaseline
score.spacing = 6
score.snp.makeConstraints { $0.height.greaterThanOrEqualTo(69) }
summary.addArrangedSubview(score)
let detail = TrainingUI.text("\(task.passScore) 分及格 · \(TrainingUI.date(attempt.submittedAt))", size: 12.5, color: TrainingUI.muted)
detail.textAlignment = .center
summary.addArrangedSubview(detail)
contentStack.addArrangedSubview(summary)
let counts = TrainingUI.card()
let row = UIStackView(arrangedSubviews: [TrainingUI.text("答对 \(attempt.correctCount) 题"), TrainingUI.text("答错 \(attempt.questionCount - attempt.correctCount) 题")])
row.distribution = .fillEqually
for label in row.arrangedSubviews.compactMap({ $0 as? UILabel }) { label.textAlignment = .center }
counts.addArrangedSubview(row)
contentStack.addArrangedSubview(counts)
let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true)
details.accessibilityIdentifier = "training.result.details"
details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside)
contentStack.addArrangedSubview(details)
let learning = TrainingUI.button("返回学习", plain: true)
learning.accessibilityIdentifier = "training.result.learning"
learning.addTarget(self, action: #selector(returnToLearning), for: .touchUpInside)
contentStack.addArrangedSubview(learning)
if showsDetails {
for (index, review) in attempt.reviews.enumerated() {
let card = TrainingUI.card()
let top = UIStackView(arrangedSubviews: [TrainingUI.text("第 \(index + 1) 题", size: 12.5, color: TrainingUI.muted), TrainingUI.text(review.isCorrect ? "回答正确" : "回答错误", size: 12, color: review.isCorrect ? TrainingUI.success : .systemRed)])
top.distribution = .equalSpacing
card.addArrangedSubview(top)
card.addArrangedSubview(TrainingUI.text(review.question.stem, size: 15.5, weight: .semibold))
for (optionIndex, option) in review.question.options.enumerated() {
card.addArrangedSubview(TrainingUI.text("\(TrainingQuestion.optionLetter(optionIndex)). \(option.text)", size: 13.5, color: UIColor(red: 92/255, green: 108/255, blue: 132/255, alpha: 1)))
}
func letters(_ ids: Set<String>) -> String {
let values = review.question.options.enumerated().compactMap { ids.contains($0.element.id) ? TrainingQuestion.optionLetter($0.offset) : nil }
return values.isEmpty ? "未作答" : values.joined(separator: "、")
}
card.addArrangedSubview(TrainingUI.text("你的答案:\(letters(review.selectedIDs)) · 正确答案:\(letters(review.correctIDs))", size: 12.5, color: TrainingUI.muted))
card.addArrangedSubview(TrainingUI.notice(review.explanation.isEmpty ? "暂无解析" : review.explanation))
contentStack.addArrangedSubview(card)
}
}
let canRetry = !attempt.passed && task.submissionBlockReason(now: Date()) == nil
contentStack.addArrangedSubview(TrainingUI.text(canRetry ? "截止前可不限次数重考,每次成绩都会保留。" : "本次记录只读,可回顾课程内容和答案解析。", size: 12, color: TrainingUI.muted))
setActionTitle(canRetry ? "再考一次" : "完成,返回培训中心")
}
@objc private func toggleDetails() {
guard let task = loadedTask, let attempt = loadedAttempt else { return }
showsDetails.toggle()
render(task: task, attempt: attempt)
}
/// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。
@objc private func returnToLearning() {
guard loadedTask != nil, let navigationController else { return }
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
navigationController.popToViewController(course, animated: true)
} else {
navigationController.pushViewController(TrainingCourseViewController(taskID: taskID, service: service), animated: true)
}
}
@objc private func actionTapped() {
if loadFailed { loadResult(); return }
guard let task = loadedTask, let attempt = loadedAttempt, let navigationController else { return }
if !attempt.passed, task.submissionBlockReason(now: Date()) == nil {
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [TrainingExamViewController(taskID: taskID, service: service, resetDraft: true)], animated: true)
} else if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
navigationController.popToViewController(center, animated: true)
} else { navigationController.setViewControllers([TrainingCenterViewController(service: service)], animated: true) }
}
}