431 lines
23 KiB
Swift
431 lines
23 KiB
Swift
import SnapKit
|
||
import UIKit
|
||
|
||
/// 交付 Sheet 只请求完成、查看记录与本地视频预览,跨页面导航由入口统一处理。
|
||
@MainActor
|
||
protocol DroneDeliveryUploadViewControllerDelegate: AnyObject {
|
||
/// 关闭交付流程并刷新入口的本地演示摘要。
|
||
func deliveryUploadViewControllerDidFinish(_ controller: DroneDeliveryUploadViewController)
|
||
/// 进入当前订单的已交付作品记录。
|
||
func deliveryUploadViewControllerDidRequestReview(_ controller: DroneDeliveryUploadViewController)
|
||
/// 预览本地示例视频,保持现有上传状态与勾选。
|
||
func deliveryUploadViewController(_ controller: DroneDeliveryUploadViewController, didRequestPreview video: DroneDeliveryVideo)
|
||
}
|
||
|
||
/// 成片交付的本地演示:选择方式、点位与视频,逐项展示前台上传及结果。
|
||
@MainActor
|
||
final class DroneDeliveryUploadViewController: BaseViewController {
|
||
/// 订单、目标点位、选择及演示上传队列的业务状态来源。
|
||
let viewModel: DroneDeliveryViewModel
|
||
/// 将完成与预览导航交回入口。
|
||
weak var delegate: DroneDeliveryUploadViewControllerDelegate?
|
||
|
||
/// 页面阶段只管理展示导航,不参与上传成功或拍摄次数计算。
|
||
private enum Phase: Equatable { case method, point, picker, queue }
|
||
/// 队列摘要与主体使用独立分区。
|
||
private enum Section: Hashable { case summary, content }
|
||
/// 每一项依靠稳定业务身份更新,选择与进度不改变 Diffable 标识。
|
||
private enum Item: Hashable {
|
||
case nearbyMethod, cloudMethod, point(String), video(String), upload(String), summary, empty
|
||
}
|
||
|
||
private var phase: Phase
|
||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||
private let headerView = DroneDeliveryUploadHeaderView()
|
||
private let footerView = DroneDeliveryUploadFooterView()
|
||
private let uploadDriver = DroneDeliveryDemoUploadDriver()
|
||
private var videosByID: [String: DroneDeliveryVideo] = [:]
|
||
private var uploadItemsByID: [String: DroneDeliveryUploadItem] = [:]
|
||
private var didRequestFinish = false
|
||
|
||
/// 每次从外部进入均先选择交付方式,已有批次在选择云端后恢复。
|
||
init(viewModel: DroneDeliveryViewModel) {
|
||
self.viewModel = viewModel
|
||
phase = .method
|
||
super.init(nibName: nil, bundle: nil)
|
||
modalPresentationStyle = .pageSheet
|
||
}
|
||
|
||
@available(*, unavailable)
|
||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||
|
||
/// 返回前台或结束预览后只刷新本地状态,不自动启动暂停队列。
|
||
override func viewWillAppear(_ animated: Bool) {
|
||
super.viewWillAppear(animated)
|
||
navigationController?.setNavigationBarHidden(true, animated: false)
|
||
viewModel.refresh()
|
||
if dataSource != nil { applySnapshot(animated: false) }
|
||
}
|
||
|
||
override func viewDidAppear(_ animated: Bool) {
|
||
super.viewDidAppear(animated)
|
||
navigationController?.presentationController?.delegate = self
|
||
if navigationController == nil { presentationController?.delegate = self }
|
||
}
|
||
|
||
/// 真正关闭交付 Sheet 时暂停未完成项;全屏预览覆盖页面不改变上传状态。
|
||
override func viewWillDisappear(_ animated: Bool) {
|
||
super.viewWillDisappear(animated)
|
||
if isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true {
|
||
if let coordinator = transitionCoordinator, coordinator.isInteractive {
|
||
coordinator.animate(alongsideTransition: nil) { [weak self] context in
|
||
if !context.isCancelled { self?.pauseForLeaving() }
|
||
}
|
||
} else {
|
||
pauseForLeaving()
|
||
}
|
||
}
|
||
}
|
||
|
||
override func setupNavigationBar() {
|
||
navigationController?.setNavigationBarHidden(true, animated: false)
|
||
}
|
||
|
||
override func setupUI() {
|
||
view.backgroundColor = .white
|
||
collectionView.backgroundColor = .white
|
||
collectionView.alwaysBounceVertical = false
|
||
collectionView.showsVerticalScrollIndicator = false
|
||
collectionView.accessibilityIdentifier = "drone.delivery.upload.list"
|
||
collectionView.delegate = self
|
||
collectionView.register(DroneDeliveryUploadMethodCell.self, forCellWithReuseIdentifier: "method")
|
||
collectionView.register(DroneDeliveryUploadPointCell.self, forCellWithReuseIdentifier: "point")
|
||
collectionView.register(DroneDeliveryUploadVideoCell.self, forCellWithReuseIdentifier: "video")
|
||
collectionView.register(DroneDeliveryUploadQueueCell.self, forCellWithReuseIdentifier: "upload")
|
||
collectionView.register(DroneDeliveryUploadMessageCell.self, forCellWithReuseIdentifier: "message")
|
||
collectionView.register(DroneDeliveryUploadSummaryCell.self, forCellWithReuseIdentifier: "summary")
|
||
[headerView, collectionView, footerView].forEach(view.addSubview)
|
||
configureDataSource()
|
||
configureDebugMenu()
|
||
applySnapshot(animated: false)
|
||
}
|
||
|
||
override func setupConstraints() {
|
||
headerView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide); make.leading.trailing.equalToSuperview() }
|
||
collectionView.snp.makeConstraints { make in
|
||
make.top.equalTo(headerView.snp.bottom)
|
||
make.leading.trailing.equalToSuperview()
|
||
make.bottom.equalTo(footerView.snp.top)
|
||
}
|
||
footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
|
||
}
|
||
|
||
override func bindActions() {
|
||
headerView.onCloseTap = { [weak self] in self?.finish() }
|
||
footerView.onPrimaryTap = { [weak self] in self?.primaryTapped() }
|
||
footerView.onSecondaryTap = { [weak self] in self?.secondaryTapped() }
|
||
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
|
||
name: UIApplication.willResignActiveNotification, object: nil)
|
||
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
|
||
name: UIApplication.didBecomeActiveNotification, object: nil)
|
||
}
|
||
|
||
private func makeLayout() -> UICollectionViewLayout {
|
||
UICollectionViewCompositionalLayout { [weak self] sectionIndex, environment in
|
||
guard let self, let dataSource = self.dataSource else { return nil }
|
||
let sections = dataSource.snapshot().sectionIdentifiers
|
||
guard sections.indices.contains(sectionIndex) else { return nil }
|
||
let section = sections[sectionIndex]
|
||
if section == .summary { return self.listSection(height: 58) }
|
||
if self.phase == .picker, !self.viewModel.availableVideos.isEmpty {
|
||
let width = max(1, (environment.container.effectiveContentSize.width - 54) / 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.56 + 32)),
|
||
repeatingSubitem: item, count: 2
|
||
)
|
||
group.interItemSpacing = .fixed(14)
|
||
let layoutSection = NSCollectionLayoutSection(group: group)
|
||
layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 4, leading: 20, bottom: 6, trailing: 20)
|
||
layoutSection.interGroupSpacing = 14
|
||
return layoutSection
|
||
}
|
||
let height: CGFloat
|
||
switch self.phase {
|
||
case .method: height = 88
|
||
case .point: height = self.viewModel.points.isEmpty ? 180 : 52
|
||
case .picker: height = 180
|
||
case .queue: height = self.viewModel.batch?.items.isEmpty == false ? 82 : 180
|
||
}
|
||
return self.listSection(height: height, spacing: self.phase == .method ? 12 : 0)
|
||
}
|
||
}
|
||
|
||
private func listSection(height: CGFloat, spacing: CGFloat = 0) -> NSCollectionLayoutSection {
|
||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
|
||
widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)
|
||
))
|
||
let group = NSCollectionLayoutGroup.vertical(
|
||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)), subitems: [item]
|
||
)
|
||
let section = NSCollectionLayoutSection(group: group)
|
||
section.contentInsets = NSDirectionalEdgeInsets(top: 4, leading: 20, bottom: 4, trailing: 20)
|
||
section.interGroupSpacing = spacing
|
||
return section
|
||
}
|
||
|
||
private func configureDataSource() {
|
||
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, indexPath, item in
|
||
guard let self else { return nil }
|
||
switch item {
|
||
case .nearbyMethod, .cloudMethod:
|
||
let cell = list.dequeueReusableCell(withReuseIdentifier: "method", for: indexPath) as! DroneDeliveryUploadMethodCell
|
||
if item == .nearbyMethod {
|
||
cell.apply(title: "面对面闪传", detail: "同一 Wi-Fi 扫码接收 · 无需上传", symbol: "wifi",
|
||
identifier: "drone.delivery.upload.method.nearby")
|
||
} else {
|
||
cell.apply(title: "云端上传", detail: "选择打卡点,演示上传成片", symbol: "icloud.and.arrow.up",
|
||
identifier: "drone.delivery.upload.method.cloud")
|
||
}
|
||
return cell
|
||
case .point(let id):
|
||
let cell = list.dequeueReusableCell(withReuseIdentifier: "point", for: indexPath) as! DroneDeliveryUploadPointCell
|
||
if let point = self.viewModel.points.first(where: { $0.id == id }) {
|
||
cell.apply(point: point, selected: self.viewModel.selectedPointID == id, locked: self.viewModel.isUploadLocked)
|
||
}
|
||
return cell
|
||
case .video(let id):
|
||
let cell = list.dequeueReusableCell(withReuseIdentifier: "video", for: indexPath) as! DroneDeliveryUploadVideoCell
|
||
if let video = self.videosByID[id] {
|
||
cell.apply(video: video, selected: self.viewModel.selectedVideoIDs.contains(id))
|
||
cell.onSelectionTap = { [weak self] in
|
||
guard let self else { return }
|
||
self.viewModel.toggleVideo(id: id)
|
||
self.applySnapshot(animated: true)
|
||
}
|
||
cell.onPreviewTap = { [weak self] in
|
||
guard let self else { return }
|
||
self.delegate?.deliveryUploadViewController(self, didRequestPreview: video)
|
||
}
|
||
}
|
||
return cell
|
||
case .upload(let id):
|
||
let cell = list.dequeueReusableCell(withReuseIdentifier: "upload", for: indexPath) as! DroneDeliveryUploadQueueCell
|
||
if let item = self.uploadItemsByID[id] { cell.apply(item: item) }
|
||
return cell
|
||
case .summary:
|
||
let cell = list.dequeueReusableCell(withReuseIdentifier: "summary", for: indexPath) as! DroneDeliveryUploadSummaryCell
|
||
cell.apply(completed: self.viewModel.uploadedCount, detail: self.queueSummary)
|
||
cell.onReviewTap = { [weak self] in
|
||
guard let self else { return }
|
||
self.pauseForLeaving()
|
||
self.delegate?.deliveryUploadViewControllerDidRequestReview(self)
|
||
}
|
||
return cell
|
||
case .empty:
|
||
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: indexPath) as! DroneDeliveryUploadMessageCell
|
||
if self.phase == .point {
|
||
cell.apply(title: "暂无可交付点位", detail: "当前订单没有可用点位,请稍后重试。", symbol: "mappin.slash.circle")
|
||
} else if self.phase == .picker {
|
||
cell.apply(title: "暂无可选演示视频", detail: "本点位的示例视频已交付,可返回选择其他点位。", symbol: "video.slash")
|
||
} else {
|
||
cell.apply(title: "暂无上传队列", detail: "请选择视频后开始演示上传。", symbol: "icloud.and.arrow.up")
|
||
}
|
||
return cell
|
||
}
|
||
}
|
||
}
|
||
|
||
private var queueSummary: String {
|
||
switch viewModel.uploadPhase {
|
||
case .idle: "请选择视频后开始演示上传"
|
||
case .uploading: "\(viewModel.pendingCount)个上传中 · 仅在本地演示"
|
||
case .paused: "上传已暂停,请手动继续"
|
||
case .partialFailure: "\(viewModel.failedCount)个上传失败"
|
||
case .completed: "全部演示上传成功 · 未向游客发送"
|
||
}
|
||
}
|
||
|
||
private func applySnapshot(animated: Bool) {
|
||
guard isViewLoaded, dataSource != nil else { return }
|
||
videosByID = Dictionary(uniqueKeysWithValues: viewModel.availableVideos.map { ($0.id, $0) })
|
||
let uploadItems = viewModel.batch?.items ?? []
|
||
uploadItemsByID = Dictionary(uniqueKeysWithValues: uploadItems.map { ($0.id, $0) })
|
||
let oldItems = Set(dataSource.snapshot().itemIdentifiers)
|
||
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
||
if phase == .queue {
|
||
snapshot.appendSections([.summary])
|
||
snapshot.appendItems([.summary], toSection: .summary)
|
||
}
|
||
snapshot.appendSections([.content])
|
||
let items: [Item]
|
||
switch phase {
|
||
case .method: items = [.nearbyMethod, .cloudMethod]
|
||
case .point: items = viewModel.points.isEmpty ? [.empty] : viewModel.points.map { .point($0.id) }
|
||
case .picker: items = viewModel.availableVideos.isEmpty ? [.empty] : viewModel.availableVideos.map { .video($0.id) }
|
||
case .queue: items = uploadItems.isEmpty ? [.empty] : uploadItems.map { .upload($0.id) }
|
||
}
|
||
snapshot.appendItems(items, toSection: .content)
|
||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { oldItems.contains($0) })
|
||
applyHeaderAndFooter()
|
||
dataSource.apply(snapshot, animatingDifferences: animated)
|
||
collectionView.collectionViewLayout.invalidateLayout()
|
||
}
|
||
|
||
private func applyHeaderAndFooter() {
|
||
let customer = viewModel.order?.customerName ?? "订单信息暂不可用"
|
||
let pointName = viewModel.batch?.pointName ?? viewModel.selectedPoint?.name
|
||
let context = pointName.map { "\(customer) · \($0)" } ?? customer
|
||
switch phase {
|
||
case .method:
|
||
headerView.apply(title: "交付成片", customer: customer, detail: "请选择本次交付方式")
|
||
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批演示交付多个作品,不影响拍摄次数", secondaryTitle: nil)
|
||
case .point:
|
||
headerView.apply(title: "选择打卡点", customer: customer, detail: "云端上传 · 请选择本批成片对应的打卡点")
|
||
footerView.apply(primaryTitle: "去演示相册选视频", enabled: viewModel.selectedPoint != nil && !viewModel.isUploadLocked,
|
||
identifier: "drone.delivery.upload.openPicker", detail: "可选择一个或多个视频,上传与交付仅在本地演示", secondaryTitle: "返回交付方式")
|
||
case .picker:
|
||
headerView.apply(title: "选择视频", customer: context, detail: "演示相册 · 不读取手机文件")
|
||
footerView.apply(primaryTitle: "开始演示上传(\(viewModel.selectedVideoIDs.count))", enabled: viewModel.canStartUpload,
|
||
identifier: "drone.delivery.upload.start", detail: "选择后体验演示上传,不执行真实云端上传", secondaryTitle: "返回选择点位")
|
||
case .queue:
|
||
headerView.apply(title: "成片上传", customer: context, detail: "本地演示 · 不执行真实上传或游客发送")
|
||
switch viewModel.uploadPhase {
|
||
case .idle:
|
||
footerView.apply(primaryTitle: "返回选择视频", enabled: true, identifier: "drone.delivery.upload.pickMore", detail: "", secondaryTitle: "完成")
|
||
case .uploading:
|
||
footerView.apply(primaryTitle: "正在演示上传…", enabled: false, identifier: "drone.delivery.upload.start",
|
||
detail: "请保持页面开启,演示成功后更新本地交付记录", secondaryTitle: nil)
|
||
case .paused:
|
||
footerView.apply(primaryTitle: "继续上传", enabled: true, identifier: "drone.delivery.upload.continue",
|
||
detail: "已成功作品会保留;继续时只处理未完成项", secondaryTitle: "完成")
|
||
case .partialFailure:
|
||
footerView.apply(primaryTitle: "重试失败视频(\(viewModel.failedCount))", enabled: viewModel.failedCount > 0,
|
||
identifier: "drone.delivery.upload.retry", detail: "演示交付成功的作品不会重复上传", secondaryTitle: "完成")
|
||
case .completed:
|
||
footerView.apply(primaryTitle: "继续上传成片", enabled: true, identifier: "drone.delivery.upload.pickMore",
|
||
detail: "可分批演示上传,不扣减拍摄次数", secondaryTitle: "完成")
|
||
}
|
||
}
|
||
}
|
||
|
||
private func showPhase(_ phase: Phase) {
|
||
self.phase = phase
|
||
applySnapshot(animated: true)
|
||
collectionView.setContentOffset(.zero, animated: false)
|
||
let sheet = navigationController?.sheetPresentationController ?? sheetPresentationController
|
||
let detent: UISheetPresentationController.Detent.Identifier = phase == .picker || (phase == .queue && viewModel.totalUploadCount > 3) ? .large : .medium
|
||
sheet?.animateChanges { sheet?.selectedDetentIdentifier = detent }
|
||
}
|
||
|
||
private func primaryTapped() {
|
||
switch phase {
|
||
case .method: break
|
||
case .point: if viewModel.selectedPoint != nil { showPhase(.picker) }
|
||
case .picker:
|
||
if viewModel.startUpload() { showPhase(.queue); startDemoUpload() }
|
||
case .queue:
|
||
switch viewModel.uploadPhase {
|
||
case .paused:
|
||
if viewModel.continueUpload() { applySnapshot(animated: true); startDemoUpload() }
|
||
case .partialFailure:
|
||
if viewModel.retryFailedUploads() { applySnapshot(animated: true); startDemoUpload() }
|
||
case .completed, .idle:
|
||
viewModel.clearUploadBatch()
|
||
showPhase(viewModel.selectedPoint == nil ? .point : .picker)
|
||
case .uploading: break
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 演示入口也使用同一局域网页面,但必须显式选择本机视频才会开放传输。
|
||
private func openNearbyFlow() {
|
||
let nearby = DroneDockNearbyTransferViewController(customerTitle: "面对面交付")
|
||
if let navigation = navigationController {
|
||
nearby.onClose = { [weak navigation] in navigation?.popViewController(animated: true) }
|
||
navigation.sheetPresentationController?.animateChanges {
|
||
navigation.sheetPresentationController?.selectedDetentIdentifier = .large
|
||
}
|
||
navigation.setNavigationBarHidden(false, animated: true)
|
||
navigation.pushViewController(nearby, animated: true)
|
||
} else {
|
||
let navigation = UINavigationController(rootViewController: nearby)
|
||
navigation.modalPresentationStyle = .pageSheet
|
||
navigation.sheetPresentationController?.detents = [.large()]
|
||
nearby.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
|
||
present(navigation, animated: true)
|
||
}
|
||
}
|
||
|
||
/// 选择云端仅恢复原队列或进入选点,不清除批次,也不自动继续上传。
|
||
private func openCloudFlow() {
|
||
showPhase(viewModel.batch == nil ? .point : .queue)
|
||
}
|
||
|
||
private func secondaryTapped() {
|
||
switch phase {
|
||
case .method: break
|
||
case .point: showPhase(.method)
|
||
case .picker: showPhase(.point)
|
||
case .queue: finish()
|
||
}
|
||
}
|
||
|
||
private func startDemoUpload() {
|
||
uploadDriver.start(viewModel: viewModel) { [weak self] in self?.applySnapshot(animated: true) }
|
||
}
|
||
|
||
private func pauseForLeaving() {
|
||
uploadDriver.stop()
|
||
guard phase == .queue else { return }
|
||
viewModel.pauseUpload(reason: .leavingPage)
|
||
}
|
||
|
||
private func finish() {
|
||
guard !didRequestFinish else { return }
|
||
didRequestFinish = true
|
||
pauseForLeaving()
|
||
if let delegate { delegate.deliveryUploadViewControllerDidFinish(self) }
|
||
else if let navigationController { navigationController.dismiss(animated: true) }
|
||
else { dismiss(animated: true) }
|
||
}
|
||
|
||
private func configureDebugMenu() {
|
||
#if DEBUG
|
||
let actions = DroneDeliveryScenario.allCases.map { scenario in
|
||
UIAction(title: scenario.title) { [weak self] _ in
|
||
guard let self else { return }
|
||
self.uploadDriver.stop()
|
||
self.viewModel.applyScenario(scenario)
|
||
self.showPhase(self.viewModel.batch == nil ? .method : .queue)
|
||
}
|
||
}
|
||
headerView.setDebugMenu(UIMenu(title: "本地交付演示状态", children: actions))
|
||
#endif
|
||
}
|
||
|
||
@objc private func applicationWillResignActive() {
|
||
uploadDriver.stop()
|
||
viewModel.pauseUpload(reason: .background)
|
||
if isViewLoaded { applySnapshot(animated: false) }
|
||
}
|
||
|
||
@objc private func applicationDidBecomeActive() {
|
||
viewModel.refresh()
|
||
if isViewLoaded { applySnapshot(animated: false) }
|
||
}
|
||
}
|
||
|
||
extension DroneDeliveryUploadViewController: UICollectionViewDelegate {
|
||
/// 卡片与点位整行选择,队列行预览不影响当前批次。
|
||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
||
switch item {
|
||
case .nearbyMethod: openNearbyFlow()
|
||
case .cloudMethod: openCloudFlow()
|
||
case .point(let id): viewModel.selectPoint(id: id); applySnapshot(animated: true)
|
||
case .upload(let id):
|
||
if let item = uploadItemsByID[id] { delegate?.deliveryUploadViewController(self, didRequestPreview: item.video) }
|
||
default: break
|
||
}
|
||
}
|
||
}
|
||
|
||
extension DroneDeliveryUploadViewController: UIAdaptivePresentationControllerDelegate {
|
||
/// 手势关闭 Sheet 后仍暂停未完成上传并刷新原入口。
|
||
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() }
|
||
}
|