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 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) [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 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() { disableControls() Task { @MainActor in await viewModel.load(service: service, resetDraft: resetDraft) finishOperation() } } private func applyState() { for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() } let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果" : viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil guard let question = viewModel.currentQuestion else { 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 ? "请选择一个答案" : "请选择所有正确答案,少选、多选、错选均不得分" for (index, option) in question.options.enumerated() { let selected = viewModel.currentSelectedIDs.contains(option.id) let button = UIButton(type: .system) var configuration = UIButton.Configuration.filled() configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)" configuration.baseBackgroundColor = selected ? AppColor.primaryLight : AppColor.pageBackgroundSoft configuration.baseForegroundColor = selected ? AppColor.primary : AppColor.textPrimary configuration.contentInsets = NSDirectionalEdgeInsets(top: 18, leading: 16, bottom: 18, trailing: 16) configuration.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle") configuration.imagePadding = 12 configuration.titleAlignment = .leading configuration.cornerStyle = .medium button.configuration = configuration button.contentHorizontalAlignment = .leading button.titleLabel?.numberOfLines = 0 button.titleLabel?.lineBreakMode = .byWordWrapping 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.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 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 await viewModel.select(optionID: id, service: service) finishOperation() } } private func goToQuestion(_ index: Int) { 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 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 } present(navigation, animated: true) } @objc private func submitTapped() { guard !viewModel.isBusy else { return } if viewModel.hasPendingMutation { disableControls() Task { @MainActor in await viewModel.retryMutation(service: service); finishOperation() } return } 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 _ = 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 private let currentIndex: Int private let collectionView: UICollectionView private var dataSource: UICollectionViewDiffableDataSource! /// 关闭答题卡后将用户选择的题目位置返回考试页面。 var onSelect: ((Int) -> Void)? /// 使用总题数和已答题号展示答题卡,无需下载题目或全部答案。 init(questionCount: Int, answeredOrders: Set, 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(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() snapshot.appendSections([0]) snapshot.appendItems(Array(0..