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() viewModel.onDraftSaveStateChange = { [weak self] in guard let self, !self.isPerformingOperation else { return } self.applyState() self.scheduleNavigationIfNeeded() } 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 Task { @MainActor in _ = await viewModel.flushDraft(service: service) } } } 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.hasDraftConflict ? "确认本机答案" : 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 let saveState = viewModel.draftSaveMessage statusLabel.text = viewModel.hasPendingMutation || viewModel.errorMessage == nil ? "已答 \(viewModel.answeredCount)/\(viewModel.questionCount) · \(saveState)" : viewModel.errorMessage statusLabel.textColor = viewModel.hasPendingMutation || viewModel.errorMessage != nil ? AppColor.danger : AppColor.textSecondary 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) { 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, viewModel.selectLocally(optionID: id, service: service) else { return } // desired 已同步更新;连续多选不等待 Task 或网络,保留同题按钮实例。 applyState() } private func goToQuestion(_ index: Int) { guard !isPerformingOperation, viewModel.canEdit, (0.. 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..