feat(training): 接入真实培训接口与学习答题恢复
This commit is contained in:
@@ -6,21 +6,35 @@ import UIKit
|
||||
final class TrainingResultViewController: TrainingBaseViewController {
|
||||
private let taskID: String
|
||||
private let attemptID: String
|
||||
private let service: any TrainingServing
|
||||
private var loadedTask: TrainingTask?
|
||||
private var loadedAttempt: TrainingAttempt?
|
||||
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<Void, Never>?
|
||||
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 TrainingServing) {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -60,27 +74,40 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
||||
}
|
||||
|
||||
override func bindActions() { actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) }
|
||||
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); loadResult() }
|
||||
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 }
|
||||
let task = Task<Void, Never> { @MainActor [weak self] in
|
||||
await self?.performReload()
|
||||
}
|
||||
resultLoadTask = task
|
||||
await task.value
|
||||
resultLoadTask = nil
|
||||
}
|
||||
|
||||
private func performReload() async {
|
||||
actionButton.isEnabled = false
|
||||
do {
|
||||
let task = try await service.task(id: taskID)
|
||||
guard let attempt = task.progress.attempts.first(where: { $0.id == attemptID }) else { throw TrainingError.notFound }
|
||||
loadedTask = task
|
||||
loadedAttempt = attempt
|
||||
await viewModel.load(service: service)
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
if let detail = viewModel.detail {
|
||||
loadFailed = false
|
||||
render(task: task, attempt: attempt)
|
||||
} catch {
|
||||
loadedTask = nil
|
||||
loadedAttempt = nil
|
||||
render(detail: detail)
|
||||
} else {
|
||||
loadFailed = true
|
||||
clearContent()
|
||||
contentStack.addArrangedSubview(TrainingUI.text(error.localizedDescription, color: TrainingUI.muted))
|
||||
contentStack.addArrangedSubview(TrainingUI.text(viewModel.errorMessage ?? "成绩加载失败", color: TrainingUI.muted))
|
||||
setActionTitle("重新加载")
|
||||
}
|
||||
actionButton.isEnabled = true
|
||||
@@ -90,11 +117,22 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
||||
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 }
|
||||
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(task: TrainingTask, attempt: TrainingAttempt) {
|
||||
private func render(detail: TrainingAttemptDetail) {
|
||||
let attempt = detail.attempt
|
||||
clearContent()
|
||||
if attempt.isDemo { contentStack.addArrangedSubview(TrainingUI.demoNotice()) }
|
||||
let summary = UIStackView()
|
||||
summary.axis = .vertical
|
||||
summary.spacing = 11
|
||||
@@ -118,9 +156,9 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
||||
score.spacing = 6
|
||||
score.snp.makeConstraints { $0.height.greaterThanOrEqualTo(69) }
|
||||
summary.addArrangedSubview(score)
|
||||
let detail = TrainingUI.text("\(task.passScore) 分及格 · \(TrainingUI.date(attempt.submittedAt))", size: 12.5, color: TrainingUI.muted)
|
||||
detail.textAlignment = .center
|
||||
summary.addArrangedSubview(detail)
|
||||
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) 题")])
|
||||
@@ -131,44 +169,74 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
||||
let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true)
|
||||
details.accessibilityIdentifier = "training.result.details"
|
||||
details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside)
|
||||
details.isEnabled = attempt.reviewAvailable && !viewModel.isLoadingReviews
|
||||
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 {
|
||||
for (index, review) in attempt.reviews.enumerated() {
|
||||
if showsDetails && attempt.reviewAvailable {
|
||||
for review in viewModel.reviews {
|
||||
let card = TrainingUI.card()
|
||||
let top = UIStackView(arrangedSubviews: [TrainingUI.text("第 \(index + 1) 题", size: 12.5, color: TrainingUI.muted), TrainingUI.text(review.isCorrect ? "回答正确" : "回答错误", size: 12, color: review.isCorrect ? TrainingUI.success : .systemRed)])
|
||||
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.question.stem, size: 15.5, weight: .semibold))
|
||||
for (optionIndex, option) in review.question.options.enumerated() {
|
||||
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>) -> String {
|
||||
let values = review.question.options.enumerated().compactMap { ids.contains($0.element.id) ? TrainingQuestion.optionLetter($0.offset) : nil }
|
||||
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(review.selectedIDs)) · 正确答案:\(letters(review.correctIDs))", size: 12.5, color: TrainingUI.muted))
|
||||
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)
|
||||
}
|
||||
}
|
||||
let canRetry = !attempt.passed && task.submissionBlockReason(now: Date()) == nil
|
||||
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.isEnabled = !viewModel.isLoadingReviews
|
||||
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 let task = loadedTask, let attempt = loadedAttempt else { return }
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
guard let detail = viewModel.detail else { return }
|
||||
showsDetails.toggle()
|
||||
render(task: task, attempt: attempt)
|
||||
render(detail: detail)
|
||||
guard showsDetails else { return }
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await viewModel.loadReviews(service: service)
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
if let current = viewModel.detail { render(detail: current) }
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func moreReviewsTapped() {
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await viewModel.loadReviews(service: service, nextPage: viewModel.hasLoadedReviews)
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
if let current = viewModel.detail { render(detail: current) }
|
||||
}
|
||||
}
|
||||
|
||||
/// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。
|
||||
@objc private func returnToLearning() {
|
||||
guard loadedTask != nil, let navigationController else { return }
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
guard viewModel.detail != nil, let navigationController else { return }
|
||||
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
|
||||
navigationController.popToViewController(course, animated: true)
|
||||
} else {
|
||||
@@ -177,9 +245,10 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
||||
}
|
||||
|
||||
@objc private func actionTapped() {
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
if loadFailed { loadResult(); return }
|
||||
guard let task = loadedTask, let attempt = loadedAttempt, let navigationController else { return }
|
||||
if !attempt.passed, task.submissionBlockReason(now: Date()) == nil {
|
||||
guard let detail = viewModel.detail, let navigationController else { return }
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user