feat(training): 接入真实培训接口与学习答题恢复

This commit is contained in:
2026-10-14 16:18:48 +08:00
parent 8862ae5401
commit 01068bb24e
28 changed files with 4945 additions and 238 deletions
@@ -204,6 +204,7 @@ final class ProfileViewController: BaseViewController {
}
private func applyViewModel() {
trainingRow.isHidden = AppStore.shared.session.accountType != .storeUser
trainingRow.configure(value: "学习课程与答题", accessory: .chevron)
nicknameField.text = viewModel.displayNickname
uidLabel.text = "UID:\(viewModel.displayUID)"
@@ -5,9 +5,11 @@ import UIKit
@MainActor
final class TrainingCenterViewController: TrainingBaseViewController {
/// 差异化列表中的任务与考试记录标识。
private enum Item: Hashable { case task(String), attempt(taskID: String, attemptID: String) }
private let service: any TrainingServing
private let viewModel = TrainingCenterViewModel()
private enum Item: Hashable { case task(String), attempt(String) }
private var reloadTask: Task<Void, Never>?
private var searchTask: Task<Void, Never>?
private let service: any TrainingDataServing
private let viewModel = TrainingRemoteCenterViewModel()
private let tableView = UITableView(frame: .zero, style: .plain)
private let refreshControl = UIRefreshControl()
private let header = UIStackView()
@@ -29,9 +31,9 @@ final class TrainingCenterViewController: TrainingBaseViewController {
private let moreButton = TrainingUI.button("加载更多记录", plain: true)
private var dataSource: UITableViewDiffableDataSource<Int, Item>!
/// 默认连接正式服务,开发演示仅由用户显式打开。
init(service: any TrainingServing = TrainingServiceFactory.production(), showsHistory: Bool = false) {
self.service = service
/// 默认使用当前登录身份连接环境配置中的培训接口。
init(service: (any TrainingDataServing)? = nil, showsHistory: Bool = false) {
self.service = service ?? TrainingRemoteServiceFactory.production()
viewModel.tab = showsHistory ? .records : .home
super.init(nibName: nil, bundle: nil)
}
@@ -41,9 +43,6 @@ final class TrainingCenterViewController: TrainingBaseViewController {
override func setupNavigationBar() {
TrainingUI.navigation(self, title: "培训中心")
#if DEBUG
if !service.isDemo { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "开发演示", style: .plain, target: self, action: #selector(demoTapped)) }
#endif
}
override func setupUI() {
@@ -87,7 +86,6 @@ final class TrainingCenterViewController: TrainingBaseViewController {
body.spacing = 11
body.isLayoutMarginsRelativeArrangement = true
body.layoutMargins = UIEdgeInsets(top: 14, left: 13, bottom: 10, right: 13)
if service.isDemo { body.addArrangedSubview(TrainingUI.demoNotice()) }
let heading = UIStackView(arrangedSubviews: [headingLabel, viewAllButton])
heading.alignment = .center
heading.spacing = 8
@@ -205,9 +203,9 @@ final class TrainingCenterViewController: TrainingBaseViewController {
cell.configure(task: task)
cell.onAction = { [weak self] in self?.openTask(task, directAction: true) }
return cell
case .attempt(let taskID, let attemptID):
guard let task = self.viewModel.tasks.first(where: { $0.id == taskID }), let attempt = task.progress.attempts.first(where: { $0.id == attemptID }), let cell = table.dequeueReusableCell(withIdentifier: TrainingRecordCell.reuseIdentifier, for: indexPath) as? TrainingRecordCell else { return nil }
cell.configure(task: task, attempt: attempt)
case .attempt(let attemptID):
guard let attempt = self.viewModel.records.first(where: { $0.id == attemptID }), let cell = table.dequeueReusableCell(withIdentifier: TrainingRecordCell.reuseIdentifier, for: indexPath) as? TrainingRecordCell else { return nil }
cell.configure(attempt: attempt)
return cell
}
}
@@ -237,7 +235,7 @@ final class TrainingCenterViewController: TrainingBaseViewController {
button.configuration = configuration
button.accessibilityTraits = index == viewModel.tab.rawValue ? [.button, .selected] : .button
}
let items: [Item] = viewModel.tab == .records ? viewModel.records.prefix(viewModel.recordLimit).map { .attempt(taskID: $0.task.id, attemptID: $0.attempt.id) } : viewModel.visibleTasks.map { .task($0.id) }
let items: [Item] = viewModel.tab == .records ? viewModel.records.map { .attempt($0.id) } : viewModel.tasks.map { .task($0.id) }
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
snapshot.appendItems(items)
@@ -247,7 +245,11 @@ final class TrainingCenterViewController: TrainingBaseViewController {
stateLabel.isHidden = !items.isEmpty
retryButton.isHidden = viewModel.errorMessage == nil
retryButton.isEnabled = !viewModel.isLoading
moreButton.isHidden = viewModel.tab != .records || viewModel.records.count <= viewModel.recordLimit
moreButton.isHidden = !viewModel.hasMore
moreButton.isEnabled = !viewModel.isLoadingMore
var moreConfiguration = moreButton.configuration
moreConfiguration?.title = viewModel.isLoadingMore ? "正在加载…" : "加载更多"
moreButton.configuration = moreConfiguration
if !viewModel.isLoading { refreshControl.endRefreshing() }
sizeTableSupplementaryViews()
}
@@ -255,6 +257,8 @@ final class TrainingCenterViewController: TrainingBaseViewController {
/// 页面出现和下拉刷新都读取最新本人任务。
func reload() async {
await viewModel.load(service: service)
guard !Task.isCancelled else { return }
if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return }
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
applyState { continuation.resume() }
}
@@ -265,29 +269,38 @@ final class TrainingCenterViewController: TrainingBaseViewController {
view.endEditing(true)
viewModel.selectTab(tab)
searchField.text = ""
applyState()
reloadTapped()
tableView.setContentOffset(.zero, animated: false)
}
@objc private func reloadTapped() {
guard !viewModel.isLoading else { return }
Task { @MainActor in await reload() }
reloadTask?.cancel()
reloadTask = Task { @MainActor [weak self] in await self?.reload() }
}
@objc private func tabTapped(_ button: UIButton) { if let tab = TrainingCenterTab(rawValue: button.tag) { selectTab(tab) } }
@objc private func filterTapped(_ button: UIButton) { viewModel.filter = button.tag == 0 ? .pendingExam : .completed; applyState() }
@objc private func searchChanged() { viewModel.keyword = searchField.text ?? ""; applyState() }
@objc private func moreTapped() { viewModel.recordLimit += 20; applyState() }
@objc private func filterTapped(_ button: UIButton) { viewModel.filter = button.tag == 0 ? .pendingExam : .completed; reloadTapped() }
@objc private func searchChanged() {
viewModel.setKeyword(searchField.text ?? "")
reloadTask?.cancel()
searchTask?.cancel()
moreButton.isHidden = true
searchTask = Task { @MainActor [weak self] in
do { try await Task.sleep(for: .milliseconds(300)) } catch { return }
self?.reloadTapped()
}
}
@objc private func moreTapped() {
Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.loadMore(service: service)
if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return }
applyState()
}
}
@objc private func viewAllTapped() { viewModel.filter = .pendingExam; selectTab(.tasks) }
#if DEBUG
@objc private func demoTapped() {
do { navigationController?.pushViewController(TrainingCenterViewController(service: try TrainingServiceFactory.demo()), animated: true) }
catch { showToast(error.localizedDescription) }
}
#endif
private func openTask(_ task: TrainingTask, directAction: Bool) {
let controller: UIViewController = directAction && TrainingTaskPresentation(task: task).canStartExam ? TrainingExamViewController(taskID: task.id, service: service) : TrainingCourseViewController(taskID: task.id, service: service)
private func openTask(_ task: TrainingTaskSummary, directAction: Bool) {
let controller: UIViewController = directAction && task.learning.canStartExam ? TrainingExamViewController(taskID: task.id, service: service) : TrainingCourseViewController(taskID: task.id, service: service)
navigationController?.pushViewController(controller, animated: true)
}
}
@@ -298,7 +311,7 @@ extension TrainingCenterViewController: UITableViewDelegate {
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .task(let id): if let task = viewModel.tasks.first(where: { $0.id == id }) { openTask(task, directAction: false) }
case .attempt(let taskID, let attemptID): navigationController?.pushViewController(TrainingResultViewController(taskID: taskID, attemptID: attemptID, service: service), animated: true)
case .attempt(let attemptID): if let attempt = viewModel.records.first(where: { $0.id == attemptID }) { navigationController?.pushViewController(TrainingResultViewController(taskID: attempt.taskID, attemptID: attempt.id, service: service), animated: true) }
}
}
}
@@ -3,28 +3,46 @@ import SnapKit
import UIKit
import WebKit
/// 全部图文小节连续阅读,唯一底部按钮展示 20 秒倒计时。
/// 正式课程按需阅读:正文分页、附件授权与服务端确认的前台读时。
@MainActor
final class TrainingCourseViewController: TrainingBaseViewController {
private let service: any TrainingServing
private let viewModel: TrainingReadingViewModel
private let service: any TrainingDataServing
private let viewModel: TrainingRemoteReadingViewModel
private let webView: WKWebView
private let toolbar = UIStackView()
private let sectionsButton = TrainingUI.button("章节目录", secondary: true)
private let attachmentsButton = TrainingUI.button("课程附件", secondary: true)
private let bottomStack = UIStackView()
private let noticeLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let actionButton = TrainingUI.button("正在加载课程…")
/// 当前课程标识,用于成绩页返回已有学习页面。
var taskID: String { viewModel.taskID }
private var readingTimer: Timer?
private var contentTask: Task<Void, Never>?
private var readingTask: Task<Void, Never>?
private var closingTask: Task<Void, Never>?
private var closingGeneration = 0
private var contentNavigation: WKNavigation?
private var appIsActive = UIApplication.shared.applicationState == .active
private var isOpeningResource = false
private var contentIsReady = false
private var contentLoadFailed = false
private var pageIsVisible = false
private var readingClock = TrainingReadingClock()
/// 开启当前任务的连续阅读页面,禁用课程 HTML 中的 JavaScript。
init(taskID: String, service: any TrainingServing) {
/// 当前任务标识,成绩页可复用已有课程页面。
var taskID: String { viewModel.taskID }
/// 使用正式数据源读取课程,课程 HTML 禁用脚本执行。
init(taskID: String, service: any TrainingDataServing) {
self.service = service
viewModel = TrainingReadingViewModel(taskID: taskID)
let session = AppStore.shared.session
let scope = session.accountCachePrefix
let scenicID = session.currentScenicId
let storeID = session.currentStoreId
let token = session.token
viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: {
let current = AppStore.shared.session
return current.accountCachePrefix == scope && current.currentScenicId == scenicID
&& current.currentStoreId == storeID && current.token == token
})
let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
webView = WKWebView(frame: .zero, configuration: configuration)
@@ -37,10 +55,14 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func setupNavigationBar() { TrainingUI.navigation(self, title: "课程学习") }
override func setupUI() {
webView.navigationDelegate = self
view.backgroundColor = TrainingUI.background
webView.navigationDelegate = self
webView.backgroundColor = TrainingUI.background
webView.isOpaque = false
toolbar.spacing = 10
toolbar.distribution = .fillEqually
toolbar.addArrangedSubview(sectionsButton)
toolbar.addArrangedSubview(attachmentsButton)
bottomStack.axis = .vertical
bottomStack.spacing = 8
bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
@@ -49,13 +71,22 @@ final class TrainingCourseViewController: TrainingBaseViewController {
bottomStack.addArrangedSubview(noticeLabel)
bottomStack.addArrangedSubview(actionButton)
actionButton.accessibilityIdentifier = "training.reading.action"
sectionsButton.accessibilityIdentifier = "training.reading.sections"
attachmentsButton.accessibilityIdentifier = "training.reading.attachments"
view.addSubview(toolbar)
view.addSubview(webView)
view.addSubview(bottomStack)
applyState()
}
override func setupConstraints() {
toolbar.snp.makeConstraints {
$0.top.equalTo(view.safeAreaLayoutGuide).offset(8)
$0.leading.trailing.equalToSuperview().inset(13)
}
webView.snp.makeConstraints {
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.top.equalTo(toolbar.snp.bottom).offset(8)
$0.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(bottomStack.snp.top)
}
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
@@ -63,14 +94,27 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func bindActions() {
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
NotificationCenter.default.addObserver(self, selector: #selector(pauseReading), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(resumeReading), name: UIApplication.didBecomeActiveNotification, object: nil)
sectionsButton.addTarget(self, action: #selector(sectionsTapped), for: .touchUpInside)
attachmentsButton.addTarget(self, action: #selector(attachmentsTapped), for: .touchUpInside)
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] {
NotificationCenter.default.addObserver(self, selector: #selector(identityChanged), name: name, object: nil)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
pageIsVisible = true
loadCourse()
if viewModel.task == nil { loadCourse() }
else {
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.refreshProgress()
applyState()
resumeReading()
}
}
}
override func viewWillDisappear(_ animated: Bool) {
@@ -79,142 +123,321 @@ final class TrainingCourseViewController: TrainingBaseViewController {
pauseReading()
}
override func onSessionDidExpire() {
pauseReading()
navigationController?.popToRootViewController(animated: true)
override func onSessionDidExpire() { identityChanged() }
private var isContentVisible: Bool {
pageIsVisible && contentIsReady && !contentLoadFailed && !isOpeningResource && presentedViewController == nil
&& navigationController?.topViewController === self && appIsActive && UIApplication.shared.applicationState == .active
}
private func loadCourse() {
pauseReading()
contentIsReady = false
contentLoadFailed = false
actionButton.isEnabled = false
Task { @MainActor in
await viewModel.load(service: service)
if let task = viewModel.task {
let sections = task.course.sections.map { "<section><h2>\(escape($0.title))</h2>\($0.contentHTML)</section>" }.joined()
let attachments = task.course.attachments.map { attachment in
guard let url = attachment.url, url.scheme?.lowercased() == "https", url.host != nil else {
return "<p>附件:\(escape(attachment.name))(尚未同步)</p>"
}
return "<p><a href=\"\(escape(url.absoluteString))\">📄 \(escape(attachment.name))</a></p>"
}.joined()
let demo = service.isDemo ? "<p class='demo'>开发演示 · 记录仅保存在本机,未同步景区后台</p>" : ""
let meta = task.mode == .exam ? "学习 + 考试 · \(task.course.sections.count) 节 · \(task.questions.count) 题 · \(task.passScore) 分及格" : "仅学习 · \(task.course.sections.count) 节"
webView.loadHTMLString("""
<!doctype html><html lang="zh-CN"><head><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<style>
*{box-sizing:border-box}body{font:15px -apple-system,BlinkMacSystemFont,sans-serif;color:#34435b;background:#f5f8fc;margin:0;padding:14px 13px;line-height:1.95;overflow-wrap:anywhere}
h1{font-size:17px;font-weight:600;line-height:1.6;color:#172033;margin:14px 0 6px}h2{font-size:15.5px;font-weight:600;color:#172033;margin:0 0 10px}img{max-width:100%;height:auto}table{max-width:100%;display:block;overflow:auto}section{margin:0 0 24px}section:last-child{margin-bottom:0}a{color:#2379ff}
.demo{color:#946116;background:#fff5e5;font-size:11px;padding:8px 10px;border-radius:6px;line-height:1.6;margin:0 0 12px}
.step{display:flex;gap:20px;background:#edf1f7;padding:9px 12px;border-radius:8px;font-size:13px;color:#8994a6}.step b{font-weight:500;color:#2379ff}
.muted{font-size:12.5px;color:#8491a6;line-height:1.65;margin:6px 0}.reading{background:white;border:1px solid #e3ebf5;border-radius:11px;padding:14px;margin-top:14px}
</style></head>
<body>\(demo)<div class='step'><b>1 课程学习</b><span>\(task.mode == .exam ? "2 在线考试" : "完成学习")</span></div><h1>\(escape(task.title))</h1><p class='muted'>\(escape(task.course.title))</p><p class='muted'>\(meta)</p><p class='muted'>\(escape(task.course.introduction))</p><div class='reading'>\(sections)</div>\(attachments)</body></html>
""", baseURL: nil)
}
contentNavigation = nil
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.load()
guard !Task.isCancelled else { return }
renderCurrentSection()
applyState()
}
}
private func selectSection(_ id: String) {
isOpeningResource = false
pauseReading()
contentIsReady = false
contentLoadFailed = false
contentNavigation = nil
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.selectSection(id: id)
guard !Task.isCancelled else { return }
renderCurrentSection()
applyState()
}
}
private func renderCurrentSection() {
guard !viewModel.isInvalidated, let task = viewModel.task?.summary,
let course = viewModel.course, let section = viewModel.currentSection else { return }
let metadata = task.mode == .exam
? "学习 + 考试 · \(course.sectionCount) 节 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格"
: "仅学习 · \(course.sectionCount) 节"
contentNavigation = webView.loadHTMLString("""
<!doctype html><html lang="zh-CN"><head><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<style>
*{box-sizing:border-box}body{font:15px -apple-system,BlinkMacSystemFont,sans-serif;color:#34435b;background:#f5f8fc;margin:0;padding:14px 13px;line-height:1.95;overflow-wrap:anywhere}
h1{font-size:17px;font-weight:600;line-height:1.6;color:#172033;margin:14px 0 6px}h2{font-size:15.5px;font-weight:600;color:#172033;margin:0 0 10px}img{max-width:100%;height:auto}table{max-width:100%;display:block;overflow:auto}a{color:#2379ff}
.step{display:flex;gap:20px;background:#edf1f7;padding:9px 12px;border-radius:8px;font-size:13px;color:#8994a6}.step b{font-weight:500;color:#2379ff}
.muted{font-size:12.5px;color:#8491a6;line-height:1.65;margin:6px 0}.reading{background:white;border:1px solid #e3ebf5;border-radius:11px;padding:14px;margin-top:14px}
</style></head><body><div class='step'><b>1 课程学习</b><span>\(task.mode == .exam ? "2 在线考试" : "完成学习")</span></div>
<h1>\(escape(task.title))</h1><p class='muted'>\(escape(course.title))</p><p class='muted'>\(metadata)</p><p class='muted'>\(escape(course.introduction))</p>
<p class='muted'>第 \(section.order) / \(course.sectionCount) 节</p><div class='reading'><h2>\(escape(section.title))</h2>\(section.contentHTML)</div></body></html>
""", baseURL: nil)
}
private func escape(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
}
private func applyState() {
if let error = viewModel.errorMessage ?? (contentLoadFailed ? "课程加载失败,请重试" : nil) {
pauseReading()
noticeLabel.text = error
setActionTitle("重新加载")
guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return }
sectionsButton.isEnabled = !viewModel.isLoading && !viewModel.sections.isEmpty
attachmentsButton.isEnabled = !viewModel.isLoading && (viewModel.course?.attachmentCount ?? 0) > 0
if let progress = viewModel.progress, progress.readingCompleted {
noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成"
if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") }
else { setActionTitle("返回培训中心") }
actionButton.isEnabled = true
readingTimer?.invalidate()
readingTimer = nil
return
}
guard let task = viewModel.task else { return }
if let reason = task.submissionBlockReason(now: Date()) {
pauseReading()
noticeLabel.text = reason
if contentLoadFailed || viewModel.currentSection == nil {
noticeLabel.text = viewModel.errorMessage ?? (contentLoadFailed ? "课程正文加载失败,请重试" : "正在加载课程…")
setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载课程" : "正在加载课程…")
actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil)
return
}
if !viewModel.canStudy {
readingTimer?.invalidate()
readingTimer = nil
noticeLabel.text = viewModel.readingErrorMessage ?? "当前任务可回顾课程,不能继续提交学习记录"
setActionTitle("返回培训中心")
actionButton.isEnabled = true
} else if task.hasFinishedReading {
pauseReading()
noticeLabel.text = "课程阅读已完成"
setActionTitle(task.mode == .exam ? "开始考试" : "完成学习")
} else if let error = viewModel.errorMessage {
readingTimer?.invalidate()
readingTimer = nil
noticeLabel.text = error
setActionTitle(viewModel.readingErrorMessage != nil ? "重试保存并继续学习" : "重新加载课程")
actionButton.isEnabled = true
} else {
noticeLabel.text = "请阅读课程内容,倒计时结束后" + (task.mode == .exam ? "即可考试" : "完成学习")
setActionTitle("\(task.mode == .exam ? "开始考试" : "完成学习")(\(viewModel.remainingSeconds)s)")
let action = viewModel.task?.summary.mode == .exam ? "开始考试" : "完成学习"
noticeLabel.text = viewModel.readingNotice ?? (viewModel.remainingSeconds == 0 ? "正在确认学习进度…" : "请在前台阅读课程内容,倒计时结束后等待保存确认")
setActionTitle("\(action)(\(viewModel.remainingSeconds)s)")
actionButton.isEnabled = false
}
}
private func setActionTitle(_ title: String) { var configuration = actionButton.configuration; configuration?.title = title; actionButton.configuration = configuration }
private func setActionTitle(_ title: String) {
var configuration = actionButton.configuration
configuration?.title = title
actionButton.configuration = configuration
}
@objc private func pauseReading() {
readingTimer?.invalidate()
readingTimer = nil
readingClock.pause()
viewModel.pauseReading()
let previousClose = closingTask
closingGeneration += 1
let epoch = closingGeneration
closingTask = Task { @MainActor [weak self] in
guard let self else { return }
await previousClose?.value
await viewModel.flush()
if closingGeneration == epoch { closingTask = nil }
applyState()
resumeReading()
}
}
@objc private func resumeReading() {
guard pageIsVisible, contentIsReady, presentedViewController == nil,
navigationController?.topViewController === self, UIApplication.shared.applicationState == .active,
readingTimer == nil, viewModel.errorMessage == nil, let task = viewModel.task,
!task.hasFinishedReading, task.submissionBlockReason(now: Date()) == nil else { return }
readingClock.resume(at: ProcessInfo.processInfo.systemUptime)
@objc private func appWillResignActive() { appIsActive = false; pauseReading() }
@objc private func appDidBecomeActive() { appIsActive = true; resumeReading() }
private func resumeReading(retrying: Bool = false) {
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), readingTask == nil else { return }
let pendingClose = closingTask
readingTask = Task { @MainActor [weak self] in
guard let self else { return }
await pendingClose?.value
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), !Task.isCancelled else {
readingTask = nil
return
}
await viewModel.startReading(at: ProcessInfo.processInfo.systemUptime)
readingTask = nil
applyState()
if isContentVisible && viewModel.isReading { installReadingTimer() }
}
}
private func installReadingTimer() {
guard readingTimer == nil else { return }
let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in
Task { @MainActor in await self?.recordSecond() }
Task { @MainActor in self?.readingTick() }
}
readingTimer = timer
RunLoop.main.add(timer, forMode: .common)
}
private func recordSecond() async {
guard pageIsVisible, contentIsReady, presentedViewController == nil,
navigationController?.topViewController === self, readingTimer != nil,
UIApplication.shared.applicationState == .active, !viewModel.isBusy else { return }
let uptime = ProcessInfo.processInfo.systemUptime
guard readingClock.takeSecond(at: uptime) else { return }
await viewModel.recordSecond(service: service)
applyState()
private func readingTick() {
guard isContentVisible, readingTask == nil, viewModel.isReading else { return }
readingTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.recordVisibleTime(at: ProcessInfo.processInfo.systemUptime)
readingTask = nil
applyState()
if isContentVisible, viewModel.canStudy, !viewModel.isReading { resumeReading() }
}
}
@objc private func identityChanged() {
readingTimer?.invalidate()
readingTimer = nil
contentTask?.cancel()
readingTask?.cancel()
closingTask?.cancel()
contentNavigation = nil
viewModel.invalidate()
leaveUnavailableCourse()
}
@objc private func actionTapped() {
if viewModel.errorMessage != nil || contentLoadFailed { loadCourse(); return }
guard let task = viewModel.task else { return }
if task.submissionBlockReason(now: Date()) != nil || task.mode == .study && task.hasFinishedReading {
if let center = navigationController?.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
navigationController?.popToViewController(center, animated: true)
}
} else if task.hasFinishedReading, task.mode == .exam {
navigationController?.pushViewController(TrainingExamViewController(taskID: task.id, service: service), animated: true)
if let progress = viewModel.progress, progress.readingCompleted {
pauseReading()
if viewModel.task?.summary.mode == .exam && progress.canStartExam {
navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true)
} else { returnToCenter() }
} else if contentLoadFailed || viewModel.currentSection == nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
} else if !viewModel.canStudy { returnToCenter() }
else if viewModel.readingErrorMessage != nil {
resumeReading(retrying: true)
} else if viewModel.errorMessage != nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
}
}
private func returnToCenter() {
if let center = navigationController?.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
navigationController?.popToViewController(center, animated: true)
} else { navigationController?.popToRootViewController(animated: true) }
}
private func leaveUnavailableCourse() {
readingTimer?.invalidate()
readingTimer = nil
contentNavigation = nil
webView.stopLoading()
webView.loadHTMLString("", baseURL: nil)
if let presentedViewController {
presentedViewController.dismiss(animated: false) { [weak self] in self?.returnToCenter() }
} else { returnToCenter() }
}
@objc private func sectionsTapped() {
isOpeningResource = true
pauseReading()
let picker = TrainingCoursePickerViewController(title: "章节目录", rows: sectionRows(), hasMore: viewModel.hasMoreSections,
selectedID: viewModel.currentSectionID, select: { [weak self] id in self?.selectSection(id) },
loadMore: { [weak self] in
guard let self else { return ([], false) }
await viewModel.loadMoreSections()
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (sectionRows(), viewModel.hasMoreSections)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
private func sectionRows() -> [TrainingCoursePickerRow] {
viewModel.sections.map { TrainingCoursePickerRow(id: $0.id, title: "\($0.order). \($0.title)") }
}
@objc private func attachmentsTapped() {
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.loadAttachments()
guard !Task.isCancelled else { return }
if viewModel.isInvalidated { applyState(); return }
if let error = viewModel.errorMessage { isOpeningResource = false; showToast(error); applyState(); return }
let picker = TrainingCoursePickerViewController(title: "课程附件", rows: attachmentRows(), hasMore: viewModel.hasMoreAttachments,
select: { [weak self] id in self?.openAttachment(id) }, loadMore: { [weak self] in
guard let self else { return ([], false) }
await viewModel.loadAttachments(loadMore: true)
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (attachmentRows(), viewModel.hasMoreAttachments)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
}
private func attachmentRows() -> [TrainingCoursePickerRow] {
viewModel.attachments.map { TrainingCoursePickerRow(id: $0.id, title: $0.name) }
}
private func presentPicker(_ picker: TrainingCoursePickerViewController) {
let navigation = UINavigationController(rootViewController: picker)
navigation.modalPresentationStyle = .pageSheet
navigation.sheetPresentationController?.detents = [.medium(), .large()]
navigation.sheetPresentationController?.prefersGrabberVisible = true
navigation.presentationController?.delegate = picker
present(navigation, animated: true)
}
private func openAttachment(_ id: String) {
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
guard let link = await viewModel.authorizeAttachment(id: id), !Task.isCancelled else {
isOpeningResource = false
if let error = viewModel.errorMessage { showToast(error) }
applyState()
return
}
let controller = SFSafariViewController(url: link.url)
controller.delegate = self
present(controller, animated: true)
}
}
private func finishResourcePresentation() {
isOpeningResource = false
resumeReading()
}
}
extension TrainingCourseViewController: WKNavigationDelegate {
/// 当前正文渲染完成且页面可见后才开始有效阅读。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = true
contentLoadFailed = false
applyState()
resumeReading()
}
/// 正文初始加载失败时停止计时,保留重试入口。
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 正文导航失败时不把失败页面停留计入学习。
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 仅允许本机 HTML 初始加载;用户点击的 HTTPS 链接交给 Safari。
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .other, navigationAction.request.url?.absoluteString == "about:blank" {
@@ -224,6 +447,7 @@ extension TrainingCourseViewController: WKNavigationDelegate {
decisionHandler(.cancel)
guard navigationAction.navigationType == .linkActivated,
let url = navigationAction.request.url, url.scheme?.lowercased() == "https", url.host != nil else { return }
isOpeningResource = true
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
@@ -232,7 +456,109 @@ extension TrainingCourseViewController: WKNavigationDelegate {
}
extension TrainingCourseViewController: SFSafariViewControllerDelegate {
/// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true) { [weak self] in self?.resumeReading() }
controller.dismiss(animated: true) { [weak self] in self?.finishResourcePresentation() }
}
}
/// 目录或附件选择器的一行展示数据,不携带业务行为。
private struct TrainingCoursePickerRow: Hashable {
let id: String
let title: String
}
/// 原生可滚动资源选择器;用户按需加载更多,选中或关闭后明确通知课程页面。
@MainActor
private final class TrainingCoursePickerViewController: UIViewController, UITableViewDelegate, UIAdaptivePresentationControllerDelegate {
/// 差异化列表中的资源项与主动分页入口。
private enum Item: Hashable { case resource(String), more }
private var rows: [TrainingCoursePickerRow]
private var hasMore: Bool
private let selectedID: String?
private let select: (String) -> Void
private let loadMore: () async -> ([TrainingCoursePickerRow], Bool)
private let close: () -> Void
private let tableView = UITableView(frame: .zero, style: .insetGrouped)
private var dataSource: UITableViewDiffableDataSource<Int, Item>!
private var isLoadingMore = false
/// 使用页面提供的展示行、明确选择动作与分页动作构造选择器。
init(title: String, rows: [TrainingCoursePickerRow], hasMore: Bool, selectedID: String? = nil,
select: @escaping (String) -> Void, loadMore: @escaping () async -> ([TrainingCoursePickerRow], Bool), close: @escaping () -> Void) {
self.rows = rows
self.hasMore = hasMore
self.selectedID = selectedID
self.select = select
self.loadMore = loadMore
self.close = close
super.init(nibName: nil, bundle: nil)
self.title = title
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = TrainingUI.background
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in
guard let self else { return }
dismiss(animated: true, completion: close)
})
tableView.delegate = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 52
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "resource")
view.addSubview(tableView)
tableView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
dataSource = UITableViewDiffableDataSource<Int, Item>(tableView: tableView) { [weak self] table, indexPath, item in
guard let self else { return nil }
let cell = table.dequeueReusableCell(withIdentifier: "resource", for: indexPath)
var content = UIListContentConfiguration.cell()
switch item {
case .resource(let id):
content.text = rows.first(where: { $0.id == id })?.title
content.textProperties.numberOfLines = 0
cell.accessoryType = id == selectedID ? .checkmark : .none
case .more:
content.text = isLoadingMore ? "正在加载…" : "加载更多"
content.textProperties.color = TrainingUI.primary
cell.accessoryType = .none
}
cell.contentConfiguration = content
return cell
}
applyRows()
}
private func applyRows() {
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
snapshot.appendItems(rows.map { .resource($0.id) })
if hasMore { snapshot.appendItems([.more]) }
if hasMore, dataSource.snapshot().indexOfItem(.more) != nil { snapshot.reconfigureItems([.more]) }
dataSource.apply(snapshot, animatingDifferences: true)
}
/// 选择后等待模态页面完全关闭,再让课程加载正文或授权附件。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard !isLoadingMore, let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .resource(let id): dismiss(animated: true) { [select] in select(id) }
case .more:
isLoadingMore = true
applyRows()
Task { @MainActor [weak self] in
guard let self else { return }
(rows, hasMore) = await loadMore()
isLoadingMore = false
applyRows()
}
}
}
/// 下拉关闭选择器时恢复正文可见性,由课程页面重新核验计时条件。
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { close() }
}
@@ -1,12 +1,15 @@
import SnapKit
import UIKit
/// 原生单选/多选答题页,支持逐题跳转、草稿恢复与确认交卷。
/// 按需分页的原生考试页,增量保存草稿并持久恢复未知交卷结果。
@MainActor
final class TrainingExamViewController: TrainingBaseViewController {
private let service: any TrainingServing
private let viewModel: TrainingExamViewModel
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)
@@ -20,10 +23,10 @@ final class TrainingExamViewController: TrainingBaseViewController {
private let statusLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let submitButton = AppButton(title: "交卷")
/// 重考时清除旧草稿,普通进入时恢复本人已保存的答案。
init(taskID: String, service: any TrainingServing, resetDraft: Bool = false) {
/// 用户明确重考才传 resetDraft;默认恢复已有草稿和未确认提交。
init(taskID: String, service: any TrainingDataServing, resetDraft: Bool = false, viewModel: TrainingRemoteExamViewModel? = nil) {
self.service = service
viewModel = TrainingExamViewModel(taskID: taskID)
self.viewModel = viewModel ?? TrainingRemoteExamViewModel(taskID: taskID, context: TrainingPendingSubmissionStore.currentContext())
self.resetDraft = resetDraft
super.init(nibName: nil, bundle: nil)
}
@@ -45,7 +48,6 @@ final class TrainingExamViewController: TrainingBaseViewController {
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
@@ -84,35 +86,49 @@ final class TrainingExamViewController: TrainingBaseViewController {
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() {
submitButton.isEnabled = false
disableControls()
Task { @MainActor in
await viewModel.load(service: service, resetDraft: resetDraft)
applyState()
finishOperation()
}
}
private func applyState() {
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
guard let task = viewModel.task, let question = viewModel.currentQuestion else {
let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果"
: viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil
guard let question = viewModel.currentQuestion else {
positionLabel.text = ""
questionLabel.text = viewModel.errorMessage ?? "正在加载试卷…"
questionLabel.text = viewModel.errorMessage ?? (viewModel.hasPendingSubmission ? "正在确认上次交卷结果…" : "正在加载试卷…")
hintLabel.text = ""
statusLabel.text = viewModel.hasPendingSubmission ? "上次提交尚未确认,恢复结果后再继续操作" : ""
navigationStack.isHidden = true
submitButton.setTitle("重新加载", for: .normal)
submitButton.isEnabled = viewModel.errorMessage != nil
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.isBusy
positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(task.questions.count) 题 · \(question.type == .single ? "单选题" : "多选题")"
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.answers[question.id]?.contains(option.id) == true
let selected = viewModel.currentSelectedIDs.contains(option.id)
let button = UIButton(type: .system)
var configuration = UIButton.Configuration.filled()
configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)"
@@ -127,44 +143,92 @@ final class TrainingExamViewController: TrainingBaseViewController {
button.contentHorizontalAlignment = .leading
button.titleLabel?.numberOfLines = 0
button.titleLabel?.lineBreakMode = .byWordWrapping
button.isEnabled = !viewModel.isBusy
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.isBusy && viewModel.currentIndex > 0
nextButton.isEnabled = !viewModel.isBusy && viewModel.currentIndex < task.questions.count - 1
statusLabel.text = viewModel.errorMessage ?? "已答 \(viewModel.answeredCount)/\(task.questions.count) · 答案已保存,可稍后继续"
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(viewModel.isBusy ? "正在保存…" : "交卷", for: .normal)
submitButton.isEnabled = !viewModel.isBusy
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
let operation = Task { await viewModel.select(optionID: id, service: service) }
await Task.yield()
applyState()
await operation.value
applyState()
await viewModel.select(optionID: id, service: service)
finishOperation()
}
}
private func goToQuestion(_ index: Int) {
viewModel.goToQuestion(index)
applyState()
scrollView.setContentOffset(.zero, animated: false)
UIAccessibility.post(notification: .screenChanged, argument: questionLabel)
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 let task = viewModel.task, !viewModel.isBusy else { return }
let controller = TrainingAnswerCardViewController(task: task, answers: viewModel.answers, currentIndex: viewModel.currentIndex)
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 }
@@ -173,52 +237,74 @@ final class TrainingExamViewController: TrainingBaseViewController {
@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) 道题未作答,已定位到第一道")
if viewModel.hasPendingMutation {
disableControls()
Task { @MainActor in await viewModel.retryMutation(service: service); finishOperation() }
return
}
let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(task.questions.count) 道题,提交后将生成本次考试记录。", preferredStyle: .alert)
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
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)
_ = 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 task: TrainingTask
private let answers: TrainingAnswers
private let questionCount: Int
private let answeredOrders: Set<Int>
private let currentIndex: Int
private let collectionView: UICollectionView
private var dataSource: UICollectionViewDiffableDataSource<Int, Int>!
/// 关闭答题卡后将用户选择的题目位置返回考试页面。
var onSelect: ((Int) -> Void)?
/// 根据本次草稿展示已答和当前题,不显示正确答案。
init(task: TrainingTask, answers: TrainingAnswers, currentIndex: Int) {
self.task = task
self.answers = answers
/// 使用总题数和已答题号展示答题卡,无需下载题目或全部答案。
init(questionCount: Int, answeredOrders: Set<Int>, 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
@@ -254,7 +340,7 @@ final class TrainingAnswerCardViewController: UIViewController {
dataSource = UICollectionViewDiffableDataSource<Int, Int>(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
let answered = self.answeredOrders.contains(index + 1)
var content = UIListContentConfiguration.cell()
content.text = "\(index + 1)"
content.textProperties.alignment = .center
@@ -272,7 +358,7 @@ final class TrainingAnswerCardViewController: UIViewController {
}
var snapshot = NSDiffableDataSourceSnapshot<Int, Int>()
snapshot.appendSections([0])
snapshot.appendItems(Array(task.questions.indices))
snapshot.appendItems(Array(0..<questionCount))
dataSource.apply(snapshot, animatingDifferences: true)
}
}
@@ -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)
+31
View File
@@ -199,6 +199,28 @@ final class TrainingTaskCell: UITableViewCell {
footer.axis = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .vertical : .horizontal
}
/// 正式任务卡只展示摘要和服务端资格,不由本地时钟推断是否可交卷。
func configure(task: TrainingTaskSummary) {
titleLabel.text = task.title
deadlineLabel.text = task.endAt.map { "截止时间:\(TrainingUI.date($0))" } ?? "未设置截止时间"
statusLabel.text = task.learnerStatus.title
statusLabel.textColor = task.learnerStatus == .completed ? TrainingUI.success : TrainingUI.primary
let publisher = task.publisherName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
publisherLabel.text = "发布人:\(publisher.isEmpty ? "未记录" : publisher)"
metaLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.sectionCount) 节 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习 · \(task.sectionCount) 节"
let completed = task.learnerStatus == .completed
hintLabel.text = completed ? "已完成本次学习任务" : task.learning.canStartExam ? "课程已学完,可以开始考试" : task.learning.canStudy ? "请阅读课程,完成学习要求" : "任务暂不可提交,可回顾课程内容"
let progress = min(100, max(0, task.learning.progressPercent))
progressView.progress = Float(progress) / 100
progressLabel.text = "学习进度 \(progress)%"
var configuration = actionButton.configuration
configuration?.title = completed ? "回顾学习" : task.learning.canStartExam ? (task.learning.hasDraft ? "继续答题" : "开始考试") : task.learning.canStudy ? "去学习" : "查看课程"
actionButton.configuration = configuration
actionButton.isEnabled = task.learning.canViewCourse || task.learning.canStartExam
actionButton.accessibilityIdentifier = "training.task.action.\(task.id)"
footer.axis = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .vertical : .horizontal
}
@objc private func actionTapped() { onAction?() }
}
@@ -245,6 +267,15 @@ final class TrainingRecordCell: UITableViewCell {
statusLabel.text = attempt.passed ? "已通过" : "未通过"
statusLabel.textColor = attempt.passed ? TrainingUI.success : .systemRed
}
/// 正式历史列表使用成绩摘要,不读取任务或完整解析。
func configure(attempt: TrainingAttemptSummary) {
titleLabel.text = attempt.taskTitle
scoreLabel.text = "\(attempt.scoreText) 分"
detailLabel.text = "\(TrainingUI.date(attempt.submittedAt)) · 答对 \(attempt.correctCount) / \(attempt.questionCount) 题"
statusLabel.text = attempt.passed ? "已通过" : "未通过"
statusLabel.textColor = attempt.passed ? TrainingUI.success : .systemRed
}
}
/// 培训页面在账号或景区切换时立即关闭,停止展示旧身份记录。