import AVKit import SnapKit import UIKit /// 正式整单交付确认:商家核对后展示小程序码,完成结果只读取服务端订单。 @MainActor final class DroneDockConfirmationViewController: BaseViewController { /// 当前订单确认状态,独立于本地演示交付会话。 let viewModel: DroneDockConfirmationViewModel /// 整单内容使用稳定分区,点位只用于排列云端成片。 private enum Section: Hashable { case summary, state, statistics, code, receipt, manifest, point(Int), note } /// 刷新状态时重配置现有内容,避免二维码和旧数据闪空。 private enum Item: Hashable { case summary, state, statistics, code, receipt, manifest, film(Int), note, error } /// 用户操作期间禁止再次提交相同请求。 private enum Operation { case refresh, status, generate } private let imageLoader: any DroneDockPaymentImageLoading private let allowsRemoteMedia: Bool private let thumbnailProvider: ((DroneDockMaterialTask) -> UIImage?)? private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout()) private var dataSource: UICollectionViewDiffableDataSource! private let footer = DroneDeliveryReviewFooterView() private var requestTask: Task? private var operation: Operation? private var hasAppeared = false private var imageURL: URL? private var codeImage: UIImage? private var imageError: String? private var imageGeneration = 0 private var foregroundObserver: NSObjectProtocol? private var isManifestExpanded = false /// 复用原尺寸小程序码图片加载器;模拟测试可替换图片来源并关闭远程素材。 init(viewModel: DroneDockConfirmationViewModel, imageLoader: (any DroneDockPaymentImageLoading)? = nil, allowsRemoteMedia: Bool = true, thumbnailProvider: ((DroneDockMaterialTask) -> UIImage?)? = nil, deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil) { self.viewModel = viewModel self.imageLoader = imageLoader ?? DroneDockPaymentImageLoader() self.allowsRemoteMedia = allowsRemoteMedia self.thumbnailProvider = thumbnailProvider self.deliveryControllerFactory = deliveryControllerFactory ?? { order, context, taskID in DroneDockDeliveryEntry.makeController(order: order, context: context, taskID: taskID) } super.init(nibName: nil, bundle: nil) hidesBottomBarWhenPushed = true } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { requestTask?.cancel() if let foregroundObserver { NotificationCenter.default.removeObserver(foregroundObserver) } } override func setupNavigationBar() { title = "订单交付确认" navigationItem.backButtonDisplayMode = .minimal let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTapped)) refresh.accessibilityIdentifier = "drone.confirmation.refresh" refresh.accessibilityLabel = "刷新确认状态" navigationItem.rightBarButtonItem = refresh } override func setupUI() { view.backgroundColor = .white collectionView.backgroundColor = .white collectionView.alwaysBounceVertical = true collectionView.accessibilityIdentifier = "drone.confirmation.list" collectionView.register(DroneDeliveryReviewOrderCell.self, forCellWithReuseIdentifier: "summary") collectionView.register(DroneDeliveryReviewTextCell.self, forCellWithReuseIdentifier: "text") collectionView.register(DroneDeliveryReviewStatisticsCell.self, forCellWithReuseIdentifier: "statistics") collectionView.register(DroneDockConfirmationCodeCell.self, forCellWithReuseIdentifier: "code") collectionView.register(DroneDockConfirmationReceiptCell.self, forCellWithReuseIdentifier: "receipt") collectionView.register(DroneDeliveryReviewManifestHeaderCell.self, forCellWithReuseIdentifier: "manifest") collectionView.register(DroneDeliveryReviewWorkCell.self, forCellWithReuseIdentifier: "film") collectionView.register(DroneDeliveryReviewPointHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "point") view.addSubview(collectionView) view.addSubview(footer) configureDataSource() applySnapshot() foregroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] _ in Task { @MainActor [weak self] in guard let self, self.viewIfLoaded?.window != nil, self.navigationController?.topViewController === self else { return } self.run(self.viewModel.detail == nil ? .refresh : .status) } } } override func setupConstraints() { collectionView.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide) $0.leading.trailing.equalToSuperview() $0.bottom.equalTo(footer.snp.top) } footer.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() } } override func bindActions() { footer.onAcknowledgementTap = { [weak self] in guard let self, self.operation == nil else { return } self.viewModel.setReviewed(!self.viewModel.isReviewed) self.applySnapshot() } footer.onPrimaryTap = { [weak self] in self?.performPrimaryAction() } footer.onSecondaryTap = { [weak self] in self?.performSecondaryAction() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) run(hasAppeared && viewModel.code != nil ? .status : .refresh) hasAppeared = true } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if isMovingFromParent || navigationController == nil || navigationController?.isBeingDismissed == true { requestTask?.cancel() viewModel.invalidate() clearImage() } } private var filmTasks: [DroneDockMaterialTask] { viewModel.tasks.filter { $0.film != nil } } private func makeLayout() -> UICollectionViewLayout { UICollectionViewCompositionalLayout { [weak self] index, environment in guard let self, let sections = self.dataSource?.snapshot().sectionIdentifiers, sections.indices.contains(index) else { return nil } let sectionID = sections[index] if case .point = sectionID { let width = (environment.container.effectiveContentSize.width - 44) / 2 let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1))) let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 9 / 16 + 45)), repeatingSubitem: item, count: 2) group.interItemSpacing = .fixed(12) let section = NSCollectionLayoutSection(group: group) section.interGroupSpacing = 12 section.contentInsets = .init(top: 0, leading: 16, bottom: 14, trailing: 16) section.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem( layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(40)), elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)] return section } let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .estimated(sectionID == .code ? 390 : 90))) let group = NSCollectionLayoutGroup.vertical(layoutSize: item.layoutSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) section.contentInsets = .init(top: sectionID == .code || sectionID == .receipt ? 20 : 0, leading: 16, bottom: sectionID == .statistics ? 8 : 0, trailing: 16) return section } } private func configureDataSource() { dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { [weak self] list, path, item in guard let self else { return nil } switch item { case .summary: let cell = list.dequeueReusableCell(withReuseIdentifier: "summary", for: path) as! DroneDeliveryReviewOrderCell cell.apply(customer: self.viewModel.order.touristTitle, orderNumber: self.viewModel.order.orderNumber ?? "—") return cell case .statistics: let cell = list.dequeueReusableCell(withReuseIdentifier: "statistics", for: path) as! DroneDeliveryReviewStatisticsCell cell.apply(workCount: self.filmTasks.count, pointCount: Set(self.filmTasks.map(\.spotID)).count, label: "本订单已上传") return cell case .code: let cell = list.dequeueReusableCell(withReuseIdentifier: "code", for: path) as! DroneDockConfirmationCodeCell cell.apply(image: self.codeImage, error: self.imageError, workCount: self.viewModel.hasLoadedTasks ? self.filmTasks.count : nil, pointCount: self.viewModel.hasLoadedTasks ? Set(self.filmTasks.map(\.spotID)).count : nil) cell.onRetry = { [weak self] in self?.loadCodeImage(forceRefresh: true) } return cell case .receipt: let cell = list.dequeueReusableCell(withReuseIdentifier: "receipt", for: path) as! DroneDockConfirmationReceiptCell cell.apply(confirmedAt: self.viewModel.order.confirmedAt) return cell case .manifest: let cell = list.dequeueReusableCell(withReuseIdentifier: "manifest", for: path) as! DroneDeliveryReviewManifestHeaderCell if self.viewModel.code != nil { cell.apply(title: "查看本订单云端成片清单", detail: nil, expanded: self.isManifestExpanded) cell.onToggle = { [weak self] in guard let self else { return } self.isManifestExpanded.toggle() self.applySnapshot() } } else { cell.apply(title: self.viewModel.isCompleted ? "本订单云端成片" : "整单交付清单", detail: self.viewModel.isCompleted ? "当前已上传内容" : "含所有云端成片") cell.onToggle = nil } return cell case .film(let id): let cell = list.dequeueReusableCell(withReuseIdentifier: "film", for: path) as! DroneDeliveryReviewWorkCell if let task = self.filmTasks.first(where: { $0.id == id }), let film = task.film { let index = self.filmTasks.filter { $0.spotID == task.spotID }.firstIndex { $0.id == id } ?? 0 cell.apply(film: film, taskID: id, title: String(format: "成片 %02d", index + 1), localImage: self.thumbnailProvider?(task), allowsRemoteImage: self.allowsRemoteMedia) cell.onPreviewTap = { [weak self] in self?.preview(film) } } return cell case .state, .note, .error: let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! DroneDeliveryReviewTextCell if item == .error { cell.apply(title: "暂未更新", detail: [self.viewModel.errorMessage, self.viewModel.tasksErrorMessage].compactMap { $0 }.joined(separator: "\n"), symbol: "exclamationmark.circle") cell.accessibilityIdentifier = "drone.confirmation.error" } else if item == .note { cell.apply(title: self.filmTasks.isEmpty ? "暂无云端成片" : nil, detail: self.filmTasks.isEmpty ? "如已通过面对面闪传等方式交付,请核对交付情况后继续。" : "请核对约定交付的全部作品。单次上传完成,不代表整单已交齐。") cell.accessibilityIdentifier = "drone.confirmation.manifest" } else { self.applyState(to: cell) } return cell } } dataSource.supplementaryViewProvider = { [weak self] list, kind, path in guard let self, case .point(let id) = self.dataSource.snapshot().sectionIdentifiers[path.section] else { return nil } let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "point", for: path) as! DroneDeliveryReviewPointHeader let tasks = self.filmTasks.filter { $0.spotID == id } header.apply(pointName: DroneDockHomeMetric.usableText(tasks.first?.spotName) ?? "拍摄点", workCount: tasks.count) return header } } private func applyState(to cell: DroneDeliveryReviewTextCell) { cell.accessibilityIdentifier = "drone.confirmation.state" if viewModel.detail == nil { cell.apply(title: operation == nil ? "订单信息暂不可用" : "正在加载订单", detail: "确认状态以最新订单信息为准。") } else if viewModel.order.canConfirm != true { cell.apply(title: "当前订单暂不可邀请确认", detail: "请返回订单列表查看最新拍摄状态,或刷新后重试。", symbol: "info.circle") } else { cell.apply(title: "先核对,再请游客确认", detail: "一次确认整单,不按打卡点逐次确认。", symbol: "checkmark.shield") } } private func applySnapshot() { guard dataSource != nil else { return } if viewModel.code == nil { clearImage() } var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([.summary]) snapshot.appendItems([.summary], toSection: .summary) if !viewModel.isCompleted && viewModel.code == nil { snapshot.appendSections([.state]) snapshot.appendItems([.state], toSection: .state) } if viewModel.errorMessage != nil || viewModel.tasksErrorMessage != nil { if !snapshot.sectionIdentifiers.contains(.state) { snapshot.appendSections([.state]) } snapshot.appendItems([.error], toSection: .state) } if viewModel.code != nil, !viewModel.isCompleted { snapshot.appendSections([.code]) snapshot.appendItems([.code], toSection: .code) } else if viewModel.isCompleted { snapshot.appendSections([.receipt]) snapshot.appendItems([.receipt], toSection: .receipt) } else if viewModel.hasLoadedTasks, !viewModel.isCompleted { snapshot.appendSections([.statistics]) snapshot.appendItems([.statistics], toSection: .statistics) } if viewModel.hasLoadedTasks { snapshot.appendSections([.manifest]) snapshot.appendItems([.manifest], toSection: .manifest) } if viewModel.hasLoadedTasks && (viewModel.code == nil || isManifestExpanded) { for task in filmTasks where !snapshot.sectionIdentifiers.contains(.point(task.spotID)) { snapshot.appendSections([.point(task.spotID)]) snapshot.appendItems(filmTasks.filter { $0.spotID == task.spotID }.map { .film($0.id) }, toSection: .point(task.spotID)) } if !viewModel.isCompleted { snapshot.appendSections([.note]) snapshot.appendItems([.note], toSection: .note) } } let existing = Set(dataSource.snapshot().itemIdentifiers) snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) }) dataSource.apply(snapshot, animatingDifferences: false) navigationItem.rightBarButtonItem?.isEnabled = operation == nil updateFooter() } private func updateFooter() { let busy = operation != nil let needsReload = viewModel.detail == nil || !viewModel.hasLoadedTasks || viewModel.tasksErrorMessage != nil let title: String if viewModel.isCompleted { title = "返回订单列表" } else if busy { title = operation == .generate ? "正在生成确认码…" : "正在刷新…" } else if viewModel.code != nil { title = "刷新确认状态" } else if needsReload { title = "重新加载订单" } else if viewModel.order.canConfirm != true { title = "刷新订单状态" } else { title = "已交齐,展示订单确认码" } let needsReview = !viewModel.isCompleted && viewModel.code == nil && !needsReload && viewModel.order.canConfirm == true footer.apply(acknowledged: needsReview ? viewModel.isReviewed : nil, note: viewModel.isCompleted ? "仅确认交付清单,不代表对拍摄效果无异议" : nil, primaryTitle: title, primaryIdentifier: "drone.confirmation.primary", primaryEnabled: !busy && (!needsReview || viewModel.canGenerate), secondaryTitle: viewModel.isCompleted ? nil : viewModel.code != nil ? "稍后确认,返回订单" : viewModel.detail != nil ? "还未交齐,继续交付" : "返回订单", secondaryIdentifier: "drone.confirmation.back", primarySymbol: viewModel.code != nil ? "arrow.clockwise" : nil) } private func run(_ action: Operation) { guard operation == nil else { return } operation = action applySnapshot() requestTask = Task { @MainActor [weak self] in guard let self else { return } let hadCode = self.viewModel.code != nil let wasCompleted = self.viewModel.isCompleted switch action { case .refresh: await self.viewModel.refresh() case .status: await self.viewModel.refreshStatus() case .generate: await self.viewModel.generateCode() } guard !Task.isCancelled else { return } self.operation = nil let stageChanged = (!hadCode && self.viewModel.code != nil) || (!wasCompleted && self.viewModel.isCompleted) if stageChanged { self.isManifestExpanded = false } if self.viewModel.code?.imageURL != self.imageURL { self.loadCodeImage(forceRefresh: false) } self.applySnapshot() if stageChanged { self.collectionView.setContentOffset(CGPoint(x: 0, y: -self.collectionView.adjustedContentInset.top), animated: false) } } } private func performPrimaryAction() { guard operation == nil else { return } if viewModel.isCompleted { navigationController?.popViewController(animated: true) } else if viewModel.code != nil { run(.status) } else if viewModel.detail == nil || !viewModel.hasLoadedTasks || viewModel.tasksErrorMessage != nil { run(.refresh) } else if viewModel.order.canConfirm != true { run(.status) } else { run(.generate) } } private func performSecondaryAction() { guard operation == nil, presentedViewController == nil else { return } guard viewModel.code == nil, !viewModel.isCompleted, viewModel.detail != nil else { navigationController?.popViewController(animated: true) return } guard viewModel.validateContext() else { applySnapshot(); return } viewModel.setReviewed(false) applySnapshot() let sheet = DroneDockDeliveryEntry.makeMethodSheet(order: viewModel.order, context: viewModel.context, controllerFactory: deliveryControllerFactory, onDidCloseCloud: { [weak self] in self?.run(.refresh) }) present(sheet, animated: true) } @objc private func refreshTapped() { run(viewModel.code != nil || viewModel.isCompleted ? .status : .refresh) } private func clearImage() { guard imageURL != nil || codeImage != nil || imageError != nil else { return } imageGeneration &+= 1 imageLoader.cancel() imageURL = nil codeImage = nil imageError = nil collectionView.visibleCells.compactMap { $0 as? DroneDockConfirmationCodeCell }.forEach { $0.clearImage() } } private func loadCodeImage(forceRefresh: Bool) { guard viewModel.validateContext(), let code = viewModel.code else { clearImage() applySnapshot() return } imageGeneration &+= 1 let generation = imageGeneration imageLoader.cancel() imageURL = code.imageURL codeImage = nil imageError = nil imageLoader.loadImage(from: code.imageURL, forceRefresh: forceRefresh) { [weak self] result in guard let self, self.imageGeneration == generation, self.viewModel.code == code else { return } guard self.viewModel.validateContext() else { self.clearImage(); self.applySnapshot(); return } switch result { case .success(let image): self.codeImage = image case .failure: self.imageError = "确认码图片加载失败,请重试" } self.applySnapshot() } applySnapshot() } private func preview(_ film: DroneDockMaterialFilm) { guard viewModel.validateContext() else { applySnapshot(); return } guard allowsRemoteMedia else { showToast("本地模拟成片,不加载远程视频"); return } guard let url = film.previewURL else { showToast("成片播放地址暂不可用"); return } let controller = AVPlayerViewController() controller.player = AVPlayer(url: url) present(controller, animated: true) { controller.player?.play() } } }