feat: 完善机巢模拟调试与素材交付交互

增加禁飞期间的设备指令拦截及本地模拟拍摄流程;适配订单素材库和景区空境库,完善素材筛选、预览与下载;订单交付入口改为方式选择弹窗并复用云端上传。补充单元测试、接口记录和模拟器截图。
This commit is contained in:
2026-10-30 09:59:11 +08:00
parent e827bf8725
commit b95b251de1
100 changed files with 7256 additions and 500 deletions
@@ -8,6 +8,9 @@ import UIKit
final class DroneDockMaterialsViewController: BaseViewController {
/// 保存当前订单摘要、点位和任务的真实状态。
let viewModel: DroneDockMaterialsViewModel
private let thumbnailProvider: ((Int, Int, Bool) -> UIImage?)?
private let mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)?
private let footerView = DroneMaterialsFooterView()
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
/// 元数据与媒体分区独立,任务没有素材时也保留其状态。
@@ -28,8 +31,12 @@ final class DroneDockMaterialsViewController: BaseViewController {
/// 注入冻结订单范围的只读素材服务。
init(viewModel: DroneDockMaterialsViewModel,
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil) {
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil,
thumbnailProvider: ((Int, Int, Bool) -> UIImage?)? = nil,
mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? = nil) {
self.viewModel = viewModel
self.thumbnailProvider = thumbnailProvider
self.mediaPreviewControllerFactory = mediaPreviewControllerFactory
self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
@@ -43,7 +50,8 @@ final class DroneDockMaterialsViewController: BaseViewController {
override func setupNavigationBar() {
title = "订单素材库"
navigationItem.backButtonDisplayMode = .minimal
let refresh = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshTapped))
let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTapped))
refresh.accessibilityLabel = "刷新素材状态"
refresh.accessibilityIdentifier = "drone.materials.remote.refresh"
navigationItem.rightBarButtonItem = refresh
}
@@ -52,9 +60,16 @@ final class DroneDockMaterialsViewController: BaseViewController {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.showsVerticalScrollIndicator = false
collectionView.accessibilityIdentifier = "drone.materials.remote.list"
collectionView.delegate = self
collectionView.register(DroneDockMaterialTextCell.self, forCellWithReuseIdentifier: "text")
collectionView.register(DroneDockMaterialOrderCell.self, forCellWithReuseIdentifier: "order")
collectionView.register(DroneMaterialSelectionCell.self, forCellWithReuseIdentifier: "summary")
collectionView.register(DroneDockMaterialRecordCell.self, forCellWithReuseIdentifier: "record")
collectionView.register(DroneDockMaterialMessageCell.self, forCellWithReuseIdentifier: "message")
collectionView.register(DroneMaterialSeparatorView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
withReuseIdentifier: "separator")
collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "filter")
collectionView.register(DroneDockMaterialMediaCell.self, forCellWithReuseIdentifier: "media")
let refresh = UIRefreshControl()
@@ -62,6 +77,9 @@ final class DroneDockMaterialsViewController: BaseViewController {
refresh.addTarget(self, action: #selector(refreshTapped), for: .valueChanged)
collectionView.refreshControl = refresh
view.addSubview(collectionView)
view.addSubview(footerView)
footerView.accessibilityIdentifier = "drone.materials.remote.footer"
footerView.onPrimaryTap = { [weak self] in self?.downloadTapped() }
configureDataSource()
applySnapshot(animated: false)
}
@@ -69,8 +87,10 @@ final class DroneDockMaterialsViewController: BaseViewController {
override func setupConstraints() {
collectionView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.bottom.equalToSuperview()
make.leading.trailing.equalToSuperview()
make.bottom.equalTo(footerView.snp.top)
}
footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
}
override func viewWillAppear(_ animated: Bool) {
@@ -101,60 +121,81 @@ final class DroneDockMaterialsViewController: BaseViewController {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] collection, path, item in
guard let self else { return nil }
switch item {
case .order:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DroneDockMaterialOrderCell
if let order = self.viewModel.detail?.order { cell.apply(order: order) }
return cell
case .summary:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "summary", for: path) as! DroneMaterialSelectionCell
cell.apply(recordCount: self.viewModel.total ?? 0,
allSelected: self.viewModel.allDownloadableSelected,
enabled: self.operation == nil && !self.viewModel.selectableMaterialIDs.isEmpty)
cell.accessibilityIdentifier = "drone.materials.remote.summary"
cell.onSelectAllTap = { [weak self] in
guard let self, self.operation == nil else { return }
self.viewModel.toggleSelectAll()
self.applySnapshot(animated: false)
}
return cell
case .filter(let id):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "filter", for: path) as! DroneMaterialFilterCell
let title = id.flatMap { id in self.viewModel.spots.first { $0.id == id } }.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位"
cell.apply(title: title, id: id.map(String.init), selected: id == self.displayedSpotID, locked: self.viewModel.detail == nil)
return cell
case .task(let taskID):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "record", for: path) as! DroneDockMaterialRecordCell
if let task = self.task(taskID) {
cell.apply(task: task, canDeliver: self.operation == nil && self.viewModel.detail?.order.canUploadFilm == true) { [weak self] in
self?.openDelivery(taskID: taskID)
}
}
return cell
case .file(let taskID, let fileID):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell
if let file = self.task(taskID)?.materials.first(where: { $0.id == fileID }) {
cell.apply(file: file, taskID: taskID)
let identity = DroneDockMaterialSelectionID(taskID: taskID, fileID: fileID)
cell.apply(file: file, taskID: taskID,
selected: self.viewModel.selectedMaterialIDs.contains(identity),
selectionEnabled: self.operation == nil && self.viewModel.selectableMaterialIDs.contains(identity),
localImage: self.thumbnailProvider?(taskID, fileID, false),
allowsRemoteImage: self.thumbnailProvider == nil,
preview: { [weak self] in self?.previewFile(taskID: taskID, fileID: fileID) },
select: { [weak self] in
guard let self, self.operation == nil else { return }
self.viewModel.toggleSelection(taskID: taskID, fileID: fileID)
self.applySnapshot(animated: false)
})
}
return cell
case .film(let taskID, _):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell
if let film = self.task(taskID)?.film { cell.apply(film: film, taskID: taskID) }
if let film = self.task(taskID)?.film {
cell.apply(film: film, taskID: taskID, localImage: self.thumbnailProvider?(taskID, film.id, true),
allowsRemoteImage: self.thumbnailProvider == nil) { [weak self] in self?.previewFilm(taskID: taskID) }
}
return cell
default:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! DroneDockMaterialTextCell
self.configureText(cell, item: item)
case .message:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DroneDockMaterialMessageCell
self.configureMessage(cell)
return cell
}
}
dataSource.supplementaryViewProvider = { collection, kind, path in
collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "separator", for: path)
}
}
private func configureText(_ cell: DroneDockMaterialTextCell, item: Item) {
switch item {
case .order:
guard let order = viewModel.detail?.order else { return }
cell.apply(title: order.touristTitle, body: "\(order.orderNumberText)\n\(order.packageTitle) · \(order.statusTitle)\n\(order.progressTitle)", identifier: "drone.materials.remote.order")
case .summary:
let text = viewModel.total.map { "\($0) 条任务记录 · 最新在前" } ?? "任务记录"
cell.apply(title: text, body: nil, identifier: "drone.materials.remote.summary", compact: true)
case .task(let id):
guard let task = task(id) else { return }
let number = task.sequence.map { "任务 \($0)" } ?? "任务 \(id)"
let title = "\(number) · \(Self.usable(task.spotName, fallback: "点位 \(task.spotID)"))"
var lines = ["\(Self.usable(task.airLineName, fallback: "航线待确认")) · \(Self.flightTitle(task.flightStatus))",
Self.usable(task.createdAt, fallback: "时间待确认")]
if task.materials.isEmpty { lines.append("暂无原素材") }
if task.film == nil { lines.append("暂无视频成片") }
let canDeliver = operation == nil && viewModel.detail?.order.canUploadFilm == true
cell.apply(title: title, body: lines.joined(separator: "\n"), identifier: "drone.materials.remote.task.\(id)",
button: canDeliver ? (task.film == nil ? "交付成片" : "替换成片") : nil,
actionID: "drone.materials.remote.delivery.\(id)") { [weak self] in self?.openDelivery(taskID: id) }
case .message:
if operation != nil || viewModel.isLoading || viewModel.isLoadingTasks {
cell.apply(title: viewModel.detail == nil ? "正在加载订单素材库" : "正在加载任务素材", body: nil, identifier: "drone.materials.remote.loading")
} else if let error = viewModel.detailErrorMessage {
cell.apply(title: "订单信息加载失败", body: error, identifier: "drone.materials.remote.error", button: "重试", actionID: "drone.materials.remote.retry") { [weak self] in self?.load(.refresh) }
} else if let error = viewModel.tasksErrorMessage {
cell.apply(title: "任务素材加载失败", body: error, identifier: "drone.materials.remote.error", button: "重试", actionID: "drone.materials.remote.retry") { [weak self] in self?.load(.retry) }
} else {
cell.apply(title: displayedSpotID == nil ? "暂无任务记录" : "当前点位暂无任务记录", body: "拍摄任务与素材更新后,可下拉刷新查看", identifier: "drone.materials.remote.empty")
}
default: break
private func configureMessage(_ cell: DroneDockMaterialMessageCell) {
if operation != nil || viewModel.isLoading || viewModel.isLoadingTasks {
cell.apply(title: viewModel.detail == nil ? "正在加载订单素材库" : "正在加载任务素材",
detail: "请稍候", identifier: "drone.materials.remote.loading", loading: true)
} else if let error = viewModel.detailErrorMessage {
cell.apply(title: "订单信息加载失败", detail: error, identifier: "drone.materials.remote.error", error: true) { [weak self] in self?.load(.refresh) }
} else if let error = viewModel.tasksErrorMessage {
cell.apply(title: "任务素材加载失败", detail: error, identifier: "drone.materials.remote.error", error: true) { [weak self] in self?.load(.retry) }
} else {
cell.apply(title: displayedSpotID == nil ? "暂无任务记录" : "当前点位暂无任务记录",
detail: "拍摄任务与素材更新后,可下拉刷新查看", identifier: "drone.materials.remote.empty")
}
}
@@ -175,22 +216,33 @@ final class DroneDockMaterialsViewController: BaseViewController {
case .media:
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 * 0.57 + 72)), repeatingSubitem: item, count: 2)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 9 / 16 + 51)), repeatingSubitem: item, count: 2)
group.interItemSpacing = .fixed(12)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 0, leading: 16, bottom: 16, trailing: 16)
section.interGroupSpacing = 12
section.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(1)),
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom)]
return section
case .message:
return self.singleColumnSection(height: .absolute(250))
case .summary:
return self.singleColumnSection(height: .absolute(46))
default:
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .estimated(80)))
let group = NSCollectionLayoutGroup.vertical(layoutSize: item.layoutSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 0, leading: 16, bottom: 0, trailing: 16)
return section
return self.singleColumnSection(height: .estimated(90))
}
}
}
private func singleColumnSection(height: NSCollectionLayoutDimension) -> NSCollectionLayoutSection {
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: height))
let group = NSCollectionLayoutGroup.vertical(layoutSize: item.layoutSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 0, leading: 16, bottom: 0, trailing: 16)
return section
}
private func applySnapshot(animated: Bool) {
guard dataSource != nil else { return }
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
@@ -217,6 +269,11 @@ final class DroneDockMaterialsViewController: BaseViewController {
snapshot.appendSections([.message])
snapshot.appendItems([.message], toSection: .message)
}
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "",
primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line",
enabled: operation == nil && viewModel.selectedCount > 0,
identifier: "drone.materials.remote.download", progress: nil,
trailingText: "仅可选择已上传素材")
let previous = Set(dataSource.snapshot().itemIdentifiers)
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) })
dataSource.apply(snapshot, animatingDifferences: animated)
@@ -250,8 +307,25 @@ final class DroneDockMaterialsViewController: BaseViewController {
navigationController.pushViewController(deliveryControllerFactory(order, viewModel.context, taskID), animated: true)
}
private func downloadTapped() {
guard operation == nil, viewModel.selectedCount > 0 else { return }
showAlert(title: "下载功能暂未开放", message: "已选择的素材会保留。当前版本尚未接入下载和保存相册功能。")
}
private func previewFile(taskID: Int, fileID: Int) {
guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return }
preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材")
}
private func previewFilm(taskID: Int) {
guard operation == nil, let film = task(taskID)?.film, let url = film.previewURL else { return }
preview(url: url, isVideo: true, title: film.fileName ?? "视频成片")
}
private func preview(url: URL, isVideo: Bool, title: String) {
if isVideo {
if let mediaPreviewControllerFactory {
navigationController?.pushViewController(mediaPreviewControllerFactory(url, isVideo, title), animated: true)
} else if isVideo {
let player = AVPlayerViewController()
player.player = AVPlayer(url: url)
present(player, animated: true) { player.player?.play() }
@@ -264,17 +338,7 @@ final class DroneDockMaterialsViewController: BaseViewController {
DroneDockHomeMetric.usableText(value) ?? fallback
}
private static func flightTitle(_ status: Int?) -> String {
switch status {
case 10: "待飞行"
case 20: "执行中"
case 30: "飞行成功"
case 40: "飞行失败"
case 50: "已取消"
case 60: "待确认"
default: "飞行状态待确认"
}
}
}
extension DroneDockMaterialsViewController: UICollectionViewDelegate {
@@ -286,138 +350,14 @@ extension DroneDockMaterialsViewController: UICollectionViewDelegate {
guard viewModel.detail != nil, id != displayedSpotID else { return }
load(.filter(id))
case .file(let taskID, let fileID):
guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return }
preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材")
previewFile(taskID: taskID, fileID: fileID)
case .film(let taskID, _):
guard operation == nil, let film = task(taskID)?.film, let url = film.previewURL else { return }
preview(url: url, isVideo: true, title: film.fileName ?? "视频成片")
previewFilm(taskID: taskID)
default: break
}
}
}
/// 摘要、任务状态及可恢复错误共用的自适应文字行。
@MainActor
private final class DroneDockMaterialTextCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 15, weight: .semibold)
private let bodyLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let button = UIButton(type: .system)
private var action: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.numberOfLines = 0
bodyLabel.numberOfLines = 0
let stack = UIStackView(arrangedSubviews: [titleLabel, bodyLabel, button])
stack.axis = .vertical
stack.spacing = 8
stack.alignment = .leading
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 14, left: 0, bottom: 16, right: 0)) }
titleLabel.snp.makeConstraints { $0.width.equalTo(stack) }
bodyLabel.snp.makeConstraints { $0.width.equalTo(stack) }
button.tintColor = DroneDockStyle.primary
button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 切换内容时同时清除复用单元的旧操作。
func apply(title: String, body: String?, identifier: String, compact: Bool = false,
button buttonTitle: String? = nil, actionID: String? = nil, action: (() -> Void)? = nil) {
titleLabel.text = title
titleLabel.font = .systemFont(ofSize: compact ? 13 : 15, weight: .semibold)
bodyLabel.text = body
bodyLabel.isHidden = body == nil
button.isHidden = buttonTitle == nil
button.setTitle(buttonTitle, for: .normal)
button.accessibilityIdentifier = actionID
self.action = action
accessibilityIdentifier = identifier
}
@objc private func tapped() { action?() }
}
/// 加载远程缩略图并明确区分原素材、视频成片及不可预览状态。
@MainActor
private final class DroneDockMaterialMediaCell: UICollectionViewCell {
private let thumbnail = UIImageView()
private let icon = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 12, weight: .medium)
private let stateLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
thumbnail.contentMode = .scaleAspectFill
thumbnail.clipsToBounds = true
thumbnail.layer.cornerRadius = 8
thumbnail.backgroundColor = DroneDockStyle.background
icon.tintColor = DroneDockStyle.secondary
icon.contentMode = .scaleAspectFit
titleLabel.numberOfLines = 2
stateLabel.numberOfLines = 2
[thumbnail, icon, titleLabel, stateLabel].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(thumbnail.snp.width).multipliedBy(0.57) }
icon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(28) }
titleLabel.snp.makeConstraints { make in make.top.equalTo(thumbnail.snp.bottom).offset(8); make.leading.trailing.equalToSuperview() }
stateLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(4); make.leading.trailing.equalToSuperview(); make.bottom.lessThanOrEqualToSuperview() }
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func prepareForReuse() {
super.prepareForReuse()
thumbnail.kf.cancelDownloadTask()
thumbnail.image = nil
}
/// 未就绪的原素材仍显示服务端状态,但不会启动播放或下载。
func apply(file: DroneDockMaterialFile, taskID: Int) {
let state: String
switch file.uploadStatus {
case 0: state = "待上传"
case 1: state = file.previewURL == nil ? "暂不可预览" : (file.fileType == 2 ? "点击播放" : "点击预览")
case 2: state = "上传中"
case 3: state = "上传失败"
default: state = "素材状态待确认"
}
let kind = file.fileType == 1 ? "图片" : file.fileType == 2 ? "视频" : "文件"
let title = DroneDockHomeMetric.usableText(file.fileName) ?? "原素材 \(file.id)"
apply(title: title, state: "原素材 · \(kind) · \(state)", cover: file.coverURL,
fallback: file.fileType == 1 ? file.previewURL : nil, video: file.fileType == 2,
enabled: file.previewURL != nil, identifier: "drone.materials.remote.file.\(taskID).\(file.id)")
accessibilityHint = file.uploadStatus == 3 ? DroneDockHomeMetric.usableText(file.failureReason) : nil
}
/// 成片是任务中的独立视频,不混入原素材数量或上传状态。
func apply(film: DroneDockMaterialFilm, taskID: Int) {
apply(title: DroneDockHomeMetric.usableText(film.fileName) ?? "视频成片", state: "视频成片 · \(film.previewURL == nil ? "暂不可预览" : "点击播放")",
cover: film.coverURL, fallback: nil, video: true, enabled: film.previewURL != nil,
identifier: "drone.materials.remote.film.\(taskID).\(film.id)")
accessibilityHint = nil
}
private func apply(title: String, state: String, cover: String?, fallback: URL?, video: Bool, enabled: Bool, identifier: String) {
thumbnail.kf.cancelDownloadTask()
thumbnail.image = nil
let coverURL = cover.flatMap(URL.init(string:)).flatMap { url in
["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil ? url : nil
}
thumbnail.kf.setImage(with: coverURL ?? fallback)
icon.image = UIImage(systemName: video && enabled ? "play.circle.fill" : video ? "video" : "photo")
icon.isHidden = !video && (coverURL ?? fallback) != nil
titleLabel.text = title
stateLabel.text = state
accessibilityIdentifier = identifier
accessibilityLabel = "\(title),\(state)"
accessibilityTraits = enabled ? .button : [.notEnabled]
}
}
/// 通过 Kingfisher 展示真实图片,加载失败保留明确提示。
@MainActor
private final class DroneDockMaterialImageViewController: UIViewController {