feat(training): 接入真实培训接口与学习答题恢复
This commit is contained in:
@@ -1,12 +1,15 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 原生单选/多选答题页,支持逐题跳转、草稿恢复与确认交卷。
|
||||
/// 按需分页的原生考试页,增量保存草稿并持久恢复未知交卷结果。
|
||||
@MainActor
|
||||
final class TrainingExamViewController: TrainingBaseViewController {
|
||||
private let service: any TrainingServing
|
||||
private let viewModel: TrainingExamViewModel
|
||||
private let service: any TrainingDataServing
|
||||
private let viewModel: TrainingRemoteExamViewModel
|
||||
private let resetDraft: Bool
|
||||
private var openedResult = false
|
||||
private var navigationIsScheduled = false
|
||||
private var hasAppeared = false
|
||||
private let scrollView = UIScrollView()
|
||||
private let contentStack = TrainingUI.card()
|
||||
private let positionLabel = TrainingUI.label(style: .subheadline, color: AppColor.primary)
|
||||
@@ -20,10 +23,10 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
private let statusLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
|
||||
private let submitButton = AppButton(title: "交卷")
|
||||
|
||||
/// 重考时清除旧草稿,普通进入时恢复本人已保存的答案。
|
||||
init(taskID: String, service: any TrainingServing, resetDraft: Bool = false) {
|
||||
/// 用户明确重考才传 resetDraft;默认恢复已有草稿和未确认提交。
|
||||
init(taskID: String, service: any TrainingDataServing, resetDraft: Bool = false, viewModel: TrainingRemoteExamViewModel? = nil) {
|
||||
self.service = service
|
||||
viewModel = TrainingExamViewModel(taskID: taskID)
|
||||
self.viewModel = viewModel ?? TrainingRemoteExamViewModel(taskID: taskID, context: TrainingPendingSubmissionStore.currentContext())
|
||||
self.resetDraft = resetDraft
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
@@ -45,7 +48,6 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
navigationStack.distribution = .fillEqually
|
||||
navigationStack.addArrangedSubview(previousButton)
|
||||
navigationStack.addArrangedSubview(nextButton)
|
||||
if service.isDemo { contentStack.addArrangedSubview(TrainingUI.demoNotice()) }
|
||||
[positionLabel, questionLabel, hintLabel, optionStack, navigationStack].forEach(contentStack.addArrangedSubview)
|
||||
bottomStack.axis = .vertical
|
||||
bottomStack.spacing = 8
|
||||
@@ -84,35 +86,49 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
loadExam()
|
||||
}
|
||||
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
super.viewDidAppear(animated)
|
||||
let returning = hasAppeared
|
||||
hasAppeared = true
|
||||
if viewModel.submittedAttempt != nil || viewModel.shouldReturnToCenter {
|
||||
Task { @MainActor in await viewModel.validateIdentity(); finishOperation() }
|
||||
return
|
||||
}
|
||||
if returning, !viewModel.isBusy { loadExam() }
|
||||
}
|
||||
|
||||
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
||||
|
||||
private func loadExam() {
|
||||
submitButton.isEnabled = false
|
||||
disableControls()
|
||||
Task { @MainActor in
|
||||
await viewModel.load(service: service, resetDraft: resetDraft)
|
||||
applyState()
|
||||
finishOperation()
|
||||
}
|
||||
}
|
||||
|
||||
private func applyState() {
|
||||
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
|
||||
guard let task = viewModel.task, let question = viewModel.currentQuestion else {
|
||||
let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果"
|
||||
: viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil
|
||||
guard let question = viewModel.currentQuestion else {
|
||||
positionLabel.text = ""
|
||||
questionLabel.text = viewModel.errorMessage ?? "正在加载试卷…"
|
||||
questionLabel.text = viewModel.errorMessage ?? (viewModel.hasPendingSubmission ? "正在确认上次交卷结果…" : "正在加载试卷…")
|
||||
hintLabel.text = ""
|
||||
statusLabel.text = viewModel.hasPendingSubmission ? "上次提交尚未确认,恢复结果后再继续操作" : ""
|
||||
navigationStack.isHidden = true
|
||||
submitButton.setTitle("重新加载", for: .normal)
|
||||
submitButton.isEnabled = viewModel.errorMessage != nil
|
||||
submitButton.setTitle(pendingTitle ?? "重新加载", for: .normal)
|
||||
submitButton.isEnabled = !viewModel.isBusy && (viewModel.errorMessage != nil || pendingTitle != nil)
|
||||
navigationItem.rightBarButtonItem?.isEnabled = false
|
||||
return
|
||||
}
|
||||
navigationStack.isHidden = false
|
||||
navigationItem.rightBarButtonItem?.isEnabled = !viewModel.isBusy
|
||||
positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(task.questions.count) 题 · \(question.type == .single ? "单选题" : "多选题")"
|
||||
navigationItem.rightBarButtonItem?.isEnabled = viewModel.canEdit
|
||||
positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(viewModel.questionCount) 题 · \(question.type == .single ? "单选题" : "多选题")"
|
||||
questionLabel.text = question.stem
|
||||
hintLabel.text = question.type == .single ? "请选择一个答案" : "请选择所有正确答案,少选、多选、错选均不得分"
|
||||
for (index, option) in question.options.enumerated() {
|
||||
let selected = viewModel.answers[question.id]?.contains(option.id) == true
|
||||
let selected = viewModel.currentSelectedIDs.contains(option.id)
|
||||
let button = UIButton(type: .system)
|
||||
var configuration = UIButton.Configuration.filled()
|
||||
configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)"
|
||||
@@ -127,44 +143,92 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
button.contentHorizontalAlignment = .leading
|
||||
button.titleLabel?.numberOfLines = 0
|
||||
button.titleLabel?.lineBreakMode = .byWordWrapping
|
||||
button.isEnabled = !viewModel.isBusy
|
||||
button.isEnabled = viewModel.canEdit
|
||||
button.accessibilityIdentifier = "training.option.\(option.id)"
|
||||
button.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
button.addAction(UIAction { [weak self] _ in self?.selectOption(option.id) }, for: .touchUpInside)
|
||||
optionStack.addArrangedSubview(button)
|
||||
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(56) }
|
||||
}
|
||||
previousButton.isEnabled = !viewModel.isBusy && viewModel.currentIndex > 0
|
||||
nextButton.isEnabled = !viewModel.isBusy && viewModel.currentIndex < task.questions.count - 1
|
||||
statusLabel.text = viewModel.errorMessage ?? "已答 \(viewModel.answeredCount)/\(task.questions.count) · 答案已保存,可稍后继续"
|
||||
previousButton.isEnabled = viewModel.canEdit && viewModel.currentIndex > 0
|
||||
nextButton.isEnabled = viewModel.canEdit && viewModel.currentIndex < viewModel.questionCount - 1
|
||||
statusLabel.text = viewModel.errorMessage ?? "已答 \(viewModel.answeredCount)/\(viewModel.questionCount) · 答案已保存,可稍后继续"
|
||||
statusLabel.textColor = viewModel.errorMessage == nil ? AppColor.textSecondary : AppColor.danger
|
||||
submitButton.setTitle(viewModel.isBusy ? "正在保存…" : "交卷", for: .normal)
|
||||
submitButton.isEnabled = !viewModel.isBusy
|
||||
submitButton.setTitle(pendingTitle ?? (viewModel.isBusy ? "正在保存…" : "交卷"), for: .normal)
|
||||
submitButton.isEnabled = !viewModel.isBusy && (pendingTitle != nil || viewModel.canEdit)
|
||||
}
|
||||
|
||||
private func disableControls() {
|
||||
optionStack.arrangedSubviews.compactMap { $0 as? UIButton }.forEach { $0.isEnabled = false }
|
||||
[previousButton, nextButton, submitButton].forEach { $0.isEnabled = false }
|
||||
navigationItem.rightBarButtonItem?.isEnabled = false
|
||||
}
|
||||
|
||||
private func finishOperation() {
|
||||
applyState()
|
||||
scheduleNavigationIfNeeded()
|
||||
}
|
||||
|
||||
private func scheduleNavigationIfNeeded() {
|
||||
guard !openedResult, !navigationIsScheduled,
|
||||
viewModel.shouldReturnToCenter || viewModel.submittedAttempt != nil,
|
||||
let navigationController, navigationController.topViewController === self else { return }
|
||||
navigationIsScheduled = true
|
||||
let complete: @MainActor @Sendable () -> Void = { [weak self, weak navigationController] in
|
||||
guard let self else { return }
|
||||
self.navigationIsScheduled = false
|
||||
guard let navigationController, navigationController.topViewController === self else { return }
|
||||
// 返回页面的原 pop 必须先结束,否则新的成绩栈会被 UIKit 恢复成旧考试栈。
|
||||
if navigationController.transitionCoordinator != nil { self.scheduleNavigationIfNeeded(); return }
|
||||
if self.viewModel.shouldReturnToCenter { self.returnToCenter() }
|
||||
else if let attempt = self.viewModel.submittedAttempt { self.openResult(attempt) }
|
||||
}
|
||||
if let coordinator = navigationController.transitionCoordinator {
|
||||
let registered = coordinator.animate(alongsideTransition: nil) { _ in
|
||||
DispatchQueue.main.async(execute: complete)
|
||||
}
|
||||
if !registered { DispatchQueue.main.async(execute: complete) }
|
||||
} else { DispatchQueue.main.async(execute: complete) }
|
||||
}
|
||||
|
||||
private func returnToCenter() {
|
||||
guard let navigationController, navigationController.topViewController === self else { return }
|
||||
if viewModel.isIdentityInvalid {
|
||||
navigationController.popToRootViewController(animated: false)
|
||||
return
|
||||
}
|
||||
if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
|
||||
navigationController.popToViewController(center, animated: true)
|
||||
} else { navigationController.popToRootViewController(animated: true) }
|
||||
}
|
||||
|
||||
private func selectOption(_ id: String) {
|
||||
guard viewModel.canEdit else { return }
|
||||
disableControls()
|
||||
Task { @MainActor in
|
||||
let operation = Task { await viewModel.select(optionID: id, service: service) }
|
||||
await Task.yield()
|
||||
applyState()
|
||||
await operation.value
|
||||
applyState()
|
||||
await viewModel.select(optionID: id, service: service)
|
||||
finishOperation()
|
||||
}
|
||||
}
|
||||
|
||||
private func goToQuestion(_ index: Int) {
|
||||
viewModel.goToQuestion(index)
|
||||
applyState()
|
||||
scrollView.setContentOffset(.zero, animated: false)
|
||||
UIAccessibility.post(notification: .screenChanged, argument: questionLabel)
|
||||
guard viewModel.canEdit else { return }
|
||||
disableControls()
|
||||
Task { @MainActor in
|
||||
await viewModel.goToQuestion(index, service: service)
|
||||
finishOperation()
|
||||
scrollView.setContentOffset(.zero, animated: false)
|
||||
UIAccessibility.post(notification: .screenChanged, argument: questionLabel)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func previousTapped() { goToQuestion(viewModel.currentIndex - 1) }
|
||||
@objc private func nextTapped() { goToQuestion(viewModel.currentIndex + 1) }
|
||||
|
||||
@objc private func answerCardTapped() {
|
||||
guard let task = viewModel.task, !viewModel.isBusy else { return }
|
||||
let controller = TrainingAnswerCardViewController(task: task, answers: viewModel.answers, currentIndex: viewModel.currentIndex)
|
||||
guard viewModel.canEdit else { return }
|
||||
let controller = TrainingAnswerCardViewController(questionCount: viewModel.questionCount,
|
||||
answeredOrders: viewModel.answeredQuestionOrders, currentIndex: viewModel.currentIndex)
|
||||
controller.onSelect = { [weak self] index in self?.goToQuestion(index) }
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
if let sheet = navigation.sheetPresentationController { sheet.detents = [.medium(), .large()]; sheet.prefersGrabberVisible = true }
|
||||
@@ -173,52 +237,74 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
||||
|
||||
@objc private func submitTapped() {
|
||||
guard !viewModel.isBusy else { return }
|
||||
guard let task = viewModel.task else { loadExam(); return }
|
||||
if let missing = viewModel.firstUnansweredIndex {
|
||||
goToQuestion(missing)
|
||||
showToast("还有 \(task.questions.count - viewModel.answeredCount) 道题未作答,已定位到第一道")
|
||||
if viewModel.hasPendingMutation {
|
||||
disableControls()
|
||||
Task { @MainActor in await viewModel.retryMutation(service: service); finishOperation() }
|
||||
return
|
||||
}
|
||||
let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(task.questions.count) 道题,提交后将生成本次考试记录。", preferredStyle: .alert)
|
||||
if viewModel.hasPendingSubmission { performSubmit(); return }
|
||||
if viewModel.canRetryCurrentPage {
|
||||
disableControls()
|
||||
Task { @MainActor in await viewModel.retryCurrentPage(service: service); finishOperation() }
|
||||
return
|
||||
}
|
||||
guard viewModel.currentQuestion != nil else { loadExam(); return }
|
||||
guard viewModel.canEdit else { return }
|
||||
if let missing = viewModel.firstUnansweredIndex {
|
||||
goToQuestion(missing)
|
||||
showToast("还有 \(viewModel.questionCount - viewModel.answeredCount) 道题未作答,已定位到第一道")
|
||||
return
|
||||
}
|
||||
let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(viewModel.questionCount) 道题,提交后将生成本次考试记录。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续检查", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "交卷", style: .default) { [weak self] _ in self?.performSubmit() })
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
private func performSubmit() {
|
||||
disableControls()
|
||||
Task { @MainActor in
|
||||
let operation = Task { await viewModel.submit(service: service) }
|
||||
await Task.yield()
|
||||
applyState()
|
||||
let attempt = await operation.value
|
||||
applyState()
|
||||
guard let attempt, let navigationController else { return }
|
||||
let result = TrainingResultViewController(taskID: viewModel.taskID, attemptID: attempt.id, service: service)
|
||||
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [result], animated: true)
|
||||
_ = await viewModel.submit(service: service)
|
||||
finishOperation()
|
||||
}
|
||||
}
|
||||
|
||||
private func openResult(_ attempt: TrainingAttemptSummary) {
|
||||
guard !openedResult, let navigationController, navigationController.topViewController === self else { return }
|
||||
openedResult = true
|
||||
let result = TrainingResultViewController(taskID: viewModel.taskID, attemptID: attempt.id, service: service, initialDetail: viewModel.submittedResult)
|
||||
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [result], animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 可滚动的网格答题卡,支持最多 500 道题。
|
||||
@MainActor
|
||||
final class TrainingAnswerCardViewController: UIViewController {
|
||||
private let task: TrainingTask
|
||||
private let answers: TrainingAnswers
|
||||
private let questionCount: Int
|
||||
private let answeredOrders: Set<Int>
|
||||
private let currentIndex: Int
|
||||
private let collectionView: UICollectionView
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Int, Int>!
|
||||
/// 关闭答题卡后将用户选择的题目位置返回考试页面。
|
||||
var onSelect: ((Int) -> Void)?
|
||||
|
||||
/// 根据本次草稿展示已答和当前题,不显示正确答案。
|
||||
init(task: TrainingTask, answers: TrainingAnswers, currentIndex: Int) {
|
||||
self.task = task
|
||||
self.answers = answers
|
||||
/// 使用总题数和已答题号展示答题卡,无需下载题目或全部答案。
|
||||
init(questionCount: Int, answeredOrders: Set<Int>, currentIndex: Int) {
|
||||
self.questionCount = min(500, max(0, questionCount))
|
||||
self.answeredOrders = answeredOrders
|
||||
self.currentIndex = currentIndex
|
||||
collectionView = UICollectionView(frame: .zero, collectionViewLayout: Self.makeLayout())
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
/// 保留演示渲染测试的初始化入口,将本地试卷转换成轻量题号状态。
|
||||
convenience init(task: TrainingTask, answers: TrainingAnswers, currentIndex: Int) {
|
||||
let orders = Set(task.questions.enumerated().compactMap { index, question in
|
||||
(answers[question.id] ?? []).isEmpty ? nil : index + 1
|
||||
})
|
||||
self.init(questionCount: task.questions.count, answeredOrders: orders, currentIndex: currentIndex)
|
||||
}
|
||||
|
||||
/// 保持原有五列、52 点行高与 12 点间距,随可用宽度自动计算列宽。
|
||||
private static func makeLayout() -> UICollectionViewCompositionalLayout {
|
||||
UICollectionViewCompositionalLayout { _, environment in
|
||||
@@ -254,7 +340,7 @@ final class TrainingAnswerCardViewController: UIViewController {
|
||||
dataSource = UICollectionViewDiffableDataSource<Int, Int>(collectionView: collectionView) { [weak self] collection, indexPath, index in
|
||||
guard let self else { return nil }
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "question", for: indexPath)
|
||||
let answered = !(self.answers[self.task.questions[index].id] ?? []).isEmpty
|
||||
let answered = self.answeredOrders.contains(index + 1)
|
||||
var content = UIListContentConfiguration.cell()
|
||||
content.text = "\(index + 1)"
|
||||
content.textProperties.alignment = .center
|
||||
@@ -272,7 +358,7 @@ final class TrainingAnswerCardViewController: UIViewController {
|
||||
}
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Int>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems(Array(task.questions.indices))
|
||||
snapshot.appendItems(Array(0..<questionCount))
|
||||
dataSource.apply(snapshot, animatingDifferences: true)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user