Files
suixinkan_uikit/suixinkan/UI/Training/TrainingExamViewController.swift
T

434 lines
22 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SnapKit
import UIKit
/// 按需分页的原生考试页,增量保存草稿并持久恢复未知交卷结果。
@MainActor
final class TrainingExamViewController: TrainingBaseViewController {
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 var isPerformingOperation = false
private var requestLoadingToken: UUID?
private var needsReloadOnReturn = false
private var renderedQuestion: TrainingQuestionItem?
private var optionButtons: [String: UIButton] = [:]
private let scrollView = UIScrollView()
private let contentStack = TrainingUI.card()
private let positionLabel = TrainingUI.label(style: .subheadline, color: AppColor.primary)
private let questionLabel = TrainingUI.label(style: .title3)
private let hintLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let optionStack = UIStackView()
private let navigationStack = UIStackView()
private let previousButton = AppButton(title: "上一题", style: .secondary)
private let nextButton = AppButton(title: "下一题", style: .secondary)
private let bottomStack = UIStackView()
private let statusLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let submitButton = AppButton(title: "交卷")
/// 用户明确重考才传 resetDraft;默认恢复已有草稿和未确认提交。
init(taskID: String, service: any TrainingDataServing, resetDraft: Bool = false, viewModel: TrainingRemoteExamViewModel? = nil) {
self.service = service
self.viewModel = viewModel ?? TrainingRemoteExamViewModel(taskID: taskID, context: TrainingPendingSubmissionStore.currentContext())
self.resetDraft = resetDraft
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() {
title = "培训答题"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "答题卡", style: .plain, target: self, action: #selector(answerCardTapped))
}
override func setupUI() {
scrollView.alwaysBounceVertical = true
optionStack.axis = .vertical
optionStack.spacing = 12
navigationStack.axis = .horizontal
navigationStack.spacing = 12
navigationStack.distribution = .fillEqually
navigationStack.addArrangedSubview(previousButton)
navigationStack.addArrangedSubview(nextButton)
previousButton.accessibilityIdentifier = "training.exam.previous"
nextButton.accessibilityIdentifier = "training.exam.next"
[positionLabel, questionLabel, hintLabel, optionStack, navigationStack].forEach(contentStack.addArrangedSubview)
bottomStack.axis = .vertical
bottomStack.spacing = 8
bottomStack.backgroundColor = AppColor.cardBackground
bottomStack.layoutMargins = UIEdgeInsets(top: 12, left: 20, bottom: 12, right: 20)
bottomStack.isLayoutMarginsRelativeArrangement = true
bottomStack.addArrangedSubview(statusLabel)
bottomStack.addArrangedSubview(submitButton)
submitButton.accessibilityIdentifier = "training.exam.submit"
scrollView.addSubview(contentStack)
view.addSubview(scrollView)
view.addSubview(bottomStack)
applyState()
}
override func setupConstraints() {
scrollView.snp.makeConstraints {
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(bottomStack.snp.top)
}
contentStack.snp.makeConstraints {
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(16)
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-32)
}
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
}
override func bindActions() {
previousButton.addTarget(self, action: #selector(previousTapped), for: .touchUpInside)
nextButton.addTarget(self, action: #selector(nextTapped), for: .touchUpInside)
submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
}
override func viewDidLoad() {
super.viewDidLoad()
loadExam()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let returning = hasAppeared
let shouldReload = needsReloadOnReturn
needsReloadOnReturn = false
hasAppeared = true
guard !isPerformingOperation, !viewModel.isBusy else { return }
if viewModel.submittedAttempt != nil || viewModel.shouldReturnToCenter {
beginOperation(message: "正在确认考试状态…", showsLoading: false)
Task { @MainActor in await viewModel.validateIdentity(); finishOperation() }
return
}
if returning, shouldReload { loadExam() }
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// 自有答题卡和确认弹窗关闭后继续当前题,真实导航返回才刷新考试资格。
if navigationController?.topViewController !== self { needsReloadOnReturn = true }
}
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
private func loadExam() {
guard !isPerformingOperation, !viewModel.isBusy else { return }
beginOperation(message: "正在加载试卷…")
Task { @MainActor in
await viewModel.load(service: service, resetDraft: resetDraft)
finishOperation()
}
}
private func applyState() {
setOperationInteractionEnabled(true)
let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果"
: viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil
guard let question = viewModel.currentQuestion else {
clearOptions()
positionLabel.text = ""
questionLabel.text = viewModel.errorMessage ?? (viewModel.hasPendingSubmission ? "正在确认上次交卷结果…" : "正在加载试卷…")
hintLabel.text = ""
statusLabel.text = viewModel.hasPendingSubmission ? "上次提交尚未确认,恢复结果后再继续操作" : ""
navigationStack.isHidden = true
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.canEdit
positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(viewModel.questionCount) 题 · \(question.type == .single ? "单选题" : "多选题")"
questionLabel.text = question.stem
hintLabel.text = question.type == .single ? "请选择一个答案" : "请选择所有正确答案,少选、多选、错选均不得分"
renderOptions(for: question)
updateOptionSelection(viewModel.currentSelectedIDs)
for button in optionButtons.values { button.isEnabled = viewModel.canEdit }
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(pendingTitle ?? (viewModel.isBusy ? "正在保存…" : "交卷"), for: .normal)
submitButton.isEnabled = !viewModel.isBusy && (pendingTitle != nil || viewModel.canEdit)
}
private func clearOptions() {
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
optionButtons = [:]
renderedQuestion = nil
}
private func renderOptions(for question: TrainingQuestionItem) {
guard renderedQuestion != question else { return }
clearOptions()
renderedQuestion = question
for (index, option) in question.options.enumerated() {
let button = UIButton(type: .system)
var configuration = UIButton.Configuration.filled()
configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)"
configuration.contentInsets = NSDirectionalEdgeInsets(top: 18, leading: 16, bottom: 18, trailing: 16)
configuration.imagePadding = 12
configuration.titleAlignment = .leading
configuration.cornerStyle = .medium
button.configuration = configuration
button.contentHorizontalAlignment = .leading
button.titleLabel?.numberOfLines = 0
button.titleLabel?.lineBreakMode = .byWordWrapping
button.accessibilityIdentifier = "training.option.\(option.id)"
button.addAction(UIAction { [weak self] _ in self?.selectOption(option.id) }, for: .touchUpInside)
optionButtons[option.id] = button
optionStack.addArrangedSubview(button)
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(56) }
}
}
private func updateOptionSelection(_ selectedIDs: Set<String>) {
UIView.performWithoutAnimation {
for (id, button) in optionButtons {
let selected = selectedIDs.contains(id)
var configuration = button.configuration
configuration?.baseBackgroundColor = selected ? AppColor.primaryLight : AppColor.pageBackgroundSoft
configuration?.baseForegroundColor = selected ? AppColor.primary : AppColor.textPrimary
configuration?.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
button.configuration = configuration
button.accessibilityTraits = selected ? [.button, .selected] : .button
}
}
}
private func setOperationInteractionEnabled(_ enabled: Bool) {
// 网络操作只暂停动作,保留已启用控件的颜色和透明度。
let buttons: [UIButton] = Array(optionButtons.values) + [previousButton, nextButton, submitButton]
for button in buttons { button.isUserInteractionEnabled = enabled }
}
private func beginOperation(message: String, showsLoading: Bool = true) {
isPerformingOperation = true
if showsLoading { requestLoadingToken = beginRequestLoading() }
setOperationInteractionEnabled(false)
statusLabel.text = message
statusLabel.textColor = AppColor.textSecondary
}
private func finishOperation() {
if let requestLoadingToken {
endRequestLoading(requestLoadingToken)
self.requestLoadingToken = nil
}
isPerformingOperation = false
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 !isPerformingOperation, let selected = viewModel.selectionPreview(optionID: id) else { return }
updateOptionSelection(selected)
beginOperation(message: "正在保存答案…")
Task { @MainActor in
await viewModel.select(optionID: id, service: service)
finishOperation()
}
}
private func goToQuestion(_ index: Int) {
guard !isPerformingOperation, viewModel.canEdit,
(0..<viewModel.questionCount).contains(index), index != viewModel.currentIndex else { return }
beginOperation(message: "正在加载题目…")
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 !isPerformingOperation, viewModel.canEdit, presentedViewController == nil 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 }
present(navigation, animated: true)
}
@objc private func submitTapped() {
guard !isPerformingOperation, !viewModel.isBusy else { return }
if viewModel.hasPendingMutation {
beginOperation(message: "正在重试保存…")
Task { @MainActor in await viewModel.retryMutation(service: service); finishOperation() }
return
}
if viewModel.hasPendingSubmission { performSubmit(); return }
if viewModel.canRetryCurrentPage {
beginOperation(message: "正在加载题目…")
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
}
guard presentedViewController == nil else { 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() {
guard !isPerformingOperation, !viewModel.isBusy else { return }
beginOperation(message: "正在提交并确认成绩…")
Task { @MainActor in
_ = 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 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(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
let columns = 5
let spacing: CGFloat = 12
let inset: CGFloat = 20
let availableWidth = environment.container.effectiveContentSize.width - inset * 2
let itemWidth = max(0, floor((availableWidth - spacing * CGFloat(columns - 1)) / CGFloat(columns)))
let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(itemWidth), heightDimension: .absolute(52))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(52))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, repeatingSubitem: item, count: columns)
group.interItemSpacing = .fixed(spacing)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = spacing
section.contentInsets = NSDirectionalEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset)
return section
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
title = "答题卡 · 蓝色为已答"
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in self?.dismiss(animated: true) })
collectionView.backgroundColor = AppColor.pageBackgroundSoft
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "question")
view.addSubview(collectionView)
collectionView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
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.answeredOrders.contains(index + 1)
var content = UIListContentConfiguration.cell()
content.text = "\(index + 1)"
content.textProperties.alignment = .center
content.textProperties.color = answered ? AppColor.primary : AppColor.textSecondary
content.directionalLayoutMargins = .zero
cell.contentConfiguration = content
cell.backgroundColor = answered ? AppColor.primaryLight : AppColor.cardBackground
cell.layer.cornerRadius = 10
cell.layer.borderWidth = index == self.currentIndex ? 2 : 0
cell.layer.borderColor = AppColor.primary.cgColor
cell.isAccessibilityElement = true
cell.accessibilityLabel = "第 \(index + 1) 题,\(answered ? "已答" : "未答")\(index == self.currentIndex ? ",当前题" : "")"
cell.accessibilityTraits = .button
return cell
}
var snapshot = NSDiffableDataSourceSnapshot<Int, Int>()
snapshot.appendSections([0])
snapshot.appendItems(Array(0..<questionCount))
dataSource.apply(snapshot, animatingDifferences: true)
}
}
extension TrainingAnswerCardViewController: UICollectionViewDelegate {
/// 选中题号后关闭答题卡并通知考试页面跳转。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let index = dataSource.itemIdentifier(for: indexPath) else { return }
let selection = onSelect
dismiss(animated: true) { selection?(index) }
}
}