import SafariServices import SnapKit import UIKit import WebKit /// 正式课程按需阅读:正文分页、附件授权与服务端确认的前台读时。 @MainActor final class TrainingCourseViewController: TrainingBaseViewController { private let service: any TrainingDataServing private let viewModel: TrainingRemoteReadingViewModel private let webView: WKWebView private let headerStack = UIStackView() private let toolbar = UIStackView() private let stepView = TrainingStepView(currentStep: .learning) 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("正在加载课程…") private var readingTimer: Timer? private var contentTask: Task? private var readingTask: Task? private var closingTask: Task? 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 userRequestID: UUID? /// 用户操作独占的请求票据;缓存复用仍防重复操作,但不展示全局进度。 private struct UserRequest { let id: UUID let loadingToken: UUID? } /// 当前任务标识,成绩页可复用已有课程页面。 var taskID: String { viewModel.taskID } /// 使用正式数据源读取课程,课程 HTML 禁用脚本执行。 init(taskID: String, service: any TrainingDataServing) { self.service = service 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) 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 webView.navigationDelegate = self webView.backgroundColor = TrainingUI.background webView.isOpaque = false toolbar.spacing = 10 toolbar.distribution = .fillEqually toolbar.addArrangedSubview(sectionsButton) toolbar.addArrangedSubview(attachmentsButton) headerStack.axis = .vertical headerStack.spacing = 20 headerStack.addArrangedSubview(toolbar) 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" sectionsButton.accessibilityIdentifier = "training.reading.sections" attachmentsButton.accessibilityIdentifier = "training.reading.attachments" view.addSubview(headerStack) view.addSubview(webView) view.addSubview(bottomStack) applyState() } override func setupConstraints() { headerStack.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(8) $0.leading.trailing.equalToSuperview().inset(13) } webView.snp.makeConstraints { $0.top.equalTo(headerStack.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) } } override func bindActions() { actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) 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 let previousContent = contentTask contentTask = Task { @MainActor [weak self] in guard let self else { return } await previousContent?.value guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self, userRequestID == nil else { return } if viewModel.task == nil { loadCourse() } else if viewModel.currentSection == nil, let id = viewModel.currentSectionID { selectSection(id) } else { if contentNavigation == nil { renderCurrentSection() } await viewModel.refreshProgress() applyState() resumeReading() } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) pageIsVisible = false contentTask?.cancel() pauseReading() } 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() { guard let request = beginUserRequest(showsLoading: true) else { return } pauseReading() contentIsReady = false contentLoadFailed = false contentNavigation = nil contentTask = Task { @MainActor [weak self] in guard let self else { return } await performUserRequest(request) { await self.viewModel.load() } guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return } renderCurrentSection() applyState() } } private func selectSection(_ id: String) { guard let request = beginUserRequest(showsLoading: !viewModel.isSectionCached(id: id)) else { return } isOpeningResource = false pauseReading() contentIsReady = false contentLoadFailed = false contentNavigation = nil contentTask = Task { @MainActor [weak self] in guard let self else { return } await performUserRequest(request) { await self.viewModel.selectSection(id: id) } guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self 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("""

\(escape(task.title))

\(escape(course.title))

\(metadata)

\(escape(course.introduction))

第 \(section.order) / \(course.sectionCount) 节

\(escape(section.title))

\(section.contentHTML)
""", baseURL: nil) } private func escape(_ text: String) -> String { text.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<") .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """) } private func applyState() { guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return } if let task = viewModel.task?.summary { stepView.configure(mode: task.mode) if stepView.superview == nil { headerStack.addArrangedSubview(stepView) } } let canInteract = userRequestID == nil sectionsButton.isUserInteractionEnabled = canInteract attachmentsButton.isUserInteractionEnabled = canInteract actionButton.isUserInteractionEnabled = canInteract guard canInteract else { return } sectionsButton.isEnabled = !viewModel.sections.isEmpty attachmentsButton.isEnabled = (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 } 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 let error = viewModel.errorMessage { readingTimer?.invalidate() readingTimer = nil noticeLabel.text = error setActionTitle(viewModel.readingErrorMessage != nil ? "重试保存并继续学习" : "重新加载课程") actionButton.isEnabled = true } else { 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 beginUserRequest(showsLoading: Bool) -> UserRequest? { guard userRequestID == nil, !viewModel.isInvalidated else { return nil } let request = UserRequest(id: UUID(), loadingToken: showsLoading ? beginRequestLoading() : nil) userRequestID = request.id applyState() return request } private func endUserRequest(_ request: UserRequest) { if let token = request.loadingToken { endRequestLoading(token) } guard userRequestID == request.id else { return } userRequestID = nil applyState() } private func performUserRequest(_ request: UserRequest, operation: () async -> Value) async -> Value { defer { endUserRequest(request) } return await operation() } @objc private func pauseReading() { readingTimer?.invalidate() readingTimer = nil 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 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 request = retrying ? beginUserRequest(showsLoading: true) : nil guard !retrying || request != nil else { return } let pendingClose = closingTask readingTask = Task { @MainActor [weak self] in guard let self else { return } defer { if let request { endUserRequest(request) } } 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 self?.readingTick() } } readingTimer = timer RunLoop.main.add(timer, forMode: .common) } 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() { guard userRequestID == nil else { return } 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() { guard userRequestID == nil, !viewModel.sections.isEmpty else { return } 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) } guard viewModel.hasMoreSections, let request = beginUserRequest(showsLoading: true) else { return (sectionRows(), viewModel.hasMoreSections) } await performUserRequest(request) { await self.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() { guard let request = beginUserRequest(showsLoading: !viewModel.hasLoadedAttachments) else { return } isOpeningResource = true pauseReading() contentTask = Task { @MainActor [weak self] in guard let self else { return } await performUserRequest(request) { await self.viewModel.loadAttachments() } guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self 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) } guard viewModel.hasMoreAttachments, let request = beginUserRequest(showsLoading: true) else { return (attachmentRows(), viewModel.hasMoreAttachments) } await performUserRequest(request) { await self.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) { guard let request = beginUserRequest(showsLoading: true) else { return } isOpeningResource = true pauseReading() contentTask = Task { @MainActor [weak self] in guard let self else { return } let link = await performUserRequest(request) { await self.viewModel.authorizeAttachment(id: id) } guard pageIsVisible, navigationController?.topViewController === self, !Task.isCancelled else { return } guard let link 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" { decisionHandler(.allow) return } 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 present(controller, animated: true) } } extension TrainingCourseViewController: SFSafariViewControllerDelegate { /// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。 func safariViewControllerDidFinish(_ controller: SFSafariViewController) { 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! 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(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() 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() } }