import SnapKit import UIKit /// 整单核对页的导航请求由机巢入口处理,不在这里打开游客网页或执行上传。 @MainActor protocol DroneDeliveryReviewViewControllerDelegate: AnyObject { /// 商家尚未交齐或需要追加成片时继续交付。 func deliveryReviewViewControllerDidRequestUpload(_ controller: DroneDeliveryReviewViewController) /// 只读预览当前核对清单或历史确认快照中的成片。 func deliveryReviewViewController(_ controller: DroneDeliveryReviewViewController, didRequestPreview work: DroneDeliveryWork) } /// 商家侧整单交付核对、演示确认码与冻结确认记录;刷新不会模拟游客主动确认。 @MainActor final class DroneDeliveryReviewViewController: BaseViewController { /// 交付与确认状态的唯一业务来源,核对范围始终为整单全部点位。 let viewModel: DroneDeliveryViewModel /// 成片上传和本地预览的跨页面导航。 weak var delegate: DroneDeliveryReviewViewControllerDelegate? /// 当前实际呈现清单的只读预览范围;历史记录不会夹带后来追加的作品。 var previewMaterials: [DroneMaterial] { displayedGroups.flatMap(\.works).map(\.previewMaterial) } /// 页面阶段只决定呈现,不改变确认会话。 private enum Stage: Equatable { case review, code, receipt } /// 辅助内容与每个点位采用稳定的 Diffable 分区身份。 private enum Section: Hashable { case order, introduction, statistics, code, receipt, manifestTitle, point(String), note } /// 素材身份与可变的确认状态分离,刷新时重配置现有项。 private enum Item: Hashable { case order, introduction, statistics, code, receipt, manifestTitle, work(String), note } private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout()) private var dataSource: UICollectionViewDiffableDataSource! private let footerView = DroneDeliveryReviewFooterView() private var displayedReceipt: DroneDeliveryConfirmationSession? private var groupsByID: [String: DroneDeliveryWorkGroup] = [:] private var worksByID: [String: DroneDeliveryWork] = [:] private var activeReceipt: DroneDeliveryConfirmationSession? { displayedReceipt ?? (viewModel.confirmationPhase == .confirmed ? viewModel.latestReceipt : nil) } private var stage: Stage { if activeReceipt != nil { return .receipt } return viewModel.confirmationPhase == .review ? .review : .code } private var displayedGroups: [DroneDeliveryWorkGroup] { if let receipt = activeReceipt { return Self.groups(for: receipt.works) } return stage == .code ? viewModel.confirmationGroups : viewModel.workGroups } /// 从任意商家订单入口打开整单核对,不继承上传页面的点位筛选。 init(viewModel: DroneDeliveryViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) hidesBottomBarWhenPushed = true } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshDeliveryState() } /// 成片上传弹层结束后显式刷新本地快照,不推进游客确认状态。 func refreshDeliveryState() { viewModel.refresh() if dataSource != nil { applySnapshot(animated: false) } } override func setupNavigationBar() { title = "订单交付确认" navigationItem.backButtonDisplayMode = .minimal let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(backTapped)) back.accessibilityIdentifier = "drone.delivery.review.back" back.accessibilityLabel = "返回" navigationItem.leftBarButtonItem = back updateNavigationActions() } override func setupUI() { view.backgroundColor = .white collectionView.backgroundColor = .white collectionView.alwaysBounceVertical = true collectionView.showsVerticalScrollIndicator = false collectionView.accessibilityIdentifier = "drone.delivery.review.list" collectionView.register(DroneDeliveryReviewOrderCell.self, forCellWithReuseIdentifier: "order") collectionView.register(DroneDeliveryReviewTextCell.self, forCellWithReuseIdentifier: "text") collectionView.register(DroneDeliveryReviewStatisticsCell.self, forCellWithReuseIdentifier: "statistics") collectionView.register(DroneDeliveryReviewWorkCell.self, forCellWithReuseIdentifier: "work") collectionView.register(DroneDeliveryConfirmationCodeCell.self, forCellWithReuseIdentifier: "code") collectionView.register(DroneDeliveryReceiptCell.self, forCellWithReuseIdentifier: "receipt") collectionView.register(DroneDeliveryReviewPointHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "point") view.addSubview(collectionView) view.addSubview(footerView) configureDataSource() applySnapshot(animated: false) } override func setupConstraints() { collectionView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide) make.leading.trailing.equalToSuperview() make.bottom.equalTo(footerView.snp.top) } footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() } } override func bindActions() { footerView.onAcknowledgementTap = { [weak self] in guard let self, self.stage == .review else { return } self.viewModel.setAllDeliveredReviewed(!self.viewModel.isAllDeliveredReviewed) self.applySnapshot(animated: true) } footerView.onPrimaryTap = { [weak self] in self?.performPrimaryAction() } footerView.onSecondaryTap = { [weak self] in self?.performSecondaryAction() } } private func makeLayout() -> UICollectionViewLayout { UICollectionViewCompositionalLayout { [weak self] index, environment in guard let self, self.dataSource != nil else { return nil } let sections = self.dataSource.snapshot().sectionIdentifiers guard sections.indices.contains(index) else { return nil } if case .point = sections[index] { let width = (environment.container.effectiveContentSize.width - 44) / 2 let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1))) let group = NSCollectionLayoutGroup.horizontal( layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 0.57 + 49)), repeatingSubitem: item, count: 2 ) group.interItemSpacing = .fixed(12) let section = NSCollectionLayoutSection(group: group) section.interGroupSpacing = 12 section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 18, trailing: 16) section.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem( layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(40)), elementKind: UICollectionView.elementKindSectionHeader, alignment: .top )] return section } let estimate: CGFloat switch sections[index] { case .code: estimate = 450 case .receipt: estimate = 360 case .statistics: estimate = 66 default: estimate = 70 } let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(estimate))) let group = NSCollectionLayoutGroup.vertical( layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(estimate)), subitems: [item] ) let section = NSCollectionLayoutSection(group: group) section.contentInsets = NSDirectionalEdgeInsets(top: sections[index] == .code ? 18 : 0, leading: 16, bottom: sections[index] == .statistics ? 8 : 0, trailing: 16) return section } } private func configureDataSource() { dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { [weak self] list, indexPath, item in guard let self else { return nil } switch item { case .order: let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: indexPath) as! DroneDeliveryReviewOrderCell cell.apply(customer: self.activeReceipt?.visitorName ?? self.viewModel.order?.customerName ?? "订单暂不可用", orderNumber: self.activeReceipt?.orderNumber ?? self.viewModel.order?.orderNumber ?? "请返回订单重新进入") return cell case .statistics: let cell = list.dequeueReusableCell(withReuseIdentifier: "statistics", for: indexPath) as! DroneDeliveryReviewStatisticsCell cell.apply(workCount: self.viewModel.works.count, pointCount: self.viewModel.workGroups.count) return cell case .work(let id): let cell = list.dequeueReusableCell(withReuseIdentifier: "work", for: indexPath) as! DroneDeliveryReviewWorkCell if let work = self.worksByID[id] { cell.apply(id: work.id, title: work.title, fileName: work.fileName, previewAssetName: work.previewAssetName, durationText: work.durationText) cell.onPreviewTap = { [weak self] in guard let self, let current = self.worksByID[id] else { return } self.delegate?.deliveryReviewViewController(self, didRequestPreview: current) } } return cell case .code: let cell = list.dequeueReusableCell(withReuseIdentifier: "code", for: indexPath) as! DroneDeliveryConfirmationCodeCell let session = self.viewModel.confirmationSession let feedback = self.viewModel.confirmationPhase == .feedback ? session?.feedback.map { "\($0.kind.title):\($0.note.isEmpty ? "请与游客核对成片清单" : $0.note)" } : nil cell.apply(status: self.viewModel.confirmationPhase.title, tone: self.viewModel.confirmationPhase == .feedback ? .orange : .blue, workCount: session?.works.count ?? 0, pointCount: self.viewModel.confirmationGroups.count, feedback: feedback) return cell case .receipt: let cell = list.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath) as! DroneDeliveryReceiptCell if let receipt = self.activeReceipt { cell.apply(workCount: receipt.works.count, pointCount: Self.groups(for: receipt.works).count, visitor: receipt.visitorName, confirmedAt: Self.dateText(receipt.confirmedAt), operatorName: receipt.operatorName) } return cell case .introduction, .manifestTitle, .note: let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: indexPath) as! DroneDeliveryReviewTextCell switch item { case .introduction: cell.apply(title: "先核对,再请游客确认", detail: "一次确认整单,不按打卡点逐次确认。", symbol: "checkmark.shield") case .manifestTitle: let title = self.stage == .receipt ? "已确认的成片清单" : (self.stage == .code ? "本次整单确认清单" : "整单交付清单") cell.apply(title: title, detail: self.stage == .review ? "含所有上传批次" : "确认时的固定作品清单") case .note: let message: String switch self.stage { case .review: message = self.viewModel.works.isEmpty ? "暂无已交付成片。请先完成成片交付,再核对整单作品。" : "请核对约定交付的全部作品。单次上传完成,不代表整单已交齐。" case .code: message = "演示图案没有有效游客链接,不提供真实扫码收货服务。刷新仅同步本机状态,不会代替游客主动确认。" case .receipt: message = "当前为本机演示记录,并非真实收货凭据。新增成片不会覆盖这份确认清单。" } cell.apply(title: nil, detail: message) default: break } return cell } } dataSource.supplementaryViewProvider = { [weak self] list, kind, indexPath in guard let self else { return nil } let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "point", for: indexPath) as! DroneDeliveryReviewPointHeader self.applyPointHeader(header, sectionIndex: indexPath.section) return header } } private func applyPointHeader(_ header: DroneDeliveryReviewPointHeader, sectionIndex: Int) { let sections = dataSource.snapshot().sectionIdentifiers guard sections.indices.contains(sectionIndex), case .point(let id) = sections[sectionIndex], let group = groupsByID[id] else { return } header.apply(pointName: group.pointName, workCount: group.works.count) } private func applySnapshot(animated: Bool) { guard isViewLoaded, dataSource != nil else { return } let groups = displayedGroups groupsByID = Dictionary(uniqueKeysWithValues: groups.map { ($0.id, $0) }) worksByID = Dictionary(uniqueKeysWithValues: groups.flatMap(\.works).map { ($0.id, $0) }) let previous = dataSource.snapshot() let existing = Set(previous.itemIdentifiers) var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([.order]) snapshot.appendItems([.order], toSection: .order) switch stage { case .review: snapshot.appendSections([.introduction, .statistics]) snapshot.appendItems([.introduction], toSection: .introduction) snapshot.appendItems([.statistics], toSection: .statistics) case .code: snapshot.appendSections([.code]) snapshot.appendItems([.code], toSection: .code) case .receipt: snapshot.appendSections([.receipt]) snapshot.appendItems([.receipt], toSection: .receipt) } snapshot.appendSections([.manifestTitle]) snapshot.appendItems([.manifestTitle], toSection: .manifestTitle) for group in groups { let section = Section.point(group.id) snapshot.appendSections([section]) snapshot.appendItems(group.works.map { .work($0.id) }, toSection: section) } snapshot.appendSections([.note]) snapshot.appendItems([.note], toSection: .note) snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) }) applyFooter() updateNavigationActions() dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in guard let self else { return } let kind = UICollectionView.elementKindSectionHeader for path in self.collectionView.indexPathsForVisibleSupplementaryElements(ofKind: kind) { guard let header = self.collectionView.supplementaryView(forElementKind: kind, at: path) as? DroneDeliveryReviewPointHeader else { continue } self.applyPointHeader(header, sectionIndex: path.section) } } if previous.sectionIdentifiers != snapshot.sectionIdentifiers { collectionView.collectionViewLayout.invalidateLayout() } } private func applyFooter() { switch stage { case .review: footerView.apply(acknowledged: viewModel.isAllDeliveredReviewed, note: "本机交互演示 · 无真实游客链接", primaryTitle: "已交齐,展示订单确认码", primaryIdentifier: "drone.delivery.review.showCode", primaryEnabled: viewModel.canCreateConfirmation, secondaryTitle: "还未交齐,继续交付", secondaryIdentifier: "drone.delivery.review.continueUpload") case .code: let feedback = viewModel.confirmationPhase == .feedback footerView.apply(acknowledged: nil, note: "本机演示状态,不代表真实收货", primaryTitle: feedback ? "重新核对整单" : "刷新确认状态", primaryIdentifier: feedback ? "drone.delivery.review.restart" : "drone.delivery.confirmation.refresh", primaryEnabled: true, secondaryTitle: feedback ? "继续补充交付" : "稍后确认,返回订单", secondaryIdentifier: feedback ? "drone.delivery.review.continueUpload" : "drone.delivery.confirmation.later") case .receipt: let hasCurrentReview = displayedReceipt != nil && viewModel.confirmationPhase != .confirmed footerView.apply(acknowledged: nil, note: "仅确认交付清单,不代表对拍摄效果无异议", primaryTitle: hasCurrentReview ? "返回当前整单核对" : "返回订单", primaryIdentifier: hasCurrentReview ? "drone.delivery.review.current" : "drone.delivery.confirmation.backToOrders", primaryEnabled: true, secondaryTitle: hasCurrentReview ? nil : "追加成片,开始新核对", secondaryIdentifier: "drone.delivery.review.continueUpload") } } private func performPrimaryAction() { switch stage { case .review: guard viewModel.createConfirmationSession() else { return } case .code: if viewModel.confirmationPhase == .feedback { viewModel.beginNewReview() } else { viewModel.refreshConfirmation() } case .receipt: if displayedReceipt != nil && viewModel.confirmationPhase != .confirmed { displayedReceipt = nil } else { closePage(); return } } applySnapshot(animated: true) collectionView.setContentOffset(CGPoint(x: 0, y: -collectionView.adjustedContentInset.top), animated: false) } private func performSecondaryAction() { switch stage { case .review, .receipt: displayedReceipt = nil delegate?.deliveryReviewViewControllerDidRequestUpload(self) case .code: if viewModel.confirmationPhase == .feedback { delegate?.deliveryReviewViewControllerDidRequestUpload(self) } else { closePage() } } } private func updateNavigationActions() { var actions: [UIBarButtonItem] = [] if !viewModel.confirmationRecords.isEmpty { let records = viewModel.confirmationRecords.map { record in UIAction(title: "\(Self.dateText(record.confirmedAt)) · \(record.works.count)个成片", state: self.activeReceipt?.id == record.id ? .on : .off) { [weak self] _ in guard let self else { return } self.displayedReceipt = record self.applySnapshot(animated: true) self.collectionView.setContentOffset(CGPoint(x: 0, y: -self.collectionView.adjustedContentInset.top), animated: false) } } let history = UIBarButtonItem(image: UIImage(systemName: "clock.arrow.circlepath"), menu: UIMenu(title: "本机演示确认记录", children: records)) history.accessibilityIdentifier = "drone.delivery.confirmation.history" history.accessibilityLabel = "查看确认记录" actions.append(history) } #if DEBUG let viewing = UIAction(title: "模拟游客查看中", image: UIImage(systemName: "eye")) { [weak self] _ in self?.simulateViewing() } let confirmed = UIAction(title: "模拟游客主动确认", image: UIImage(systemName: "checkmark.circle")) { [weak self] _ in self?.simulateConfirmed() } let feedback = DroneDeliveryFeedbackKind.allCases.map { kind in UIAction(title: kind.title) { [weak self] _ in self?.simulateFeedback(kind) } } let scenarios: [DroneDeliveryScenario] = [.empty, .completed, .awaitingConfirmation, .viewing, .feedback, .confirmed] let fixtures = scenarios.map { scenario in UIAction(title: scenario.title) { [weak self] _ in guard let self else { return } self.displayedReceipt = nil self.viewModel.applyScenario(scenario) self.applySnapshot(animated: true) } } let menu = UIMenu(title: "本机确认演示,不连接游客", children: [ UIMenu(options: .displayInline, children: [viewing, confirmed]), UIMenu(title: "模拟游客反馈", children: feedback), UIMenu(title: "载入演示状态", children: fixtures) ]) let debug = UIBarButtonItem(image: UIImage(systemName: "slider.horizontal.3"), menu: menu) debug.accessibilityIdentifier = "drone.delivery.review.scenarios" debug.accessibilityLabel = "交付确认演示状态" actions.append(debug) #endif navigationItem.rightBarButtonItems = actions } #if DEBUG private func simulateViewing() { guard let session = viewModel.confirmationSession else { showToast("请先核对整单并展示确认码"); return } displayedReceipt = nil viewModel.receiveConfirmation(.viewing, sessionID: session.id) applySnapshot(animated: true) } private func simulateConfirmed() { guard let session = viewModel.confirmationSession else { showToast("请先核对整单并展示确认码"); return } displayedReceipt = nil viewModel.receiveConfirmation(.viewing, sessionID: session.id) viewModel.setVisitorAcknowledged(true) viewModel.receiveConfirmation(.confirmed, sessionID: session.id) applySnapshot(animated: true) collectionView.setContentOffset(CGPoint(x: 0, y: -collectionView.adjustedContentInset.top), animated: false) } private func simulateFeedback(_ kind: DroneDeliveryFeedbackKind) { guard let session = viewModel.confirmationSession else { showToast("请先核对整单并展示确认码"); return } displayedReceipt = nil viewModel.receiveConfirmation(.viewing, sessionID: session.id) viewModel.receiveConfirmation(.feedback(kind: kind, note: "本机演示反馈,请核对成片清单。"), sessionID: session.id) applySnapshot(animated: true) } #endif private func closePage() { if let navigationController, navigationController.viewControllers.first !== self { navigationController.popViewController(animated: true) } else { dismiss(animated: true) } } @objc private func backTapped() { if displayedReceipt != nil && viewModel.confirmationPhase != .confirmed { displayedReceipt = nil applySnapshot(animated: true) } else { closePage() } } /// 按快照首次出现顺序呈现点位,不以当前作品库重新计算历史确认范围。 private static func groups(for works: [DroneDeliveryWork]) -> [DroneDeliveryWorkGroup] { var order: [String] = [] var names: [String: String] = [:] var values: [String: [DroneDeliveryWork]] = [:] for work in works { if values[work.pointID] == nil { order.append(work.pointID); names[work.pointID] = work.pointName } values[work.pointID, default: []].append(work) } return order.map { DroneDeliveryWorkGroup(pointID: $0, pointName: names[$0] ?? "打卡点", works: values[$0] ?? []) } } private static func dateText(_ date: Date?) -> String { guard let date else { return "—" } let formatter = DateFormatter() formatter.locale = Locale(identifier: "zh_CN") formatter.dateFormat = "yyyy/MM/dd HH:mm:ss" return formatter.string(from: date) } }