feat(drone-dock): 搭建素材库预览选择与下载演示

This commit is contained in:
2026-10-23 17:11:54 +08:00
parent 7834b8bcbc
commit 837623ee7f
24 changed files with 3214 additions and 5 deletions
@@ -0,0 +1,491 @@
import SnapKit
import UIKit
/// 素材库只提出导航请求,由机巢入口协调预览与尚未实现的交付流程。
@MainActor
protocol DroneMaterialsViewControllerDelegate: AnyObject {
/// 预览单项素材,保持素材库现有选择与下载批次。
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestPreview material: DroneMaterial)
/// 请求当前拍摄记录的交付占位入口。
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord)
}
/// 订单素材库:按拍摄记录分组,支持点位筛选、独立预览选择与前台演示下载。
@MainActor
final class DroneMaterialsViewController: BaseViewController {
/// 素材展示、选择与批次状态的来源。
let viewModel: DroneMaterialsViewModel
/// 将跨页面操作交给机巢导航入口。
weak var delegate: DroneMaterialsViewControllerDelegate?
/// 订单、筛选和拍摄记录采用稳定分区标识,刷新时保留当前滚动位置。
private enum Section: Hashable {
case order, filters, summary, record(String), message
}
/// 网格和辅助单元的稳定身份,不将可变选择状态纳入 Diffable 标识。
private enum Item: Hashable {
case order, filter(String?), context, summary, material(String), message
}
/// 底部主按钮当前对应的操作;启用规则由 ViewModel 提供。
private enum FooterAction {
case download, resume, retry, selectMore, permission, none
}
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private let footerView = DroneMaterialsFooterView()
private let refreshControl = UIRefreshControl()
private let transferDriver = DroneMaterialDemoTransferDriver()
private var footerAction: FooterAction = .download
private var recordsByID: [String: DroneMaterialRecord] = [:]
private var materialsByID: [String: DroneMaterial] = [:]
private var originalInteractivePopEnabled: Bool?
private var hasRunningDownload: Bool {
switch viewModel.downloadPhase {
case .downloading, .awaitingSave, .saving: true
default: false
}
}
/// 使用入口共享的素材状态,支持订单全量入口与当前任务点位入口。
init(viewModel: DroneMaterialsViewModel) {
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)
viewModel.refresh()
if dataSource != nil { applySnapshot(animated: false) }
}
/// 真正返回上层页面时停止未完成项;全屏预览覆盖素材页不触发离页处理。
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true {
transferDriver.stop()
viewModel.leavePage()
restoreInteractivePopGesture()
}
}
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.materials.back"
back.accessibilityLabel = "返回"
navigationItem.leftBarButtonItem = back
let refresh = UIBarButtonItem(title: "刷新", style: .plain,
target: self, action: #selector(refreshTapped))
refresh.accessibilityIdentifier = "drone.materials.refresh"
refresh.accessibilityLabel = "刷新素材状态"
#if DEBUG
let scenarios = DroneMaterialsScenario.allCases.map { scenario in
UIAction(title: scenario.title) { [weak self] _ in
guard let self else { return }
self.transferDriver.stop()
self.viewModel.applyScenario(scenario)
self.applySnapshot(animated: true)
}
}
let advance = UIAction(title: "模拟下一项下载回执", image: UIImage(systemName: "arrow.forward.circle")) { [weak self] _ in
guard let self else { return }
self.transferDriver.stop()
self.viewModel.advanceDemoDownload()
self.applySnapshot(animated: true)
}
let allowPermission = UIAction(title: "模拟相册权限恢复", image: UIImage(systemName: "lock.open")) { [weak self] _ in
guard let self, self.viewModel.photoPermission != .allowed else { return }
self.transferDriver.stop()
self.viewModel.setPhotoPermission(.allowed)
self.applySnapshot(animated: true)
self.showToast("演示权限已恢复,请手动继续下载")
}
let menu = UIMenu(title: "素材库本地演示状态", children: [
UIMenu(options: .displayInline, children: scenarios),
UIMenu(options: .displayInline, children: [advance, allowPermission])
])
let debug = UIBarButtonItem(image: UIImage(systemName: "slider.horizontal.3"), menu: menu)
debug.accessibilityIdentifier = "drone.materials.scenarios"
debug.accessibilityLabel = "素材库演示状态"
navigationItem.rightBarButtonItems = [refresh, debug]
#else
navigationItem.rightBarButtonItem = refresh
#endif
}
override func setupUI() {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.showsVerticalScrollIndicator = false
collectionView.accessibilityIdentifier = "drone.materials.list"
collectionView.delegate = self
collectionView.register(DroneMaterialOrderCell.self, forCellWithReuseIdentifier: "order")
collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "filter")
collectionView.register(DroneMaterialPointContextCell.self, forCellWithReuseIdentifier: "context")
collectionView.register(DroneMaterialSelectionCell.self, forCellWithReuseIdentifier: "summary")
collectionView.register(DroneMaterialCell.self, forCellWithReuseIdentifier: "material")
collectionView.register(DroneMaterialMessageCell.self, forCellWithReuseIdentifier: "message")
collectionView.register(DroneMaterialRecordHeaderView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "recordHeader")
collectionView.register(DroneMaterialSeparatorView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
withReuseIdentifier: "separator")
refreshControl.tintColor = DroneDockStyle.primary
collectionView.refreshControl = refreshControl
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() {
refreshControl.addTarget(self, action: #selector(refreshTapped), for: .valueChanged)
footerView.onPrimaryTap = { [weak self] in self?.performFooterAction() }
footerView.onSecondaryTap = { [weak self] in
guard let self else { return }
self.viewModel.clearBatch()
self.applySnapshot(animated: true)
}
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]
switch section {
case .record:
let width = (environment.container.effectiveContentSize.width - 44) / 2
let height = width * 0.57 + 51
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1)
))
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)),
repeatingSubitem: item, count: 2
)
group.interItemSpacing = .fixed(12)
let layoutSection = NSCollectionLayoutSection(group: group)
layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 20, trailing: 16)
layoutSection.interGroupSpacing = 12
layoutSection.boundarySupplementaryItems = [
NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(80)),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top
),
NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(1)),
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom
)
]
return layoutSection
case .order:
return self.singleColumnSection(height: .estimated(116))
case .filters:
if self.viewModel.pointID != nil { return self.singleColumnSection(height: .absolute(46)) }
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)
))
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: NSCollectionLayoutSize(widthDimension: .absolute(90), heightDimension: .absolute(36)),
subitems: [item]
)
let layoutSection = NSCollectionLayoutSection(group: group)
layoutSection.orthogonalScrollingBehavior = .continuous
layoutSection.interGroupSpacing = 9
layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 16, bottom: 8, trailing: 16)
return layoutSection
case .summary:
return self.singleColumnSection(height: .absolute(46))
case .message:
return self.singleColumnSection(height: .absolute(250))
}
}
}
private func singleColumnSection(height: NSCollectionLayoutDimension) -> NSCollectionLayoutSection {
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1), heightDimension: height
))
let group = NSCollectionLayoutGroup.vertical(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height), subitems: [item]
)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
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 .order:
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: indexPath) as! DroneMaterialOrderCell
cell.apply(order: self.viewModel.order)
return cell
case .filter(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "filter", for: indexPath) as! DroneMaterialFilterCell
if let filter = self.viewModel.filters.first(where: { $0.id == id }) {
cell.apply(title: filter.title, id: filter.id,
selected: filter.id == self.viewModel.selectedFilterID, locked: self.viewModel.isSelectionLocked)
}
return cell
case .context:
let cell = list.dequeueReusableCell(withReuseIdentifier: "context", for: indexPath) as! DroneMaterialPointContextCell
let title = self.viewModel.filters.first(where: { $0.id == self.viewModel.pointID })?.title
?? self.viewModel.sections.first?.pointName ?? "当前拍摄点"
cell.apply(title: title)
return cell
case .summary:
let cell = list.dequeueReusableCell(withReuseIdentifier: "summary", for: indexPath) as! DroneMaterialSelectionCell
cell.apply(recordCount: self.viewModel.sections.count, allSelected: self.viewModel.isAllSelected,
enabled: !self.viewModel.isSelectionLocked && !self.viewModel.downloadableIDs.isEmpty)
cell.onSelectAllTap = { [weak self] in
guard let self else { return }
self.viewModel.selectAll()
self.applySnapshot(animated: true)
}
return cell
case .material(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "material", for: indexPath) as! DroneMaterialCell
if let material = self.materialsByID[id] {
let completed: Bool
if case .completed = material.downloadState { completed = true } else { completed = false }
cell.apply(material: material, selected: self.viewModel.selectedIDs.contains(id),
selectionEnabled: !self.viewModel.isSelectionLocked && self.viewModel.downloadableIDs.contains(id),
completed: completed)
cell.onPreviewTap = { [weak self] in
guard let self, let current = self.viewModel.material(id: id), current.canPreview else { return }
self.delegate?.materialsViewController(self, didRequestPreview: current)
}
cell.onSelectionTap = { [weak self] in
guard let self else { return }
self.viewModel.toggleSelection(id: id)
self.applySnapshot(animated: true)
}
}
return cell
case .message:
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: indexPath) as! DroneMaterialMessageCell
switch self.viewModel.listState {
case .loading:
cell.apply(title: "正在获取素材", detail: "请稍候", symbol: "arrow.triangle.2.circlepath")
case .failed(let message):
cell.apply(title: "素材加载失败", detail: "\(message)\n请下拉或点击右上角刷新", symbol: "wifi.exclamationmark")
case .loaded:
cell.apply(title: "暂无拍摄素材", detail: "拍摄完成后的素材会显示在这里", symbol: "photo.on.rectangle.angled")
}
return cell
}
}
dataSource.supplementaryViewProvider = { [weak self] list, kind, indexPath in
guard let self else { return nil }
if kind == UICollectionView.elementKindSectionFooter {
return list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "separator", for: indexPath)
}
let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "recordHeader", for: indexPath) as! DroneMaterialRecordHeaderView
self.applyHeader(header, sectionIndex: indexPath.section)
return header
}
}
private func applySnapshot(animated: Bool) {
guard isViewLoaded, dataSource != nil else { return }
let records = viewModel.sections
recordsByID = Dictionary(uniqueKeysWithValues: records.map { ($0.id, $0) })
materialsByID = Dictionary(uniqueKeysWithValues: records.flatMap(\.materials).map { ($0.id, $0) })
let previous = dataSource.snapshot()
let existing = Set(previous.itemIdentifiers)
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.order, .filters, .summary])
snapshot.appendItems([.order], toSection: .order)
snapshot.appendItems(viewModel.pointID == nil ? viewModel.filters.map { .filter($0.id) } : [.context], toSection: .filters)
snapshot.appendItems([.summary], toSection: .summary)
switch viewModel.listState {
case .loaded where !records.isEmpty:
for record in records {
let section = Section.record(record.id)
snapshot.appendSections([section])
snapshot.appendItems(record.materials.map { .material($0.id) }, toSection: section)
}
default:
snapshot.appendSections([.message])
snapshot.appendItems([.message], toSection: .message)
}
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
applyFooter()
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? DroneMaterialRecordHeaderView else { continue }
self.applyHeader(header, sectionIndex: path.section)
}
}
if previous.sectionIdentifiers != snapshot.sectionIdentifiers { collectionView.collectionViewLayout.invalidateLayout() }
updateInteractivePopGesture()
}
private func applyHeader(_ header: DroneMaterialRecordHeaderView, sectionIndex: Int) {
let sections = dataSource.snapshot().sectionIdentifiers
guard sections.indices.contains(sectionIndex), case .record(let id) = sections[sectionIndex], let record = recordsByID[id] else { return }
header.apply(record: record)
header.onDeliveryTap = { [weak self] in
guard let self, let current = self.recordsByID[id] else { return }
self.delegate?.materialsViewController(self, didRequestDelivery: current)
}
}
private func applyFooter() {
if viewModel.photoPermission != .allowed {
footerAction = .permission
footerView.apply(title: "无法保存到手机相册", detail: "演示相册权限未开启,恢复后请手动继续。",
primaryTitle: "检查相册权限", primarySymbol: "lock", enabled: true,
identifier: "drone.materials.permission", progress: nil, tone: .orange)
return
}
switch viewModel.downloadPhase {
case .idle:
footerAction = .download
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "仅可选择已上传素材 · 本次为本地演示",
primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line", enabled: viewModel.canStartDownload,
identifier: "drone.materials.download", progress: nil)
case .downloading, .awaitingSave, .saving:
footerAction = .none
footerView.apply(title: "本次下载\(viewModel.batchTotalCount)项 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
detail: "请保持本页开启,下载期间不可更改选择",
primaryTitle: viewModel.downloadButtonTitle, primarySymbol: "arrow.triangle.2.circlepath", enabled: false,
identifier: "drone.materials.download", progress: viewModel.batchProgress, tone: .blue)
case .paused:
footerAction = .resume
footerView.apply(title: "下载已暂停 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
detail: "已完成项会保留;继续时仅处理未完成文件。",
primaryTitle: "继续下载", primarySymbol: "play.fill", enabled: true,
identifier: "drone.materials.continue", progress: viewModel.batchProgress, tone: .orange)
case .partialFailure:
footerAction = .retry
footerView.apply(title: "部分素材下载失败", detail: "演示完成\(viewModel.completedCount)项 · 失败\(viewModel.failedCount)项,重试仅处理失败项",
primaryTitle: "重试失败素材(\(viewModel.failedCount))", primarySymbol: "arrow.clockwise", enabled: viewModel.failedCount > 0,
identifier: "drone.materials.retry", progress: nil, secondaryTitle: "选择其他素材", tone: .orange)
case .completed:
footerAction = .selectMore
footerView.apply(title: "本次素材演示完成", detail: "\(viewModel.completedCount)项演示完成,未写入系统相册",
primaryTitle: "继续选择素材", primarySymbol: "checkmark.circle", enabled: true,
identifier: "drone.materials.continueSelecting", progress: nil, tone: .green)
}
}
private func performFooterAction() {
var shouldStartDriver = false
switch footerAction {
case .download:
shouldStartDriver = viewModel.startDownload()
case .resume:
shouldStartDriver = viewModel.continueDownload()
case .retry:
shouldStartDriver = viewModel.retryFailed()
case .selectMore:
viewModel.clearBatch()
case .permission:
showAlert(title: "相册权限演示", message: "当前为本地演示,不读取或修改系统相册权限。可在右上角演示状态中选择“模拟相册权限恢复”,再手动继续下载。")
case .none:
return
}
applySnapshot(animated: true)
if shouldStartDriver { startDemoTransfer() }
}
private func startDemoTransfer() {
guard let batch = viewModel.batch, !batch.isPaused else { return }
transferDriver.start(viewModel: viewModel) { [weak self] in self?.applySnapshot(animated: true) }
}
private func updateInteractivePopGesture() {
guard let gesture = navigationController?.interactivePopGestureRecognizer else { return }
if hasRunningDownload {
if originalInteractivePopEnabled == nil { originalInteractivePopEnabled = gesture.isEnabled }
gesture.isEnabled = false
} else {
restoreInteractivePopGesture()
}
}
private func restoreInteractivePopGesture() {
guard let originalInteractivePopEnabled else { return }
navigationController?.interactivePopGestureRecognizer?.isEnabled = originalInteractivePopEnabled
self.originalInteractivePopEnabled = nil
}
private func leaveMaterialsPage() {
transferDriver.stop()
viewModel.leavePage()
restoreInteractivePopGesture()
if let navigationController, navigationController.viewControllers.first !== self {
navigationController.popViewController(animated: true)
} else {
dismiss(animated: true)
}
}
@objc private func backTapped() {
guard hasRunningDownload else { leaveMaterialsPage(); return }
let alert = UIAlertController(title: "素材仍在下载",
message: "离开将暂停未完成的下载,已完成项会保留。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "继续下载", style: .cancel))
alert.addAction(UIAlertAction(title: "离开并暂停", style: .default) { [weak self] _ in self?.leaveMaterialsPage() })
present(alert, animated: true)
}
@objc private func refreshTapped() {
viewModel.refresh()
applySnapshot(animated: true)
refreshControl.endRefreshing()
}
@objc private func applicationWillResignActive() {
transferDriver.stop()
viewModel.pauseDownloads(reason: .background)
if isViewLoaded { applySnapshot(animated: false) }
}
@objc private func applicationDidBecomeActive() {
viewModel.refresh()
if isViewLoaded { applySnapshot(animated: false) }
}
}
extension DroneMaterialsViewController: UICollectionViewDelegate {
/// 点位标签整项可点,素材的预览与选择交由各自按钮处理。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath), case .filter(let id) = item else { return }
viewModel.selectFilter(id: id)
applySnapshot(animated: true)
}
}