import SafariServices import SnapKit import UIKit /// 原生课程信息与附件文件预览,并上报服务端确认的有效前台读时。 @MainActor final class TrainingCourseViewController: TrainingBaseViewController { private let service: any TrainingDataServing private let viewModel: TrainingRemoteReadingViewModel private let validateIdentity: @MainActor @Sendable () -> Bool private let documentLoader: any TrainingDocumentLoading private let scrollView = UIScrollView() private let contentStack = UIStackView() private let metadataStack = UIStackView() private let taskTitleLabel = TrainingUI.text(size: 17, weight: .semibold) private let courseNameLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted) private let examInfoLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted) private let introductionLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted) private let previewView = TrainingDocumentPreviewView() private var previewHeightConstraint: Constraint? private var localDocument: TrainingLocalDocument? private let stepView = TrainingStepView(currentStep: .learning) 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 appIsActive = UIApplication.shared.applicationState == .active private var isOpeningExternalLink = 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 } /// 使用正式接口与独立文件下载器读取课程附件,支持测试注入本地文件。 init(taskID: String, service: any TrainingDataServing, documentLoader: any TrainingDocumentLoading = TrainingDocumentLoader()) { self.service = service self.documentLoader = documentLoader let session = AppStore.shared.session let scope = session.accountCachePrefix let scenicID = session.currentScenicId let storeID = session.currentStoreId let token = session.token let validate: @MainActor @Sendable () -> Bool = { let current = AppStore.shared.session return current.accountCachePrefix == scope && current.currentScenicId == scenicID && current.currentStoreId == storeID && current.token == token } validateIdentity = validate viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: validate) 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 scrollView.delegate = self scrollView.accessibilityIdentifier = "training.reading.scroll" scrollView.alwaysBounceVertical = true contentStack.axis = .vertical contentStack.spacing = 14 metadataStack.axis = .vertical metadataStack.spacing = 8 metadataStack.isHidden = true [taskTitleLabel, courseNameLabel, examInfoLabel, introductionLabel].forEach(metadataStack.addArrangedSubview) taskTitleLabel.accessibilityIdentifier = "training.reading.taskTitle" courseNameLabel.accessibilityIdentifier = "training.reading.courseName" examInfoLabel.accessibilityIdentifier = "training.reading.examInfo" introductionLabel.accessibilityIdentifier = "training.reading.introduction" contentStack.addArrangedSubview(metadataStack) contentStack.addArrangedSubview(previewView) stepView.isHidden = true 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(stepView) view.addSubview(scrollView) scrollView.addSubview(contentStack) view.addSubview(bottomStack) previewView.onReady = { [weak self] previewID in guard let self else { return } guard self.validateIdentity() else { self.identityChanged(); return } guard let id = self.viewModel.currentAttachmentID, self.viewModel.markAttachmentRendered(id: id, previewID: previewID) else { return } self.contentIsReady = true self.contentLoadFailed = false self.applyState() self.resumeReading() } previewView.onFailure = { [weak self] previewID, message in guard let self, self.viewModel.attachmentPreviewID == previewID, let id = self.viewModel.currentAttachmentID else { return } self.viewModel.reportAttachmentFailure(id: id, previewID: previewID, message: message) self.contentIsReady = false self.contentLoadFailed = true self.pauseReading() self.applyState() } previewView.onOpenLink = { [weak self] url in self?.openExternalLink(url) } previewView.onContentHeightChange = { [weak self] height in guard let self else { return } self.previewHeightConstraint?.update(offset: height) self.view.layoutIfNeeded() let minimum = -self.scrollView.adjustedContentInset.top let maximum = max(minimum, self.scrollView.contentSize.height - self.scrollView.bounds.height + self.scrollView.adjustedContentInset.bottom) if self.scrollView.contentOffset.y > maximum { self.scrollView.setContentOffset(CGPoint(x: 0, y: maximum), animated: false) } self.previewView.notifyIfRenderedAndVisible() if self.isContentVisible { self.resumeReading() } } previewView.onScrollToPosition = { [weak self] top in self?.scrollToDocumentPosition(top) } applyState() } override func setupConstraints() { stepView.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(8) $0.leading.trailing.equalToSuperview().inset(13) } scrollView.snp.makeConstraints { $0.top.equalTo(stepView.snp.bottom).offset(8) $0.leading.trailing.equalTo(view.safeAreaLayoutGuide) $0.bottom.equalTo(bottomStack.snp.top) } contentStack.snp.makeConstraints { $0.edges.equalTo(scrollView.contentLayoutGuide).inset(UIEdgeInsets(top: 14, left: 13, bottom: 14, right: 13)) $0.width.equalTo(scrollView.frameLayoutGuide).offset(-26) } previewView.snp.makeConstraints { previewHeightConstraint = $0.height.equalTo(previewView.preferredContentHeight).constraint } 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(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 localDocument == nil, let id = viewModel.currentAttachmentID { selectAttachment(id) } else { 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 { let visibleFrame = previewView.convert(previewView.bounds, to: view).intersection(scrollView.frame) return pageIsVisible && contentIsReady && viewModel.isAttachmentRendered && previewView.isReady && visibleFrame.height >= 40 && !contentLoadFailed && !isOpeningExternalLink && presentedViewController == nil && navigationController?.topViewController === self && appIsActive && UIApplication.shared.applicationState == .active } private func loadCourse() { guard let request = beginUserRequest(showsLoading: true) else { return } resetDocument() contentTask = Task { @MainActor [weak self] in guard let self else { return } await performUserRequest(request) { await self.viewModel.load() await self.loadSelectedDocument() } self.applyMetadata() self.applyState() } } private func selectAttachment(_ id: String) { guard let request = beginUserRequest(showsLoading: true) else { return } resetDocument() contentTask = Task { @MainActor [weak self] in guard let self else { return } await performUserRequest(request) { await self.viewModel.selectAttachment(id: id) await self.loadSelectedDocument() } self.applyMetadata() self.applyState() } } private func resetDocument() { pauseReading() contentIsReady = false contentLoadFailed = false previewView.showStatus("正在加载附件…") localDocument?.removeTemporaryFile() localDocument = nil scrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.adjustedContentInset.top), animated: false) } private func scrollToDocumentPosition(_ top: CGFloat) { view.layoutIfNeeded() let target = previewView.convert(CGPoint(x: 0, y: top), to: scrollView).y - scrollView.adjustedContentInset.top let minimum = -scrollView.adjustedContentInset.top let maximum = max(minimum, scrollView.contentSize.height - scrollView.bounds.height + scrollView.adjustedContentInset.bottom) scrollView.setContentOffset(CGPoint(x: 0, y: min(maximum, max(minimum, target))), animated: true) } private func loadSelectedDocument() async { guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated else { return } applyMetadata() guard let attachment = viewModel.currentAttachment, let link = viewModel.currentAttachmentLink, let previewID = viewModel.attachmentPreviewID else { contentLoadFailed = viewModel.errorMessage != nil previewView.showStatus(viewModel.errorMessage ?? "暂未上传课程附件") return } do { let document = try await documentLoader.load(attachment: attachment, link: link) guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated, viewModel.attachmentPreviewID == previewID else { document.removeTemporaryFile(); return } guard validateIdentity() else { document.removeTemporaryFile() identityChanged() return } localDocument = document previewView.show(document, requestID: previewID) } catch { guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated, viewModel.attachmentPreviewID == previewID else { return } contentLoadFailed = true viewModel.reportAttachmentFailure(id: attachment.id, previewID: previewID, message: error.localizedDescription) previewView.showStatus(error.localizedDescription) } } private func applyMetadata() { guard let task = viewModel.task?.summary, let course = viewModel.course else { return } metadataStack.isHidden = false taskTitleLabel.text = task.title courseNameLabel.text = course.title courseNameLabel.isHidden = course.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty examInfoLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习" introductionLabel.text = course.introduction introductionLabel.isHidden = course.introduction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } private func applyState() { guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return } if let task = viewModel.task?.summary { stepView.configure(mode: task.mode) stepView.isHidden = false } let canInteract = userRequestID == nil actionButton.isUserInteractionEnabled = canInteract guard canInteract else { return } if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil { noticeLabel.text = viewModel.errorMessage ?? "正在加载课程…" setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载附件" : "正在加载课程…") actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil) return } if viewModel.hasLoadedAttachments && viewModel.attachments.isEmpty { noticeLabel.text = "暂未上传课程附件" setActionTitle("返回培训中心") actionButton.isEnabled = true return } if viewModel.progress?.learnerStatus == .ended { noticeLabel.text = "任务已结束,仅可回顾课程内容" setActionTitle("返回培训中心") actionButton.isEnabled = true readingTimer?.invalidate() readingTimer = nil return } if let progress = viewModel.progress, progress.readingCompleted { noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成" if viewModel.task?.summary.mode == .exam && viewModel.task?.summary.learnerStatus == .pendingExam && progress.learnerStatus == .pendingExam && progress.canStartExam { setActionTitle("开始考试") } else { setActionTitle("返回培训中心") } actionButton.isEnabled = true readingTimer?.invalidate() readingTimer = nil return } if !contentIsReady { noticeLabel.text = "正在打开课程附件…" setActionTitle("正在加载附件…") actionButton.isEnabled = false 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() previewView.showStatus("") localDocument?.removeTemporaryFile() localDocument = nil viewModel.invalidate() leaveUnavailableCourse() } @objc private func actionTapped() { guard userRequestID == nil else { return } if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil { if let id = viewModel.currentAttachmentID { selectAttachment(id) } else { loadCourse() } } else if viewModel.attachments.isEmpty { returnToCenter() } else if let progress = viewModel.progress, progress.readingCompleted { pauseReading() if viewModel.task?.summary.mode == .exam && viewModel.task?.summary.learnerStatus == .pendingExam && progress.learnerStatus == .pendingExam && progress.canStartExam { navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true) } else { returnToCenter() } } else if !viewModel.canStudy { returnToCenter() } else if viewModel.readingErrorMessage != nil { resumeReading(retrying: true) } else if viewModel.errorMessage != nil { loadCourse() } } private func openExternalLink(_ url: URL) { guard TrainingDocumentLoader.isAllowed(url), presentedViewController == nil else { return } isOpeningExternalLink = true pauseReading() let controller = SFSafariViewController(url: url) controller.delegate = self present(controller, animated: true) } 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 previewView.showStatus("") localDocument?.removeTemporaryFile() localDocument = nil if let presentedViewController { presentedViewController.dismiss(animated: false) { [weak self] in self?.returnToCenter() } } else { returnToCenter() } } deinit { localDocument?.removeTemporaryFile() } private func finishExternalLinkPresentation() { isOpeningExternalLink = false resumeReading() } } extension TrainingCourseViewController: UIScrollViewDelegate { /// 原生课程信息滚动到覆盖整个预览区时暂停,文件再次可见时才恢复。 func scrollViewDidScroll(_ scrollView: UIScrollView) { previewView.notifyIfRenderedAndVisible() if isContentVisible { resumeReading() } else if viewModel.isReading { pauseReading() } } } extension TrainingCourseViewController: SFSafariViewControllerDelegate { /// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。 func safariViewControllerDidFinish(_ controller: SFSafariViewController) { controller.dismiss(animated: true) { [weak self] in self?.finishExternalLinkPresentation() } } }