feat(training): 新增培训中心学习答题演示及成绩回顾

新增首页和个人页培训入口,支持课程阅读、答题卡、未交卷答案恢复、成绩记录及重考。
对齐小程序的培训首页与成绩页,答案解析默认收起并提供返回对应课程的入口。

开发版使用隔离的本机演示数据,正式培训服务尚未接入。
This commit is contained in:
han xin
2026-10-10 11:36:49 +08:00
parent e1175066b9
commit 74c451c5e5
17 changed files with 2612 additions and 7 deletions
@@ -0,0 +1,238 @@
import SafariServices
import SnapKit
import UIKit
import WebKit
/// 全部图文小节连续阅读,唯一底部按钮展示 20 秒倒计时。
@MainActor
final class TrainingCourseViewController: TrainingBaseViewController {
private let service: any TrainingServing
private let viewModel: TrainingReadingViewModel
private let webView: WKWebView
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 contentIsReady = false
private var contentLoadFailed = false
private var pageIsVisible = false
private var readingClock = TrainingReadingClock()
/// 开启当前任务的连续阅读页面,禁用课程 HTML 中的 JavaScript。
init(taskID: String, service: any TrainingServing) {
self.service = service
viewModel = TrainingReadingViewModel(taskID: taskID)
let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
webView = WKWebView(frame: .zero, configuration: configuration)
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() {
webView.navigationDelegate = self
view.backgroundColor = TrainingUI.background
webView.backgroundColor = TrainingUI.background
webView.isOpaque = false
bottomStack.axis = .vertical
bottomStack.spacing = 8
bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
bottomStack.isLayoutMarginsRelativeArrangement = true
bottomStack.backgroundColor = AppColor.cardBackground
bottomStack.addArrangedSubview(noticeLabel)
bottomStack.addArrangedSubview(actionButton)
actionButton.accessibilityIdentifier = "training.reading.action"
view.addSubview(webView)
view.addSubview(bottomStack)
}
override func setupConstraints() {
webView.snp.makeConstraints {
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(bottomStack.snp.top)
}
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
}
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)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
pageIsVisible = true
loadCourse()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
pageIsVisible = false
pauseReading()
}
override func onSessionDidExpire() {
pauseReading()
navigationController?.popToRootViewController(animated: true)
}
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)
}
applyState()
}
}
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("重新加载")
actionButton.isEnabled = true
return
}
guard let task = viewModel.task else { return }
if let reason = task.submissionBlockReason(now: Date()) {
pauseReading()
noticeLabel.text = reason
setActionTitle("返回培训中心")
actionButton.isEnabled = true
} else if task.hasFinishedReading {
pauseReading()
noticeLabel.text = "课程阅读已完成"
setActionTitle(task.mode == .exam ? "开始考试" : "完成学习")
actionButton.isEnabled = true
} else {
noticeLabel.text = "请阅读课程内容,倒计时结束后" + (task.mode == .exam ? "即可考试" : "完成学习")
setActionTitle("\(task.mode == .exam ? "开始考试" : "完成学习")(\(viewModel.remainingSeconds)s)")
actionButton.isEnabled = false
}
}
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()
}
@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)
let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in
Task { @MainActor in await self?.recordSecond() }
}
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()
}
@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)
}
}
}
extension TrainingCourseViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
contentIsReady = true
contentLoadFailed = false
applyState()
resumeReading()
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .other, navigationAction.request.url?.absoluteString == "about:blank" {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
guard navigationAction.navigationType == .linkActivated,
let url = navigationAction.request.url, url.scheme?.lowercased() == "https", url.host != nil else { return }
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
present(controller, animated: true)
}
}
extension TrainingCourseViewController: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true) { [weak self] in self?.resumeReading() }
}
}