import SnapKit import UIKit /// 原生单选/多选答题页,支持逐题跳转、草稿恢复与确认交卷。 @MainActor final class TrainingExamViewController: TrainingBaseViewController { private let service: any TrainingServing private let viewModel: TrainingExamViewModel private let resetDraft: Bool 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: "交卷") /// 重考时清除旧草稿,普通进入时恢复本人已保存的答案。 init(taskID: String, service: any TrainingServing, resetDraft: Bool = false) { self.service = service viewModel = TrainingExamViewModel(taskID: taskID) 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) if service.isDemo { contentStack.addArrangedSubview(TrainingUI.demoNotice()) } [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 onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) } private func loadExam() { submitButton.isEnabled = false Task { @MainActor in await viewModel.load(service: service, resetDraft: resetDraft) applyState() } } private func applyState() { for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() } guard let task = viewModel.task, let question = viewModel.currentQuestion else { positionLabel.text = "" questionLabel.text = viewModel.errorMessage ?? "正在加载试卷…" hintLabel.text = "" navigationStack.isHidden = true submitButton.setTitle("重新加载", for: .normal) submitButton.isEnabled = viewModel.errorMessage != 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 ? "单选题" : "多选题")" 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 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.isBusy 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) · 答案已保存,可稍后继续" statusLabel.textColor = viewModel.errorMessage == nil ? AppColor.textSecondary : AppColor.danger submitButton.setTitle(viewModel.isBusy ? "正在保存…" : "交卷", for: .normal) submitButton.isEnabled = !viewModel.isBusy } private func selectOption(_ id: String) { Task { @MainActor in let operation = Task { await viewModel.select(optionID: id, service: service) } await Task.yield() applyState() await operation.value applyState() } } private func goToQuestion(_ index: Int) { viewModel.goToQuestion(index) applyState() 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) 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 } guard let task = viewModel.task else { loadExam(); return } if let missing = viewModel.firstUnansweredIndex { goToQuestion(missing) showToast("还有 \(task.questions.count - viewModel.answeredCount) 道题未作答,已定位到第一道") return } let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(task.questions.count) 道题,提交后将生成本次考试记录。", 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() { 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) } } } /// 可滚动的网格答题卡,支持最多 500 道题。 @MainActor final class TrainingAnswerCardViewController: UIViewController { private let task: TrainingTask private let answers: TrainingAnswers private let currentIndex: Int private let collectionView: UICollectionView private var dataSource: UICollectionViewDiffableDataSource! /// 关闭答题卡后将用户选择的题目位置返回考试页面。 var onSelect: ((Int) -> Void)? /// 根据本次草稿展示已答和当前题,不显示正确答案。 init(task: TrainingTask, answers: TrainingAnswers, currentIndex: Int) { self.task = task self.answers = answers self.currentIndex = currentIndex collectionView = UICollectionView(frame: .zero, collectionViewLayout: Self.makeLayout()) super.init(nibName: nil, bundle: nil) } /// 保持原有五列、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.answers[self.task.questions[index].id] ?? []).isEmpty 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(task.questions.indices)) 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) } } }