import SnapKit import UIKit /// 成绩概览、可展开解析和返回学习入口,历史记录只按最新任务状态提供重考。 @MainActor final class TrainingResultViewController: TrainingBaseViewController { private let taskID: String private let attemptID: String private let service: any TrainingDataServing private let viewModel: TrainingRemoteResultViewModel private let validateIdentity: () -> Bool private var loadFailed = false private var showsDetails = false private var usesInitialDetail: Bool private var resultLoadTask: Task? private var isRequestInFlight = false private var requestLoadingToken: UUID? private let scrollView = UIScrollView() private let contentStack = UIStackView() private let footer = UIView() private let actionButton = TrainingUI.button("完成,返回培训中心") /// 使用记录 ID 读取最新本人任务,禁止通过后从旧失败记录继续重考。 init(taskID: String, attemptID: String, service: any TrainingDataServing, initialDetail: TrainingAttemptDetail? = nil) { self.taskID = taskID self.attemptID = attemptID self.service = service let session = AppStore.shared.session let scope = session.accountCachePrefix let token = session.token let scenicID = session.currentScenicId let storeID = session.currentStoreId validateIdentity = { let current = AppStore.shared.session return current.accountCachePrefix == scope && current.token == token && current.currentScenicId == scenicID && current.currentStoreId == storeID } viewModel = TrainingRemoteResultViewModel(attemptID: attemptID, initialDetail: initialDetail) usesInitialDetail = initialDetail != nil super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setupNavigationBar() { TrainingUI.navigation(self, title: "考试结果") } override func setupUI() { view.backgroundColor = TrainingUI.background contentStack.axis = .vertical contentStack.spacing = 12 scrollView.addSubview(contentStack) view.addSubview(scrollView) footer.backgroundColor = .white let line = UIView() line.backgroundColor = TrainingUI.border footer.addSubview(line) line.snp.makeConstraints { $0.leading.trailing.top.equalToSuperview(); $0.height.equalTo(1) } footer.addSubview(actionButton) view.addSubview(footer) actionButton.accessibilityIdentifier = "training.result.action" } override func setupConstraints() { footer.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() } actionButton.snp.makeConstraints { $0.leading.trailing.equalToSuperview().inset(12) $0.top.equalToSuperview().offset(10) $0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-10) } scrollView.snp.makeConstraints { $0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide); $0.bottom.equalTo(footer.snp.top) } contentStack.snp.makeConstraints { $0.edges.equalTo(scrollView.contentLayoutGuide).inset(UIEdgeInsets(top: 14, left: 13, bottom: 20, right: 13)) $0.width.equalTo(scrollView.frameLayoutGuide).offset(-26) } } override func bindActions() { actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if leaveInaccessibleTaskIfNeeded() { return } if usesInitialDetail, let detail = viewModel.detail { usesInitialDetail = false render(detail: detail) } else { loadResult() } } override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) } private func loadResult() { Task { @MainActor in await reload() } } /// 页面出现时只刷新该次成绩,解析在用户展开后加载。 func reload() async { if let resultLoadTask { await resultLoadTask.value; return } guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews, !Task.isCancelled else { return } if leaveInaccessibleTaskIfNeeded() { return } let token = beginResultRequest() let task = Task { @MainActor [weak self] in guard let self else { return } defer { finishResultRequest(token) } await performReload() } resultLoadTask = task await task.value resultLoadTask = nil } private func performReload() async { await viewModel.load(service: service) if leaveInaccessibleTaskIfNeeded() { return } if let detail = viewModel.detail { loadFailed = false render(detail: detail) } else { loadFailed = true clearContent() contentStack.addArrangedSubview(TrainingUI.text(viewModel.errorMessage ?? "成绩加载失败", color: TrainingUI.muted)) setActionTitle("重新加载") } } /// 同步锁定请求动作,Loading 令牌只属于这一次真正发出的请求。 private func beginResultRequest() -> UUID { isRequestInFlight = true contentStack.isUserInteractionEnabled = false actionButton.isUserInteractionEnabled = false let token = beginRequestLoading() requestLoadingToken = token return token } /// 成功、失败和取消均释放原令牌,保持按钮正常外观。 private func finishResultRequest(_ token: UUID) { endRequestLoading(token) guard requestLoadingToken == token else { return } requestLoadingToken = nil isRequestInFlight = false contentStack.isUserInteractionEnabled = true actionButton.isUserInteractionEnabled = true } /// 导航前主动释放本页请求;离页后的旧 defer 可以安全再次结束同一令牌。 private func finishCurrentRequestBeforeNavigation() { if let token = requestLoadingToken { finishResultRequest(token) } } private func clearContent() { for child in contentStack.arrangedSubviews { contentStack.removeArrangedSubview(child); child.removeFromSuperview() } } private func leaveInaccessibleTaskIfNeeded() -> Bool { let identityChanged = !validateIdentity() || viewModel.isIdentityInvalid guard identityChanged || viewModel.isAccessRevoked else { return false } finishCurrentRequestBeforeNavigation() clearContent() if !identityChanged, let center = navigationController?.viewControllers.first(where: { $0 is TrainingCenterViewController }) { navigationController?.popToViewController(center, animated: true) } else { navigationController?.popToRootViewController(animated: false) } return true } private func setActionTitle(_ title: String) { var configuration = actionButton.configuration; configuration?.title = title; actionButton.configuration = configuration } private func render(detail: TrainingAttemptDetail) { let attempt = detail.attempt clearContent() let summary = UIStackView() summary.axis = .vertical summary.spacing = 11 summary.alignment = .center summary.backgroundColor = .white summary.layer.cornerRadius = 11 summary.layer.borderWidth = 1 summary.layer.borderColor = TrainingUI.border.cgColor summary.isLayoutMarginsRelativeArrangement = true summary.layoutMargins = UIEdgeInsets(top: 25, left: 12, bottom: 25, right: 12) let symbol = UIImageView(image: UIImage(systemName: attempt.passed ? "checkmark.circle.fill" : "info.circle.fill")) symbol.tintColor = attempt.passed ? TrainingUI.success : UIColor(red: 237/255, green: 140/255, blue: 36/255, alpha: 1) symbol.contentMode = .scaleAspectFit symbol.snp.makeConstraints { $0.size.equalTo(54) } summary.addArrangedSubview(symbol) let title = TrainingUI.text(attempt.passed ? "考试通过,学习任务已完成" : "本次未通过,再接再厉", size: 16.5, weight: .bold) title.textAlignment = .center summary.addArrangedSubview(title) let score = UIStackView(arrangedSubviews: [TrainingUI.text(attempt.scoreText, size: 46, weight: .bold, color: TrainingUI.primary), TrainingUI.text("/ 100 分", size: 13, color: TrainingUI.muted)]) score.alignment = .firstBaseline score.spacing = 6 score.snp.makeConstraints { $0.height.greaterThanOrEqualTo(69) } summary.addArrangedSubview(score) let dateLabel = TrainingUI.text("\(attempt.passScore) 分及格 · \(TrainingUI.date(attempt.submittedAt))", size: 12.5, color: TrainingUI.muted) dateLabel.textAlignment = .center summary.addArrangedSubview(dateLabel) contentStack.addArrangedSubview(summary) let counts = TrainingUI.card() let row = UIStackView(arrangedSubviews: [TrainingUI.text("答对 \(attempt.correctCount) 题"), TrainingUI.text("答错 \(attempt.questionCount - attempt.correctCount) 题")]) row.distribution = .fillEqually for label in row.arrangedSubviews.compactMap({ $0 as? UILabel }) { label.textAlignment = .center } counts.addArrangedSubview(row) contentStack.addArrangedSubview(counts) let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true) details.accessibilityIdentifier = "training.result.details" details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside) details.isEnabled = attempt.reviewAvailable contentStack.addArrangedSubview(details) let learning = TrainingUI.button("返回学习", plain: true) learning.accessibilityIdentifier = "training.result.learning" learning.addTarget(self, action: #selector(returnToLearning), for: .touchUpInside) contentStack.addArrangedSubview(learning) if showsDetails && attempt.reviewAvailable { for review in viewModel.reviews { let card = TrainingUI.card() let top = UIStackView(arrangedSubviews: [TrainingUI.text("第 \(review.order) 题", size: 12.5, color: TrainingUI.muted), TrainingUI.text(review.isCorrect ? "回答正确" : "回答错误", size: 12, color: review.isCorrect ? TrainingUI.success : .systemRed)]) top.distribution = .equalSpacing card.addArrangedSubview(top) card.addArrangedSubview(TrainingUI.text(review.stem, size: 15.5, weight: .semibold)) for (optionIndex, option) in review.options.enumerated() { card.addArrangedSubview(TrainingUI.text("\(TrainingQuestion.optionLetter(optionIndex)). \(option.text)", size: 13.5, color: UIColor(red: 92/255, green: 108/255, blue: 132/255, alpha: 1))) } func letters(_ ids: Set) -> String { let values = review.options.enumerated().compactMap { ids.contains($0.element.id) ? TrainingQuestion.optionLetter($0.offset) : nil } return values.isEmpty ? "未作答" : values.joined(separator: "、") } card.addArrangedSubview(TrainingUI.text("你的答案:\(letters(Set(review.selectedOptionIDs))) · 正确答案:\(letters(Set(review.correctOptionIDs)))", size: 12.5, color: TrainingUI.muted)) card.addArrangedSubview(TrainingUI.notice(review.explanation.isEmpty ? "暂无解析" : review.explanation)) contentStack.addArrangedSubview(card) } } if showsDetails && attempt.reviewAvailable { if let error = viewModel.reviewErrorMessage { contentStack.addArrangedSubview(TrainingUI.notice(error)) } if viewModel.isLoadingReviews { contentStack.addArrangedSubview(TrainingUI.text("正在加载解析…", color: TrainingUI.muted)) } if viewModel.hasMoreReviews || viewModel.reviewErrorMessage != nil { let more = TrainingUI.button(viewModel.reviewErrorMessage != nil ? "重试加载解析" : "加载更多解析", plain: true) more.accessibilityIdentifier = "training.result.reviews.more" more.addTarget(self, action: #selector(moreReviewsTapped), for: .touchUpInside) contentStack.addArrangedSubview(more) } } let canRetry = !attempt.passed && detail.taskState.canRetry contentStack.addArrangedSubview(TrainingUI.text(canRetry ? "截止前可不限次数重考,每次成绩都会保留。" : "本次记录只读,可回顾课程内容和答案解析。", size: 12, color: TrainingUI.muted)) setActionTitle(canRetry ? "再考一次" : "完成,返回培训中心") } @objc private func toggleDetails() { guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return } if leaveInaccessibleTaskIfNeeded() { return } guard let detail = viewModel.detail, detail.attempt.reviewAvailable else { return } showsDetails.toggle() render(detail: detail) guard showsDetails, !viewModel.hasLoadedReviews else { return } loadReviewPage(nextPage: false) } @objc private func moreReviewsTapped() { guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return } if leaveInaccessibleTaskIfNeeded() { return } loadReviewPage(nextPage: viewModel.hasLoadedReviews) } /// 首次展开、翻页和失败重试才持有 Loading,已缓存解析切换不发请求。 private func loadReviewPage(nextPage: Bool) { guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews, viewModel.detail?.attempt.reviewAvailable == true else { return } if nextPage { guard viewModel.hasMoreReviews else { return } } else { guard !viewModel.hasLoadedReviews else { return } } let token = beginResultRequest() Task { @MainActor in defer { finishResultRequest(token) } await viewModel.loadReviews(service: service, nextPage: nextPage) if leaveInaccessibleTaskIfNeeded() { return } if let current = viewModel.detail { render(detail: current) } } } /// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。 @objc private func returnToLearning() { guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return } if leaveInaccessibleTaskIfNeeded() { return } guard viewModel.detail != nil, let navigationController else { return } finishCurrentRequestBeforeNavigation() if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) { navigationController.popToViewController(course, animated: true) } else { navigationController.pushViewController(TrainingCourseViewController(taskID: taskID, service: service), animated: true) } } @objc private func actionTapped() { guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return } if leaveInaccessibleTaskIfNeeded() { return } if loadFailed { loadResult(); return } guard let detail = viewModel.detail, let navigationController else { return } finishCurrentRequestBeforeNavigation() if !detail.attempt.passed, detail.taskState.canRetry { navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [TrainingExamViewController(taskID: taskID, service: service, resetDraft: true)], animated: true) } else if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) { navigationController.popToViewController(center, animated: true) } else { navigationController.setViewControllers([TrainingCenterViewController(service: service)], animated: true) } } }