feat: 完善机巢模拟调试与素材交付交互
增加禁飞期间的设备指令拦截及本地模拟拍摄流程;适配订单素材库和景区空境库,完善素材筛选、预览与下载;订单交付入口改为方式选择弹窗并复用云端上传。补充单元测试、接口记录和模拟器截图。
This commit is contained in:
@@ -3,6 +3,33 @@ import UIKit
|
||||
/// 订单列表与素材库共用的真实成片交付页面工厂。
|
||||
@MainActor
|
||||
enum DroneDockDeliveryEntry {
|
||||
/// 订单列表先展示方式选择,云端页面在同一弹窗内继续,关闭后再通知列表刷新。
|
||||
static func makeMethodSheet(order: DroneDockHomeOrder, context: DroneDockHomeContext,
|
||||
controllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController,
|
||||
onDidCloseCloud: @escaping () -> Void = {}) -> UINavigationController {
|
||||
let methods = DroneDockDeliveryMethodViewController(customerTitle: order.touristTitle)
|
||||
let navigation = DroneDockDeliverySheetNavigationController(rootViewController: methods)
|
||||
navigation.modalPresentationStyle = .pageSheet
|
||||
navigation.onDidCloseCloud = onDidCloseCloud
|
||||
methods.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
methods.onCloudUpload = { [weak navigation, weak methods] in
|
||||
guard let navigation, let methods, navigation.topViewController === methods else { return }
|
||||
let cloud = controllerFactory(order, context, nil)
|
||||
if let cloud = cloud as? DroneDockDeliveryViewController {
|
||||
cloud.configureSheetPresentation { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
}
|
||||
navigation.didOpenCloud = true
|
||||
navigation.isModalInPresentation = true
|
||||
navigation.sheetPresentationController?.animateChanges {
|
||||
navigation.sheetPresentationController?.detents = [.large()]
|
||||
navigation.sheetPresentationController?.selectedDetentIdentifier = .large
|
||||
}
|
||||
navigation.setNavigationBarHidden(false, animated: true)
|
||||
navigation.pushViewController(cloud, animated: true)
|
||||
}
|
||||
return navigation
|
||||
}
|
||||
|
||||
/// 同时传递订单与可选任务,进入页面后重新校验当前身份和上传权限。
|
||||
static func makeController(order: DroneDockHomeOrder, context: DroneDockHomeContext, taskID: Int?) -> UIViewController {
|
||||
let client = NetworkServices.shared.apiClient
|
||||
@@ -15,3 +42,32 @@ enum DroneDockDeliveryEntry {
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// 统一处理手动关闭与下拉关闭,云端交付结束后只通知来源列表一次。
|
||||
@MainActor
|
||||
private final class DroneDockDeliverySheetNavigationController: UINavigationController, UIAdaptivePresentationControllerDelegate {
|
||||
/// 云端页面已经进入,关闭弹窗后需要重读订单状态。
|
||||
var didOpenCloud = false
|
||||
/// 不因仅查看交付方式而刷新订单。
|
||||
var onDidCloseCloud: (() -> Void)?
|
||||
private var didNotifyClose = false
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
presentationController?.delegate = self
|
||||
}
|
||||
|
||||
override func viewDidDisappear(_ animated: Bool) {
|
||||
super.viewDidDisappear(animated)
|
||||
if isBeingDismissed || presentingViewController == nil { notifyClose() }
|
||||
}
|
||||
|
||||
/// 系统下拉关闭与按钮关闭使用同一去重通知。
|
||||
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { notifyClose() }
|
||||
|
||||
private func notifyClose() {
|
||||
guard !didNotifyClose else { return }
|
||||
didNotifyClose = true
|
||||
if didOpenCloud { onDidCloseCloud?() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 真实订单的交付方式弹窗,只展示方式选择并将云端交付导航交回入口。
|
||||
@MainActor
|
||||
final class DroneDockDeliveryMethodViewController: BaseViewController {
|
||||
/// 用户选择云端上传后,由入口打开现有真实交付页。
|
||||
var onCloudUpload: (() -> Void)?
|
||||
/// 用户关闭弹窗后,由入口统一结束当前模态流程。
|
||||
var onClose: (() -> Void)?
|
||||
|
||||
/// 闪传只显示未接入说明,不创建传输任务或连接设备。
|
||||
private enum Phase: Equatable { case methods, nearby }
|
||||
/// 两种交付方式与闪传说明使用独立、稳定的列表身份。
|
||||
private enum Item: Hashable { case nearby, cloud, nearbyMessage }
|
||||
|
||||
private let customerTitle: String
|
||||
private let headerView = DroneDeliveryUploadHeaderView()
|
||||
private let footerView = DroneDeliveryUploadFooterView()
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Int, Item>!
|
||||
private var phase = Phase.methods
|
||||
private var hasRequestedCloud = false
|
||||
|
||||
/// 游客标题由选中的订单传入,本弹窗不读取网络或改变订单状态。
|
||||
init(customerTitle: String) {
|
||||
self.customerTitle = customerTitle
|
||||
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)
|
||||
hasRequestedCloud = false
|
||||
navigationController?.isModalInPresentation = false
|
||||
isModalInPresentation = false
|
||||
navigationController?.setNavigationBarHidden(true, animated: false)
|
||||
configureSheet()
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "交付成片"
|
||||
navigationController?.setNavigationBarHidden(true, animated: false)
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
collectionView.backgroundColor = .white
|
||||
collectionView.alwaysBounceVertical = false
|
||||
collectionView.showsVerticalScrollIndicator = false
|
||||
collectionView.accessibilityIdentifier = "drone.delivery.method.list"
|
||||
collectionView.delegate = self
|
||||
collectionView.register(DroneDeliveryUploadMethodCell.self, forCellWithReuseIdentifier: "method")
|
||||
collectionView.register(DroneDeliveryUploadMessageCell.self, forCellWithReuseIdentifier: "message")
|
||||
[headerView, collectionView, footerView].forEach(view.addSubview)
|
||||
configureDataSource()
|
||||
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?.onClose?() }
|
||||
footerView.onPrimaryTap = { [weak self] in self?.requestCloudUpload() }
|
||||
footerView.onSecondaryTap = { [weak self] in self?.showPhase(.methods) }
|
||||
}
|
||||
|
||||
private func configureSheet() {
|
||||
guard let sheet = navigationController?.sheetPresentationController ?? sheetPresentationController else { return }
|
||||
let identifier = UISheetPresentationController.Detent.Identifier("drone.delivery.method")
|
||||
sheet.detents = [
|
||||
.custom(identifier: identifier) { context in min(410, context.maximumDetentValue) },
|
||||
.large()
|
||||
]
|
||||
sheet.selectedDetentIdentifier = identifier
|
||||
sheet.prefersGrabberVisible = true
|
||||
sheet.preferredCornerRadius = 22
|
||||
sheet.prefersScrollingExpandsWhenScrolledToEdge = false
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { [weak self] _, _ in
|
||||
guard let self else { return nil }
|
||||
let height: CGFloat = self.phase == .methods ? 88 : 132
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
|
||||
let group = NSCollectionLayoutGroup.vertical(
|
||||
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)), subitems: [item])
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.interGroupSpacing = self.phase == .methods ? 12 : 0
|
||||
section.contentInsets = .init(top: 4, leading: 20, bottom: 4, trailing: 20)
|
||||
return section
|
||||
}
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Int, Item>(collectionView: collectionView) { collection, path, item in
|
||||
switch item {
|
||||
case .nearby, .cloud:
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "method", for: path) as! DroneDeliveryUploadMethodCell
|
||||
if item == .nearby {
|
||||
cell.apply(title: "面对面闪传", detail: "近距离传给游客 · 流程待确认", symbol: "wifi", identifier: "drone.delivery.method.nearby")
|
||||
} else {
|
||||
cell.apply(title: "云端上传", detail: "选择打卡点,上传后游客可查看", symbol: "icloud.and.arrow.up", identifier: "drone.delivery.method.cloud")
|
||||
}
|
||||
return cell
|
||||
case .nearbyMessage:
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DroneDeliveryUploadMessageCell
|
||||
cell.apply(title: "闪传流程待确认", detail: "热点连接与游客接收流程暂未接入。\n请使用云端上传交付成片。", symbol: "wifi")
|
||||
cell.accessibilityIdentifier = "drone.delivery.method.nearbyMessage"
|
||||
return cell
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func applySnapshot(animated: Bool) {
|
||||
guard dataSource != nil else { return }
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
|
||||
snapshot.appendSections([0])
|
||||
switch phase {
|
||||
case .methods:
|
||||
headerView.apply(title: "交付成片", customer: customerTitle, detail: "请选择本次交付方式")
|
||||
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批交付多个作品,不影响拍摄次数", secondaryTitle: nil)
|
||||
snapshot.appendItems([.nearby, .cloud])
|
||||
case .nearby:
|
||||
headerView.apply(title: "面对面闪传", customer: customerTitle, detail: "本次仅展示交付入口")
|
||||
footerView.apply(primaryTitle: "改用云端上传", enabled: true, identifier: "drone.delivery.method.useCloud", detail: "", secondaryTitle: "返回交付方式")
|
||||
snapshot.appendItems([.nearbyMessage])
|
||||
}
|
||||
dataSource.apply(snapshot, animatingDifferences: animated)
|
||||
collectionView.collectionViewLayout.invalidateLayout()
|
||||
}
|
||||
|
||||
private func showPhase(_ phase: Phase) {
|
||||
self.phase = phase
|
||||
applySnapshot(animated: true)
|
||||
collectionView.setContentOffset(.zero, animated: false)
|
||||
}
|
||||
|
||||
private func requestCloudUpload() {
|
||||
guard !hasRequestedCloud, let onCloudUpload else { return }
|
||||
hasRequestedCloud = true
|
||||
onCloudUpload()
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockDeliveryMethodViewController: UICollectionViewDelegate {
|
||||
/// 云端方式交回调用方,闪传方式只在当前弹窗展示待接入说明。
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath), !hasRequestedCloud else { return }
|
||||
switch item {
|
||||
case .nearby: showPhase(.nearby)
|
||||
case .cloud: requestCloudUpload()
|
||||
case .nearbyMessage: break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ final class DroneDockDeliveryViewController: BaseViewController {
|
||||
private var pickerError: String?
|
||||
private var ownedVideoURLs: Set<URL> = []
|
||||
private var previousGestureEnabled: Bool?
|
||||
private var onCloseSheet: (() -> Void)?
|
||||
private weak var trackedNavigationController: UINavigationController?
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||||
@@ -50,15 +51,26 @@ final class DroneDockDeliveryViewController: BaseViewController {
|
||||
ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard)
|
||||
}
|
||||
|
||||
/// 订单列表以弹窗展示时复用上传流程,并将关闭动作纳入处理中退出确认。
|
||||
func configureSheetPresentation(onClose: @escaping () -> Void) {
|
||||
onCloseSheet = onClose
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "交付成片"
|
||||
title = onCloseSheet == nil ? "交付成片" : "云端上传"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
let back = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(backTapped))
|
||||
let back = UIBarButtonItem(title: onCloseSheet == nil ? "返回" : "交付方式", style: .plain, target: self, action: #selector(backTapped))
|
||||
back.accessibilityIdentifier = "drone.delivery.back"
|
||||
navigationItem.leftBarButtonItem = back
|
||||
let refresh = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshTapped))
|
||||
refresh.accessibilityIdentifier = "drone.delivery.refresh"
|
||||
navigationItem.rightBarButtonItem = refresh
|
||||
if onCloseSheet != nil {
|
||||
let close = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(closeSheetTapped))
|
||||
close.accessibilityLabel = "关闭成片交付"
|
||||
close.accessibilityIdentifier = "drone.delivery.sheet.close"
|
||||
navigationItem.rightBarButtonItems = [close, refresh]
|
||||
}
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
@@ -110,6 +122,12 @@ final class DroneDockDeliveryViewController: BaseViewController {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
if onCloseSheet != nil {
|
||||
navigationController?.setNavigationBarHidden(false, animated: false)
|
||||
navigationController?.isModalInPresentation = true
|
||||
navigationController?.sheetPresentationController?.detents = [.large()]
|
||||
navigationController?.sheetPresentationController?.selectedDetentIdentifier = .large
|
||||
}
|
||||
trackedNavigationController = navigationController
|
||||
if previousGestureEnabled == nil { previousGestureEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled }
|
||||
guard !hasAppeared else { updateFooter(); return }
|
||||
@@ -246,7 +264,7 @@ final class DroneDockDeliveryViewController: BaseViewController {
|
||||
submitButton.setTitle(working ? "处理中…" : title, for: .normal)
|
||||
submitButton.isEnabled = viewModel.canSubmit && !locked
|
||||
submitButton.backgroundColor = submitButton.isEnabled ? DroneDockStyle.primary : DroneDockStyle.secondary.withAlphaComponent(0.45)
|
||||
navigationItem.rightBarButtonItem?.isEnabled = !working && !isPicking && !isRefreshing
|
||||
navigationItem.rightBarButtonItems?.first { $0.accessibilityIdentifier == "drone.delivery.refresh" }?.isEnabled = !working && !isPicking && !isRefreshing
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = !working && !isStartingSubmission && !isPicking && (previousGestureEnabled ?? true)
|
||||
}
|
||||
|
||||
@@ -368,14 +386,23 @@ final class DroneDockDeliveryViewController: BaseViewController {
|
||||
}
|
||||
|
||||
@objc private func backTapped() {
|
||||
guard viewModel.isSubmitting || isStartingSubmission || isPicking else { navigationController?.popViewController(animated: true); return }
|
||||
requestExit { [weak self] in self?.navigationController?.popViewController(animated: true) }
|
||||
}
|
||||
|
||||
@objc private func closeSheetTapped() {
|
||||
requestExit { [weak self] in self?.onCloseSheet?() }
|
||||
}
|
||||
|
||||
private func requestExit(_ exit: @escaping () -> Void) {
|
||||
guard presentedViewController == nil else { return }
|
||||
guard viewModel.isSubmitting || isStartingSubmission || isPicking else { exit(); return }
|
||||
let alert = UIAlertController(title: "停止处理并返回?", message: "未完成的上传将停止。如果正在保存成片,返回素材库刷新可核对实际结果。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续处理", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "停止并返回", style: .destructive) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.operationTask?.cancel()
|
||||
self.viewModel.invalidate()
|
||||
self.navigationController?.popViewController(animated: true)
|
||||
exit()
|
||||
})
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
@@ -309,6 +309,7 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
planeStatusService: DroneDockPlaneStatusAPI(client: NetworkServices.shared.apiClient),
|
||||
taskCreationService: DroneDockTaskCreationAPI(client: NetworkServices.shared.apiClient),
|
||||
shootService: DroneDockShootAPI(client: NetworkServices.shared.apiClient),
|
||||
allowsTaskSubmission: !DeviceCommandDebugPolicy.blocksLiveRequests,
|
||||
currentContext: { Self.currentContext() }
|
||||
))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
import Kingfisher
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 真实订单素材库摘要:游客与状态同排,次数始终来自订单详情。
|
||||
@MainActor
|
||||
final class DroneDockMaterialOrderCell: UICollectionViewCell {
|
||||
private let customerLabel = DroneDockStyle.label(size: 19, weight: .semibold)
|
||||
private let statusLabel = DroneDockStatusLabel()
|
||||
private let numberLabel = DroneDockStyle.label(size: 13, color: UIColor(hex: 0x70809D))
|
||||
private let countLabel = DroneDockStyle.label(size: 13, color: UIColor(hex: 0x5D6C88))
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
let row = UIStackView(arrangedSubviews: [customerLabel, statusLabel, UIView()])
|
||||
row.axis = .horizontal
|
||||
row.spacing = 8
|
||||
row.alignment = .center
|
||||
customerLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
|
||||
customerLabel.lineBreakMode = .byTruncatingTail
|
||||
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
numberLabel.numberOfLines = 2
|
||||
countLabel.numberOfLines = 2
|
||||
let stack = UIStackView(arrangedSubviews: [row, numberLabel, countLabel])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 9
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in
|
||||
make.top.equalToSuperview().offset(16)
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.bottom.equalToSuperview().inset(18)
|
||||
}
|
||||
accessibilityIdentifier = "drone.materials.remote.order"
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 不根据任务数量或素材上传状态推导订单拍摄履约状态。
|
||||
func apply(order: DroneDockHomeOrder) {
|
||||
customerLabel.text = order.touristTitle
|
||||
let tone: DroneDockStatusTone = switch order.shootStatus {
|
||||
case "completed": .green
|
||||
case "processing": .blue
|
||||
case "pending": .orange
|
||||
default: .gray
|
||||
}
|
||||
statusLabel.apply(title: order.statusTitle, tone: tone)
|
||||
numberLabel.text = order.orderNumberText
|
||||
let total = order.shotTotal.map(String.init) ?? "—"
|
||||
let used = order.shotUsed.map(String.init) ?? "—"
|
||||
let remain = order.shotRemain.map(String.init) ?? "—"
|
||||
countLabel.text = "含\(total)次拍摄 · 已拍摄\(used)次 · 剩余\(remain)次"
|
||||
accessibilityLabel = [order.touristTitle, order.statusTitle, order.orderNumberText, countLabel.text].compactMap { $0 }.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
/// 素材记录标题:点位和交付按钮同排,航线、时间、记录序号位于次行。
|
||||
@MainActor
|
||||
final class DroneDockMaterialRecordCell: UICollectionViewCell {
|
||||
private let titleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
|
||||
private let metadataLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let deliveryButton = UIButton(type: .system)
|
||||
private let emptyIcon = UIImageView()
|
||||
private let emptyTitle = DroneDockStyle.label(size: 13, weight: .medium)
|
||||
private let emptyDetail = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let emptyPanel = UIStackView()
|
||||
private let separator = UIView()
|
||||
private var action: (() -> Void)?
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
titleLabel.numberOfLines = 1
|
||||
titleLabel.lineBreakMode = .byTruncatingTail
|
||||
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
|
||||
deliveryButton.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
deliveryButton.tintColor = DroneDockStyle.primary
|
||||
deliveryButton.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside)
|
||||
let titleRow = UIStackView(arrangedSubviews: [titleLabel, UIView(), deliveryButton])
|
||||
titleRow.axis = .horizontal
|
||||
titleRow.alignment = .center
|
||||
titleRow.spacing = 8
|
||||
metadataLabel.numberOfLines = 2
|
||||
emptyIcon.contentMode = .scaleAspectFit
|
||||
emptyTitle.numberOfLines = 2
|
||||
emptyDetail.numberOfLines = 0
|
||||
emptyPanel.axis = .vertical
|
||||
emptyPanel.alignment = .leading
|
||||
emptyPanel.spacing = 6
|
||||
let emptyHeading = UIStackView(arrangedSubviews: [emptyIcon, emptyTitle])
|
||||
emptyHeading.axis = .horizontal
|
||||
emptyHeading.alignment = .center
|
||||
emptyHeading.spacing = 6
|
||||
emptyIcon.snp.makeConstraints { $0.size.equalTo(16).priority(999) }
|
||||
emptyPanel.addArrangedSubview(emptyHeading)
|
||||
emptyPanel.addArrangedSubview(emptyDetail)
|
||||
let stack = UIStackView(arrangedSubviews: [titleRow, metadataLabel, emptyPanel])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 7
|
||||
stack.setCustomSpacing(14, after: metadataLabel)
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in
|
||||
make.top.equalToSuperview().offset(14)
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.bottom.equalToSuperview().inset(14)
|
||||
}
|
||||
deliveryButton.snp.makeConstraints { $0.height.equalTo(44) }
|
||||
separator.backgroundColor = DroneDockStyle.border
|
||||
contentView.addSubview(separator)
|
||||
separator.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(0.5) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 保留无素材任务的独立飞行与上传状态,不伪造文件或上传进度。
|
||||
func apply(task: DroneDockMaterialTask, canDeliver: Bool, action: @escaping () -> Void) {
|
||||
titleLabel.text = usable(task.spotName, fallback: "点位 \(task.spotID)")
|
||||
let record = task.sequence.map { String(format: "记录%02d", $0) } ?? "记录序号待确认"
|
||||
metadataLabel.text = "\(usable(task.airLineName, fallback: "航线待确认")) · \(shortDate(task.createdAt)) · \(record)"
|
||||
var configuration = UIButton.Configuration.plain()
|
||||
configuration.title = task.film == nil ? "交付成片" : "替换成片"
|
||||
configuration.image = UIImage(systemName: "play.rectangle")
|
||||
configuration.imagePadding = 5
|
||||
configuration.contentInsets = .zero
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13)
|
||||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { value in
|
||||
var attributes = value
|
||||
attributes.font = .systemFont(ofSize: 12)
|
||||
return attributes
|
||||
}
|
||||
deliveryButton.configuration = configuration
|
||||
deliveryButton.isHidden = !canDeliver
|
||||
deliveryButton.accessibilityIdentifier = "drone.materials.remote.delivery.\(task.id)"
|
||||
self.action = action
|
||||
emptyPanel.isHidden = !task.materials.isEmpty
|
||||
separator.isHidden = !task.materials.isEmpty || task.film != nil
|
||||
let state: (String, String, String, UIColor) = switch task.materialStatus {
|
||||
case 0: ("素材待上传", "拍摄完成后将自动上传,请稍后刷新", "icloud.and.arrow.up", DroneDockStyle.secondary)
|
||||
case 1: ("暂无可用原素材", "素材记录尚未返回,请刷新查看", "photo.on.rectangle", DroneDockStyle.secondary)
|
||||
case 2: ("素材上传中", "素材正在上传,请稍后刷新查看", "icloud.and.arrow.up", DroneDockStyle.primary)
|
||||
case 3: ("素材上传失败", "请刷新查看最新状态,或联系工作人员", "xmark.circle", DroneDockStyle.color(for: .red))
|
||||
default: ("素材状态待确认", "暂无原素材,请稍后刷新查看", "questionmark.circle", DroneDockStyle.secondary)
|
||||
}
|
||||
emptyTitle.text = state.0
|
||||
emptyTitle.textColor = state.3
|
||||
emptyIcon.image = UIImage(systemName: state.2)
|
||||
emptyIcon.tintColor = state.3
|
||||
let film = task.film == nil ? " · 暂无视频成片" : ""
|
||||
emptyDetail.text = "\(flightTitle(task.flightStatus))\(film)\n\(state.1)"
|
||||
accessibilityIdentifier = "drone.materials.remote.task.\(task.id)"
|
||||
}
|
||||
|
||||
private func usable(_ value: String?, fallback: String) -> String { DroneDockHomeMetric.usableText(value) ?? fallback }
|
||||
private func shortDate(_ raw: String?) -> String {
|
||||
guard let raw = DroneDockHomeMetric.usableText(raw) else { return "时间待确认" }
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
||||
guard let date = formatter.date(from: raw) else { return raw }
|
||||
formatter.dateFormat = "MM-dd HH:mm"
|
||||
return formatter.string(from: date)
|
||||
}
|
||||
private func flightTitle(_ value: Int?) -> String {
|
||||
switch value {
|
||||
case 10: "待飞行"
|
||||
case 20: "执行中"
|
||||
case 30: "飞行成功"
|
||||
case 40: "飞行失败"
|
||||
case 50: "已取消"
|
||||
case 60: "待确认"
|
||||
default: "飞行状态待确认"
|
||||
}
|
||||
}
|
||||
@objc private func deliveryTapped() { action?() }
|
||||
}
|
||||
|
||||
/// 真实文件的缩略图、状态和选择控件;预览与选择使用独立点击区域。
|
||||
@MainActor
|
||||
final class DroneDockMaterialMediaCell: UICollectionViewCell {
|
||||
private let thumbnail = UIImageView()
|
||||
private let icon = UIImageView()
|
||||
private let previewButton = UIButton(type: .custom)
|
||||
private let selectionButton = UIButton(type: .custom)
|
||||
private let videoBadge = DroneDockStyle.label("视频", size: 10, color: .white)
|
||||
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
|
||||
private let stateLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let retryLabel = DroneDockStyle.label("重试上传", size: 11, color: DroneDockStyle.primary.withAlphaComponent(0.5))
|
||||
private var previewAction: (() -> Void)?
|
||||
private var selectionAction: (() -> Void)?
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
thumbnail.contentMode = .scaleAspectFill
|
||||
thumbnail.clipsToBounds = true
|
||||
thumbnail.layer.cornerRadius = 6
|
||||
thumbnail.layer.borderWidth = 2
|
||||
thumbnail.backgroundColor = UIColor(hex: 0xE9EDF5)
|
||||
thumbnail.accessibilityIdentifier = "drone.materials.remote.thumbnail"
|
||||
icon.contentMode = .scaleAspectFit
|
||||
titleLabel.lineBreakMode = .byTruncatingMiddle
|
||||
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
|
||||
retryLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
retryLabel.accessibilityTraits = [.button, .notEnabled]
|
||||
retryLabel.accessibilityHint = "当前接口不支持重试上传,可通过页面刷新查看最新状态"
|
||||
videoBadge.textAlignment = .center
|
||||
videoBadge.backgroundColor = UIColor.black.withAlphaComponent(0.48)
|
||||
videoBadge.layer.cornerRadius = 3
|
||||
videoBadge.clipsToBounds = true
|
||||
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
|
||||
selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
|
||||
let nameRow = UIStackView(arrangedSubviews: [titleLabel, retryLabel])
|
||||
nameRow.axis = .horizontal
|
||||
nameRow.spacing = 4
|
||||
nameRow.alignment = .center
|
||||
[thumbnail, icon, previewButton, videoBadge, selectionButton, nameRow, stateLabel].forEach(contentView.addSubview)
|
||||
thumbnail.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(thumbnail.snp.width).multipliedBy(9.0 / 16.0) }
|
||||
icon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(28) }
|
||||
previewButton.snp.makeConstraints { $0.edges.equalTo(thumbnail) }
|
||||
selectionButton.snp.makeConstraints { make in make.top.trailing.equalTo(thumbnail); make.size.equalTo(44) }
|
||||
videoBadge.snp.makeConstraints { make in make.leading.bottom.equalTo(thumbnail).inset(6); make.size.equalTo(CGSize(width: 32, height: 18)) }
|
||||
nameRow.snp.makeConstraints { make in make.top.equalTo(thumbnail.snp.bottom).offset(7); make.leading.trailing.equalToSuperview() }
|
||||
stateLabel.snp.makeConstraints { make in make.top.equalTo(nameRow.snp.bottom).offset(4); make.leading.trailing.equalToSuperview(); make.bottom.lessThanOrEqualToSuperview().inset(5) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() {
|
||||
super.prepareForReuse()
|
||||
thumbnail.kf.cancelDownloadTask()
|
||||
thumbnail.image = nil
|
||||
previewAction = nil
|
||||
selectionAction = nil
|
||||
}
|
||||
|
||||
/// 原素材上传就绪且 URL 有效才可勾选;Mock 图片存在时不请求远程缩略图。
|
||||
func apply(file: DroneDockMaterialFile, taskID: Int, selected: Bool, selectionEnabled: Bool,
|
||||
localImage: UIImage?, allowsRemoteImage: Bool, preview: @escaping () -> Void, select: @escaping () -> Void) {
|
||||
let ready = file.previewURL != nil
|
||||
let state: (String, UIColor) = switch file.uploadStatus {
|
||||
case 0: ("待上传", DroneDockStyle.secondary)
|
||||
case 1: (ready ? "上传完成 · 可下载" : "暂不可预览", ready ? DroneDockStyle.success : DroneDockStyle.secondary)
|
||||
case 2: ("上传中", DroneDockStyle.primary)
|
||||
case 3: ("上传失败", DroneDockStyle.color(for: .red))
|
||||
default: ("素材状态待确认", DroneDockStyle.secondary)
|
||||
}
|
||||
let title = DroneDockHomeMetric.usableText(file.fileName) ?? "原素材 \(file.id)"
|
||||
apply(title: title, state: state.0, color: state.1, cover: ready ? file.coverURL : nil,
|
||||
fallback: ready && file.fileType == 1 ? file.previewURL : nil, video: file.fileType == 2,
|
||||
enabled: ready, failed: file.uploadStatus == 3, localImage: ready ? localImage : nil,
|
||||
allowsRemoteImage: allowsRemoteImage, identifier: "drone.materials.remote.file.\(taskID).\(file.id)")
|
||||
previewAction = preview
|
||||
selectionAction = select
|
||||
selectionButton.isHidden = !ready
|
||||
selectionButton.isEnabled = ready && selectionEnabled
|
||||
selectionButton.accessibilityIdentifier = "drone.materials.remote.select.\(taskID).\(file.id)"
|
||||
selectionButton.accessibilityLabel = "选择\(title)"
|
||||
selectionButton.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
selectionButton.setImage(DroneMaterialSelectionIcon.image(selected: selected, tint: selected ? DroneDockStyle.primary : .white), for: .normal)
|
||||
selectionButton.imageView?.layer.shadowColor = UIColor.black.cgColor
|
||||
selectionButton.imageView?.layer.shadowOpacity = 0.25
|
||||
selectionButton.imageView?.layer.shadowRadius = 2
|
||||
selectionButton.imageView?.layer.shadowOffset = .zero
|
||||
thumbnail.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor
|
||||
previewButton.accessibilityHint = file.uploadStatus == 3 ? DroneDockHomeMetric.usableText(file.failureReason) : nil
|
||||
}
|
||||
|
||||
/// 已交付成片独立标记且不参与原素材全选。
|
||||
func apply(film: DroneDockMaterialFilm, taskID: Int, localImage: UIImage?, allowsRemoteImage: Bool,
|
||||
preview: @escaping () -> Void) {
|
||||
let ready = film.previewURL != nil
|
||||
apply(title: DroneDockHomeMetric.usableText(film.fileName) ?? "视频成片", state: ready ? "视频成片 · 点击播放" : "视频成片 · 暂不可预览",
|
||||
color: ready ? DroneDockStyle.success : DroneDockStyle.secondary, cover: film.coverURL, fallback: nil,
|
||||
video: true, enabled: ready, failed: false, localImage: localImage, allowsRemoteImage: allowsRemoteImage,
|
||||
identifier: "drone.materials.remote.film.\(taskID).\(film.id)")
|
||||
selectionButton.isHidden = true
|
||||
selectionAction = nil
|
||||
previewAction = preview
|
||||
previewButton.accessibilityHint = nil
|
||||
thumbnail.layer.borderColor = UIColor.clear.cgColor
|
||||
}
|
||||
|
||||
private func apply(title: String, state: String, color: UIColor, cover: String?, fallback: URL?, video: Bool,
|
||||
enabled: Bool, failed: Bool, localImage: UIImage?, allowsRemoteImage: Bool, identifier: String) {
|
||||
thumbnail.kf.cancelDownloadTask()
|
||||
thumbnail.image = localImage
|
||||
let coverURL = cover.flatMap(URL.init(string:)).flatMap { url in
|
||||
["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil ? url : nil
|
||||
}
|
||||
if allowsRemoteImage, enabled { thumbnail.kf.setImage(with: coverURL ?? fallback) }
|
||||
icon.image = UIImage(systemName: failed ? "xmark.circle" : video ? "play.fill" : "photo")
|
||||
icon.tintColor = failed ? DroneDockStyle.color(for: .red) : UIColor(hex: 0x9CA6B6)
|
||||
icon.isHidden = enabled && (localImage != nil || coverURL != nil || fallback != nil)
|
||||
titleLabel.text = title
|
||||
stateLabel.text = state
|
||||
stateLabel.textColor = color
|
||||
retryLabel.isHidden = !failed
|
||||
retryLabel.accessibilityIdentifier = identifier + ".retryUpload"
|
||||
videoBadge.isHidden = !video || !enabled
|
||||
previewButton.isEnabled = enabled
|
||||
previewButton.accessibilityIdentifier = identifier + ".preview"
|
||||
previewButton.accessibilityLabel = "\(title),\(state)"
|
||||
accessibilityIdentifier = identifier
|
||||
accessibilityLabel = "\(title),\(state)"
|
||||
accessibilityTraits = enabled ? .button : [.notEnabled]
|
||||
}
|
||||
|
||||
@objc private func previewTapped() { previewAction?() }
|
||||
@objc private func selectionTapped() { selectionAction?() }
|
||||
}
|
||||
|
||||
/// 居中展示列表加载、空态和错误;刷新失败与没有素材是不同状态。
|
||||
@MainActor
|
||||
final class DroneDockMaterialMessageCell: UICollectionViewCell {
|
||||
private let icon = UIImageView()
|
||||
private let titleLabel = DroneDockStyle.label(size: 16, weight: .medium)
|
||||
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let button = UIButton(type: .system)
|
||||
private let spinner = UIActivityIndicatorView(style: .medium)
|
||||
private var action: (() -> Void)?
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
icon.contentMode = .scaleAspectFit
|
||||
icon.tintColor = DroneDockStyle.secondary
|
||||
titleLabel.textAlignment = .center
|
||||
titleLabel.numberOfLines = 2
|
||||
detailLabel.textAlignment = .center
|
||||
detailLabel.numberOfLines = 0
|
||||
button.tintColor = DroneDockStyle.primary
|
||||
button.addTarget(self, action: #selector(retryTapped), for: .touchUpInside)
|
||||
let stack = UIStackView(arrangedSubviews: [icon, spinner, titleLabel, detailLabel, button])
|
||||
stack.axis = .vertical
|
||||
stack.alignment = .center
|
||||
stack.spacing = 12
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in make.centerY.equalToSuperview(); make.leading.trailing.equalToSuperview().inset(12) }
|
||||
icon.snp.makeConstraints { $0.size.equalTo(38).priority(999) }
|
||||
button.snp.makeConstraints { $0.height.equalTo(44).priority(999) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 不将错误转换为空列表,未提供重试闭包时隐藏操作。
|
||||
func apply(title: String, detail: String, identifier: String, loading: Bool = false,
|
||||
error: Bool = false, retry: (() -> Void)? = nil) {
|
||||
titleLabel.text = title
|
||||
detailLabel.text = detail
|
||||
detailLabel.isHidden = detail.isEmpty
|
||||
icon.image = UIImage(systemName: error ? "exclamationmark.circle" : "photo.on.rectangle.angled")
|
||||
icon.isHidden = loading
|
||||
if loading { spinner.startAnimating() } else { spinner.stopAnimating() }
|
||||
spinner.isHidden = !loading
|
||||
spinner.alpha = loading ? 1 : 0
|
||||
button.isHidden = retry == nil
|
||||
button.setTitle("重试", for: .normal)
|
||||
button.accessibilityIdentifier = "drone.materials.remote.retry"
|
||||
action = retry
|
||||
accessibilityIdentifier = identifier
|
||||
}
|
||||
|
||||
@objc private func retryTapped() { action?() }
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
#if DEBUG
|
||||
/// 使用正式订单素材页和内存服务验证各展示状态,不读取登录身份或连接后端。
|
||||
@MainActor
|
||||
enum DroneDockMaterialsSimulation {
|
||||
/// 支持显式场景参数,未传场景的模拟入口默认展示混合上传状态。
|
||||
static func makeController(arguments: [String]) -> UIViewController? {
|
||||
let flag = "--dock-materials-mock"
|
||||
guard arguments.contains(flag) || arguments.contains(where: { $0.hasPrefix(flag + "=") }) else { return nil }
|
||||
let value = arguments.first(where: { $0.hasPrefix(flag + "=") }).map { String($0.dropFirst(flag.count + 1)) }
|
||||
return makeController(scenario: value ?? "mixed")
|
||||
}
|
||||
|
||||
/// 创建全新模拟会话;同一页的点位筛选、选择及刷新仍由正式 ViewModel 执行。
|
||||
static func makeController(scenario: String) -> UIViewController? {
|
||||
let state = DroneDockMaterialsMockScenario(rawValue: scenario) ?? .mixed
|
||||
guard let service = try? DroneDockMaterialsMockService(scenario: state) else { return nil }
|
||||
let context = DroneDockHomeContext(userID: "local-materials-mock", accountType: "store_user",
|
||||
scenicID: 901, scenicName: "本地模拟景区", storeID: 901,
|
||||
photographerName: "本地演示", token: "local-materials-only")
|
||||
let model = DroneDockMaterialsViewModel(context: context, order: service.order,
|
||||
service: service, currentContext: { context })
|
||||
let controller = DroneDockMaterialsViewController(viewModel: model,
|
||||
deliveryControllerFactory: { _, _, _ in
|
||||
DroneDockMaterialsMockPreviewController(title: "交付成片 · 本地演示", image: nil,
|
||||
message: "本地演示仅验证入口,不连接云端或上传文件。")
|
||||
},
|
||||
thumbnailProvider: { taskID, fileID, isFilm in
|
||||
guard isFilm || service.isReady(taskID: taskID, fileID: fileID) else { return nil }
|
||||
return UIImage(named: taskID == 902 ? "drone_demo_pagoda" : fileID.isMultiple(of: 2) ? "drone_demo_mountain" : "drone_demo_tourists")
|
||||
},
|
||||
mediaPreviewControllerFactory: { _, isVideo, title in
|
||||
DroneDockMaterialsMockPreviewController(title: title, image: UIImage(named: "drone_demo_tourists"),
|
||||
message: isVideo ? "本地演示视频封面,不请求远程片源。" : "本地演示图片,不请求远程文件。")
|
||||
})
|
||||
controller.navigationItem.prompt = "本地演示 · 未联网"
|
||||
return controller
|
||||
}
|
||||
}
|
||||
|
||||
/// 上传、记录及首屏异常的固定样例,不表示实际接口或设备状态。
|
||||
private enum DroneDockMaterialsMockScenario: String {
|
||||
case ready, uploading, uploadFailed, mixed, empty, loading, error, taskUploading, taskFailed, film
|
||||
}
|
||||
|
||||
/// 通过正式解码器构造的纯内存素材服务,没有真实网络或共享账号依赖。
|
||||
@MainActor
|
||||
private final class DroneDockMaterialsMockService: DroneDockMaterialsServing {
|
||||
private let scenario: DroneDockMaterialsMockScenario
|
||||
private let detailValue: DroneDockMaterialDetail
|
||||
private let taskValues: [[String: Any]]
|
||||
|
||||
/// 合成订单用于正式页面的入口身份,不可用于真实请求。
|
||||
var order: DroneDockHomeOrder { detailValue.order }
|
||||
|
||||
/// 固定三条拍摄记录与两处购买点位,文件状态由场景决定。
|
||||
init(scenario: DroneDockMaterialsMockScenario) throws {
|
||||
self.scenario = scenario
|
||||
let detail: [String: Any] = [
|
||||
"order_number": "LOCAL-MOCK-MATERIALS-901", "project_id": 901,
|
||||
"project_name": "模拟航拍套餐", "user_phone": "158****8888",
|
||||
"shoot_count": 5, "shot_count": scenario == .empty ? 0 : 3,
|
||||
"remaining_count": scenario == .empty ? 5 : 2, "shoot_status": "processing",
|
||||
"order_status": 20, "can_upload_film": true, "can_create_task": true,
|
||||
"spot": [["scenic_spot_id": 301, "scenic_spot_name": "三皇寨"],
|
||||
["scenic_spot_id": 302, "scenic_spot_name": "金阙云宫"]]
|
||||
]
|
||||
detailValue = try JSONDecoder().decode(DroneDockMaterialDetail.self,
|
||||
from: JSONSerialization.data(withJSONObject: detail))
|
||||
taskValues = scenario == .empty ? [] : [3, 2, 1].map { sequence in
|
||||
let taskID = 900 + sequence
|
||||
let isPagoda = sequence == 2
|
||||
let files: [[String: Any]] = [sequence * 2 - 1, sequence * 2].map { fileID in
|
||||
let status = Self.uploadStatus(scenario: scenario, sequence: sequence, fileID: fileID)
|
||||
return ["id": fileID, "file_name": String(format: "素材%02d", fileID),
|
||||
"file_type": fileID.isMultiple(of: 2) ? 1 : 2,
|
||||
"file_size": 4_194_304,
|
||||
"file_url": status == 1 ? "https://mock.invalid/media/\(taskID)/\(fileID)" : "",
|
||||
"cover_url": "", "upload_status": status,
|
||||
"failure_reason": status == 3 ? "本地演示:素材上传失败,请刷新查看最新状态" : ""]
|
||||
}
|
||||
let taskOnly = scenario == .taskUploading || scenario == .taskFailed
|
||||
var task: [String: Any] = [
|
||||
"id": taskID, "order_number": "LOCAL-MOCK-MATERIALS-901", "seq": sequence,
|
||||
"scenic_spot_id": isPagoda ? 302 : 301,
|
||||
"scenic_spot_name": isPagoda ? "金阙云宫" : "三皇寨",
|
||||
"air_line_name": isPagoda ? "云宫环绕" : "经典航线",
|
||||
"created_at": "2026-10-29 \(sequence == 3 ? "14:32:00" : sequence == 2 ? "14:10:00" : "13:45:00")",
|
||||
"flight_status": 30,
|
||||
"material_status": scenario == .taskFailed || scenario == .uploadFailed ? 3 : scenario == .ready || scenario == .film ? 1 : 2,
|
||||
"materials": taskOnly ? [] : files, "film": NSNull()
|
||||
]
|
||||
if scenario == .film, sequence == 3 {
|
||||
task["film"] = ["id": 8001, "task_id": taskID, "file_name": "已交付成片",
|
||||
"file_size": 8_388_608, "cover_url": "",
|
||||
"file_url": "https://mock.invalid/film/\(taskID)"]
|
||||
}
|
||||
return task
|
||||
}
|
||||
}
|
||||
|
||||
/// 纯内存详情;加载场景等待取消,错误场景提供明确失败。
|
||||
func detail(scenicID: Int, orderNumber: String) async throws -> DroneDockMaterialDetail {
|
||||
try validate(scenicID: scenicID, orderNumber: orderNumber)
|
||||
if scenario == .loading {
|
||||
while true { try await Task.sleep(nanoseconds: 30_000_000_000) }
|
||||
}
|
||||
if scenario == .error { throw APIError.networkFailed("本地演示:订单素材读取失败,请稍后重试") }
|
||||
try Task.checkCancellation()
|
||||
return detailValue
|
||||
}
|
||||
|
||||
/// 根据所选点位过滤内存任务,不发出 HTTP 请求。
|
||||
func tasks(scenicID: Int, orderNumber: String, spotID: Int?) async throws -> DroneDockMaterialTasks {
|
||||
try validate(scenicID: scenicID, orderNumber: orderNumber)
|
||||
try Task.checkCancellation()
|
||||
let values = taskValues.filter { spotID == nil || ($0["scenic_spot_id"] as? Int) == spotID }
|
||||
return try JSONDecoder().decode(DroneDockMaterialTasks.self, from: JSONSerialization.data(withJSONObject: [
|
||||
"order_number": orderNumber, "total": values.count, "list": values
|
||||
]))
|
||||
}
|
||||
|
||||
/// 仅就绪样例使用本地缩略图,上传中和失败仍保留页面占位样式。
|
||||
func isReady(taskID: Int, fileID: Int) -> Bool {
|
||||
guard let task = taskValues.first(where: { $0["id"] as? Int == taskID }),
|
||||
let files = task["materials"] as? [[String: Any]],
|
||||
let file = files.first(where: { $0["id"] as? Int == fileID }) else { return false }
|
||||
return file["upload_status"] as? Int == 1
|
||||
}
|
||||
|
||||
private func validate(scenicID: Int, orderNumber: String) throws {
|
||||
guard scenicID == 901, orderNumber == "LOCAL-MOCK-MATERIALS-901" else {
|
||||
throw APIError.networkFailed("本地素材演示不接受真实订单身份")
|
||||
}
|
||||
}
|
||||
|
||||
private static func uploadStatus(scenario: DroneDockMaterialsMockScenario, sequence: Int, fileID: Int) -> Int {
|
||||
switch scenario {
|
||||
case .uploading, .taskUploading: return 2
|
||||
case .uploadFailed, .taskFailed: return 3
|
||||
case .mixed:
|
||||
if sequence == 3, fileID.isMultiple(of: 2) { return 2 }
|
||||
if sequence == 2, !fileID.isMultiple(of: 2) { return 3 }
|
||||
return 1
|
||||
default: return 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 图片预览及交付入口的本地占位,不使用播放器、云端上传或相册权限。
|
||||
@MainActor
|
||||
private final class DroneDockMaterialsMockPreviewController: BaseViewController {
|
||||
private let image: UIImage?
|
||||
private let message: String
|
||||
private let imageView = UIImageView()
|
||||
private let messageLabel = UILabel()
|
||||
|
||||
/// 固定当前演示内容,防止跳入真实媒体或上传服务。
|
||||
init(title: String, image: UIImage?, message: String) {
|
||||
self.image = image
|
||||
self.message = message
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
self.title = title
|
||||
navigationItem.prompt = "本地演示 · 未联网"
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = .systemBackground
|
||||
imageView.image = image
|
||||
imageView.contentMode = .scaleAspectFit
|
||||
messageLabel.text = message
|
||||
messageLabel.numberOfLines = 0
|
||||
messageLabel.font = .systemFont(ofSize: 14)
|
||||
messageLabel.textAlignment = .center
|
||||
view.addSubview(imageView)
|
||||
view.addSubview(messageLabel)
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
imageView.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview().inset(16)
|
||||
make.top.equalTo(view.safeAreaLayoutGuide).offset(24)
|
||||
make.height.equalTo(view).multipliedBy(0.5)
|
||||
}
|
||||
messageLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(imageView.snp.bottom).offset(16)
|
||||
make.leading.trailing.equalTo(imageView)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -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 {
|
||||
|
||||
@@ -16,6 +16,7 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Int, Item>!
|
||||
private var loadTask: Task<Void, Never>?
|
||||
private var operation: LoadAction?
|
||||
private weak var deliverySheet: UINavigationController?
|
||||
|
||||
/// 使用订单号更新同一张卡片,空态和分页入口也纳入快照。
|
||||
private enum Item: Hashable { case order(String), message, more }
|
||||
@@ -92,11 +93,13 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
guard deliverySheet == nil else { return }
|
||||
load(.refresh)
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
guard deliverySheet == nil else { return }
|
||||
loadTask?.cancel()
|
||||
operation = nil
|
||||
collectionView.refreshControl?.endRefreshing()
|
||||
@@ -205,9 +208,16 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
private func showUnavailable(_ feature: String) { showAlert(title: feature, message: "该功能暂未开放") }
|
||||
|
||||
private func openDelivery(orderID: String) {
|
||||
guard operation == nil, let order = viewModel.orders.first(where: { $0.orderID == orderID }),
|
||||
guard operation == nil, presentedViewController == nil,
|
||||
let order = viewModel.orders.first(where: { $0.orderID == orderID }),
|
||||
order.canUploadFilm == true else { return }
|
||||
navigationController?.pushViewController(deliveryControllerFactory(order, viewModel.context, nil), animated: true)
|
||||
let sheet = DroneDockDeliveryEntry.makeMethodSheet(order: order, context: viewModel.context,
|
||||
controllerFactory: deliveryControllerFactory) { [weak self] in
|
||||
guard let self, self.viewIfLoaded?.window != nil else { return }
|
||||
self.load(.refresh)
|
||||
}
|
||||
deliverySheet = sheet
|
||||
present(sheet, animated: true)
|
||||
}
|
||||
|
||||
private func openMaterials(orderID: String) {
|
||||
|
||||
@@ -6,6 +6,12 @@ import UIKit
|
||||
enum DroneDockPreview {
|
||||
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
if let materials = DroneDockMaterialsSimulation.makeController(arguments: arguments) {
|
||||
return UINavigationController(rootViewController: materials)
|
||||
}
|
||||
if let simulation = DroneDockStartShootSimulation.makeController(arguments: arguments) {
|
||||
return UINavigationController(rootViewController: simulation)
|
||||
}
|
||||
// 仅打开已存在任务进行只读联调;不经过创建或召唤流程。
|
||||
if let taskArgument = arguments.first(where: { $0.hasPrefix("--dock-task-live=") }),
|
||||
let taskID = Int(taskArgument.dropFirst("--dock-task-live=".count)), taskID > 0,
|
||||
|
||||
@@ -26,12 +26,15 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
private var isApplicationActive = false
|
||||
private var automaticallyOpenedTaskID: Int?
|
||||
private let taskControllerFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private let simulationRecordsProvider: (@MainActor () -> String)?
|
||||
|
||||
/// 注入准备页业务状态和轮询等待,便于验证任务创建及页面生命周期。
|
||||
init(viewModel: DroneDockPreparationViewModel,
|
||||
taskControllerFactory: (@MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
|
||||
simulationRecordsProvider: (@MainActor () -> String)? = nil,
|
||||
planeStatusPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
|
||||
self.viewModel = viewModel
|
||||
self.simulationRecordsProvider = simulationRecordsProvider
|
||||
self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in
|
||||
DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context)
|
||||
}
|
||||
@@ -51,8 +54,42 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "拍摄准备"
|
||||
title = simulationRecordsProvider == nil ? "拍摄准备" : "拍摄准备 · 本地模拟"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
if simulationRecordsProvider != nil {
|
||||
let records = UIBarButtonItem(image: UIImage(systemName: "doc.text"), style: .plain,
|
||||
target: self, action: #selector(showSimulationRecords))
|
||||
records.accessibilityLabel = "查看模拟接口回执"
|
||||
records.accessibilityIdentifier = "drone.preparation.mock.recordsButton"
|
||||
navigationItem.rightBarButtonItem = records
|
||||
}
|
||||
#if DEBUG
|
||||
if simulationRecordsProvider == nil, DeviceCommandDebugPolicy.blocksLiveRequests,
|
||||
viewModel.isTaskSubmissionBlocked {
|
||||
let simulation = UIBarButtonItem(title: "本地模拟", style: .plain,
|
||||
target: self, action: #selector(openLocalSimulation))
|
||||
simulation.accessibilityIdentifier = "drone.preparation.mock.entry"
|
||||
navigationItem.rightBarButtonItem = simulation
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// 打开独立模拟订单,不沿用真实会话、服务或当前订单创建任务。
|
||||
@objc private func openLocalSimulation() {
|
||||
guard !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning,
|
||||
let navigationController, navigationController.topViewController === self,
|
||||
let controller = DroneDockStartShootSimulation.makePreparationController() else { return }
|
||||
navigationController.pushViewController(controller, animated: true)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// 显示内存传输记录,并明确说明其不是后端真实回执。
|
||||
@objc private func showSimulationRecords() {
|
||||
guard let simulationRecordsProvider, presentedViewController == nil,
|
||||
!isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning else { return }
|
||||
let controller = DroneDockSimulationRecordsViewController(records: simulationRecordsProvider())
|
||||
present(UINavigationController(rootViewController: controller), animated: true)
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
@@ -200,7 +237,8 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
if viewModel.errorMessage != nil {
|
||||
applySnapshot(animated: false)
|
||||
} else {
|
||||
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
|
||||
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation,
|
||||
isLocalSimulation: simulationRecordsProvider != nil)
|
||||
}
|
||||
return viewModel.pollIntervalNanoseconds
|
||||
}
|
||||
@@ -214,7 +252,8 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
@objc private func applicationWillResignActive() {
|
||||
isApplicationActive = false
|
||||
stopPlaneStatusPolling()
|
||||
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
|
||||
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation,
|
||||
isLocalSimulation: simulationRecordsProvider != nil)
|
||||
}
|
||||
|
||||
@objc private func applicationDidBecomeActive() {
|
||||
@@ -290,6 +329,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) {
|
||||
navigationItem.rightBarButtonItem?.isEnabled = !isStartingCreation && !viewModel.isCreatingTask && !viewModel.isSummoning
|
||||
guard dataSource != nil else { return }
|
||||
let previous = dataSource.snapshot()
|
||||
let existing = Set(previous.itemIdentifiers)
|
||||
@@ -312,7 +352,8 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
snapshot.appendItems([.shootResult], toSection: .shootResult)
|
||||
}
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
|
||||
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
|
||||
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation,
|
||||
isLocalSimulation: simulationRecordsProvider != nil)
|
||||
let previousPointCount = previous.sectionIdentifiers.contains(.points) ? previous.numberOfItems(inSection: .points) : 0
|
||||
let previousRouteCount = previous.sectionIdentifiers.contains(.routes) ? previous.numberOfItems(inSection: .routes) : 0
|
||||
let layoutChanged = previousPointCount != snapshot.numberOfItems(inSection: .points)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 真实拍摄任务页:进入后仅查询同一任务,展示状态与遥测,不发送飞行控制。
|
||||
/// 拍摄任务页:真实入口只读,本地模拟入口可注入开始拍摄服务验证接口流程。
|
||||
@MainActor
|
||||
final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
|
||||
@@ -20,16 +20,21 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
private var compactLayout: Bool?
|
||||
private var bottomInset: CGFloat = -1
|
||||
private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private let simulationRecordsProvider: (@MainActor () -> String)?
|
||||
private var refreshTask: Task<Void, Never>?
|
||||
private var startTask: Task<Void, Never>?
|
||||
private var requestGeneration = 0
|
||||
private var isPageVisible = false
|
||||
private var isApplicationActive = false
|
||||
private var isRequesting = false
|
||||
private var isStartingAction = false
|
||||
|
||||
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
|
||||
init(viewModel: DroneDockShootingTaskViewModel,
|
||||
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
|
||||
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
|
||||
simulationRecordsProvider: (@MainActor () -> String)? = nil) {
|
||||
self.viewModel = viewModel
|
||||
self.simulationRecordsProvider = simulationRecordsProvider
|
||||
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
|
||||
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
|
||||
context: context, order: order,
|
||||
@@ -45,18 +50,26 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
|
||||
deinit {
|
||||
refreshTask?.cancel()
|
||||
startTask?.cancel()
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
/// 使用常规导航返回准备页,不劫持返回手势或自动创建任务。
|
||||
override func setupNavigationBar() {
|
||||
title = "拍摄任务"
|
||||
title = simulationRecordsProvider == nil ? "拍摄任务" : "拍摄任务 · 本地模拟"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain,
|
||||
target: self, action: #selector(refreshTriggered))
|
||||
refresh.accessibilityLabel = "刷新任务状态"
|
||||
refresh.accessibilityIdentifier = "drone.task.remote.navigationRefresh"
|
||||
navigationItem.rightBarButtonItem = refresh
|
||||
if simulationRecordsProvider != nil {
|
||||
let records = UIBarButtonItem(image: UIImage(systemName: "doc.text"), style: .plain,
|
||||
target: self, action: #selector(showSimulationRecords))
|
||||
records.accessibilityLabel = "查看模拟接口回执"
|
||||
records.accessibilityIdentifier = "drone.task.mock.recordsButton"
|
||||
navigationItem.rightBarButtonItems = [refresh, records]
|
||||
}
|
||||
}
|
||||
|
||||
/// 顶部、中间状态和安全控制分开布局,状态切换不影响外部区域大小。
|
||||
@@ -139,7 +152,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
taskTitleLabel.font = .systemFont(ofSize: compact ? 16 : 17, weight: .semibold)
|
||||
}
|
||||
|
||||
/// 仅绑定读取、详情和已有素材入口;本轮不发送飞控指令。
|
||||
/// 模拟服务明确注入时才允许开始;真实入口仍只提供读取、详情和已有素材。
|
||||
override func bindActions() {
|
||||
statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() }
|
||||
statusView.onDetails = { [weak self] in self?.showStatusDetails() }
|
||||
@@ -166,7 +179,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
|
||||
private func applySnapshot() {
|
||||
guard isViewLoaded else { return }
|
||||
let loading = isRequesting || viewModel.isLoading
|
||||
let loading = isRequesting || viewModel.isLoading || isStartingAction || viewModel.isStartingShooting
|
||||
taskTitleLabel.text = viewModel.title
|
||||
subtitleLabel.text = viewModel.subtitle
|
||||
let telemetry = viewModel.telemetry
|
||||
@@ -178,21 +191,24 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
|
||||
statusView.apply(value, isRefreshing: loading)
|
||||
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
|
||||
navigationItem.rightBarButtonItem?.isEnabled = isPageVisible && isApplicationActive && !loading
|
||||
navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading }
|
||||
navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil
|
||||
}
|
||||
|
||||
private func primaryActionTriggered() {
|
||||
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
|
||||
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
|
||||
!isStartingAction, !viewModel.isStartingShooting else { return }
|
||||
let state = viewModel.presentation
|
||||
guard state.isActionEnabled else { return }
|
||||
switch state.action {
|
||||
case .refresh:
|
||||
refreshTaskIfVisible()
|
||||
case .start:
|
||||
startShootingIfAllowed()
|
||||
case .materials:
|
||||
guard let navigationController, navigationController.topViewController === self else { return }
|
||||
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
|
||||
case .start, .resume, .retry, .none:
|
||||
case .resume, .retry, .none:
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -204,6 +220,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
if viewModel.response != nil, let error = viewModel.errorMessage {
|
||||
texts.append("刷新失败,当前显示上次数据:\(error)")
|
||||
}
|
||||
if let error = viewModel.startErrorMessage { texts.append(error) }
|
||||
var distinct: [String] = []
|
||||
for text in texts where !distinct.contains(text) { distinct.append(text) }
|
||||
let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert)
|
||||
@@ -213,7 +230,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
|
||||
/// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。
|
||||
private func refreshTaskIfVisible() {
|
||||
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
|
||||
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
|
||||
!isStartingAction, !viewModel.isStartingShooting else { return }
|
||||
requestGeneration &+= 1
|
||||
let generation = requestGeneration
|
||||
isRequesting = true
|
||||
@@ -236,11 +254,44 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
requestGeneration &+= 1
|
||||
refreshTask?.cancel()
|
||||
refreshTask = nil
|
||||
startTask?.cancel()
|
||||
startTask = nil
|
||||
isStartingAction = false
|
||||
isRequesting = false
|
||||
viewModel.invalidate(preservingSnapshot: true)
|
||||
applySnapshot()
|
||||
}
|
||||
|
||||
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
|
||||
private func startShootingIfAllowed() {
|
||||
guard !isStartingAction, viewModel.canStartShooting else { return }
|
||||
requestGeneration &+= 1
|
||||
let generation = requestGeneration
|
||||
isStartingAction = true
|
||||
applySnapshot()
|
||||
startTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.startShooting { [weak self] in self?.applySnapshot() }
|
||||
guard self.isPageVisible, self.isApplicationActive,
|
||||
self.requestGeneration == generation, !Task.isCancelled else { return }
|
||||
self.startTask = nil
|
||||
self.isStartingAction = false
|
||||
self.applySnapshot()
|
||||
if let error = self.viewModel.startErrorMessage {
|
||||
self.showToast(error)
|
||||
} else if let error = self.viewModel.errorMessage {
|
||||
self.showToast("开始请求已受理,状态刷新失败:\(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 模拟入口专用记录页,内容由内存传输提供,不请求后端日志或设备。
|
||||
@objc private func showSimulationRecords() {
|
||||
guard let simulationRecordsProvider, presentedViewController == nil else { return }
|
||||
let controller = DroneDockSimulationRecordsViewController(records: simulationRecordsProvider())
|
||||
present(UINavigationController(rootViewController: controller), animated: true)
|
||||
}
|
||||
|
||||
@objc private func refreshTriggered() {
|
||||
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else {
|
||||
return
|
||||
@@ -260,6 +311,44 @@ final class DroneDockShootingTaskViewController: BaseViewController {
|
||||
}
|
||||
}
|
||||
|
||||
/// 以可选择的 JSON 文本展示本地模拟请求与回执,避免与真实接口联调混淆。
|
||||
@MainActor
|
||||
final class DroneDockSimulationRecordsViewController: BaseViewController {
|
||||
private let records: String
|
||||
private let textView = UITextView()
|
||||
|
||||
/// 固定展示打开时的内存记录快照。
|
||||
init(records: String) {
|
||||
self.records = records
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "本地模拟回执(未联网)"
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .done,
|
||||
target: self, action: #selector(close))
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = .systemBackground
|
||||
textView.isEditable = false
|
||||
textView.font = .monospacedSystemFont(ofSize: 12, weight: .regular)
|
||||
textView.text = records
|
||||
textView.accessibilityIdentifier = "drone.task.mock.records"
|
||||
textView.textContainerInset = UIEdgeInsets(top: 16, left: 12, bottom: 24, right: 12)
|
||||
view.addSubview(textView)
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
textView.snp.makeConstraints { make in make.edges.equalTo(view.safeAreaLayoutGuide) }
|
||||
}
|
||||
|
||||
@objc private func close() { dismiss(animated: true) }
|
||||
}
|
||||
|
||||
/// 固定底部的安全控制占位,尚未接入控制接口时不提供可执行的飞控动作。
|
||||
@MainActor
|
||||
private final class DroneDockTaskSafetyView: UIView {
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
#if DEBUG
|
||||
/// 独立的准备、召唤与开拍模拟入口;所有请求在内存中处理,不复用账号或真实网络服务。
|
||||
@MainActor
|
||||
enum DroneDockStartShootSimulation {
|
||||
/// 显式启动参数选择准备页或任务页,两个入口始终使用隔离的模拟会话。
|
||||
static func makeController(arguments: [String]) -> UIViewController? {
|
||||
let startsAtPreparation = arguments.contains("--dock-preparation-mock")
|
||||
guard startsAtPreparation || arguments.contains("--dock-start-shoot-mock") else { return nil }
|
||||
let resultArgument = arguments.first { $0.hasPrefix("--dock-start-shoot-result=") }
|
||||
let result = resultArgument.flatMap {
|
||||
DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-start-shoot-result=".count)))
|
||||
} ?? .success
|
||||
return makeFlow(result: result, startsAtPreparation: startsAtPreparation)
|
||||
}
|
||||
|
||||
/// 从正式准备页进入全新的纯内存模拟,不携带真实订单、账号或设备身份。
|
||||
static func makePreparationController() -> DroneDockRemotePreparationViewController? {
|
||||
makeFlow(result: .success, startsAtPreparation: true) as? DroneDockRemotePreparationViewController
|
||||
}
|
||||
|
||||
private static func makeFlow(result: DroneDockStartShootMockResult,
|
||||
startsAtPreparation: Bool) -> UIViewController? {
|
||||
let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation)
|
||||
let environment = APIEnvironment(baseURL: URL(string: "https://mock.invalid")!,
|
||||
webSocketURL: URL(string: "wss://mock.invalid/unused")!)
|
||||
let client = APIClient(environment: environment, session: session)
|
||||
let context = DroneDockHomeContext(userID: "local-start-shoot-mock", accountType: "store_user",
|
||||
scenicID: 128, scenicName: "本地模拟景区", storeID: 38,
|
||||
photographerName: "模拟操作员", token: "local-simulation-only")
|
||||
let orderData = Data(#"{"order_number":"LOCAL-MOCK-ORDER-901","project_id":101,"project_name":"模拟五次套餐","user_phone":"本地模拟游客","shoot_count":5,"shot_count":0,"remaining_count":5}"#.utf8)
|
||||
guard let order = try? JSONDecoder().decode(DroneDockHomeOrder.self, from: orderData) else { return nil }
|
||||
let taskFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController = { taskID, taskOrder, taskContext in
|
||||
let model = DroneDockShootingTaskViewModel(context: taskContext, taskID: taskID, order: taskOrder,
|
||||
service: DroneDockShootingAPI(client: client),
|
||||
startService: DroneDockStartShootAPI(client: client), currentContext: { context })
|
||||
return DroneDockShootingTaskViewController(viewModel: model,
|
||||
materialsControllerFactory: { _, _ in
|
||||
let unavailable = UIViewController()
|
||||
unavailable.title = "本地模拟不连接素材库"
|
||||
unavailable.view.backgroundColor = .systemBackground
|
||||
return unavailable
|
||||
},
|
||||
simulationRecordsProvider: { session.transcriptJSON })
|
||||
}
|
||||
guard startsAtPreparation else { return taskFactory(901, order, context) }
|
||||
let model = DroneDockPreparationViewModel(context: context, order: order,
|
||||
service: DroneDockPreparationAPI(client: client),
|
||||
planeStatusService: DroneDockPlaneStatusAPI(client: client),
|
||||
taskCreationService: DroneDockTaskCreationAPI(client: client),
|
||||
shootService: DroneDockShootAPI(client: client), allowsTaskSubmission: true,
|
||||
currentContext: { context })
|
||||
return DroneDockRemotePreparationViewController(viewModel: model,
|
||||
taskControllerFactory: taskFactory,
|
||||
simulationRecordsProvider: { session.transcriptJSON })
|
||||
}
|
||||
}
|
||||
|
||||
/// 模拟开拍请求的三种结果,不构成真实接口结果或设备执行反馈。
|
||||
private enum DroneDockStartShootMockResult: String {
|
||||
case success
|
||||
case businessFailure = "business-failure"
|
||||
case timeout
|
||||
}
|
||||
|
||||
/// 无任何网络转发能力的响应替身;仅接受 mock.invalid 上约定的准备、模拟召唤和开拍请求。
|
||||
private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
|
||||
private let result: DroneDockStartShootMockResult
|
||||
private let lock = NSLock()
|
||||
private var hasCreated: Bool
|
||||
private var hasSummoned: Bool
|
||||
private var hasStarted = false
|
||||
private var exchanges: [Exchange] = []
|
||||
|
||||
/// 固定当前实例结果,不能用参数切换到真实传输。
|
||||
init(result: DroneDockStartShootMockResult, requiresPreparation: Bool) {
|
||||
self.result = result
|
||||
hasCreated = !requiresPreparation
|
||||
hasSummoned = !requiresPreparation
|
||||
}
|
||||
|
||||
/// 全部本地请求及完整模拟回执;任务、设备、游客均为虚构测试身份。
|
||||
var transcriptJSON: String {
|
||||
let records = lock.withLock { exchanges }
|
||||
let items: [[String: Any]] = records.map { record in
|
||||
var item: [String: Any] = ["method": record.request.httpMethod ?? "",
|
||||
"path": record.request.url?.path ?? ""]
|
||||
if let query = record.request.url?.query { item["query"] = query }
|
||||
if let body = record.request.httpBody {
|
||||
item["request_body"] = (try? JSONSerialization.jsonObject(with: body)) ?? String(decoding: body, as: UTF8.self)
|
||||
}
|
||||
if let response = record.responseData {
|
||||
item["http_status"] = 200
|
||||
item["response_body"] = (try? JSONSerialization.jsonObject(with: response)) ?? String(decoding: response, as: UTF8.self)
|
||||
}
|
||||
if let error = record.error { item["error"] = error }
|
||||
return item
|
||||
}
|
||||
let object: [String: Any] = ["source": "local_mock", "description": "纯内存模拟,未调用后端或设备",
|
||||
"network_sent": false, "scenario": result.rawValue, "records": items]
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) else {
|
||||
return "本地模拟记录暂不可显示;没有网络请求。"
|
||||
}
|
||||
return String(decoding: data, as: UTF8.self)
|
||||
}
|
||||
|
||||
/// 模拟少量等待后返回内存响应,任何未知请求均在本机失败,绝不回退真实请求。
|
||||
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
|
||||
print("[LOCAL MOCK][Request] \(request.httpMethod ?? "") \(request.url?.absoluteString ?? "") — 不联网")
|
||||
if let body = request.httpBody { print(String(decoding: body, as: UTF8.self)) }
|
||||
do {
|
||||
try Task.checkCancellation()
|
||||
if request.httpMethod == "POST" { try await Task.sleep(nanoseconds: 400_000_000) }
|
||||
try Task.checkCancellation()
|
||||
let data = try lock.withLock { try responseData(for: request) }
|
||||
lock.withLock { exchanges.append(Exchange(request: request, responseData: data, error: nil)) }
|
||||
guard let url = request.url,
|
||||
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
print("[LOCAL MOCK][Response] \(String(decoding: data, as: UTF8.self))")
|
||||
return (data, response)
|
||||
} catch {
|
||||
let message = error is CancellationError ? "本地模拟请求取消" : error.localizedDescription
|
||||
lock.withLock { exchanges.append(Exchange(request: request, responseData: nil, error: message)) }
|
||||
print("[LOCAL MOCK][Error] \(message) — 没有网络或设备指令")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func responseData(for request: URLRequest) throws -> Data {
|
||||
guard let url = request.url, url.scheme == "https", url.host == "mock.invalid" else {
|
||||
throw URLError(.unsupportedURL)
|
||||
}
|
||||
if request.httpMethod == "GET", url.path == "/api/yf-handset-app/photog/multi-plane/project-info" {
|
||||
guard queryMatches(url, required: ["scenic_id": "128", "project_id": "101",
|
||||
"order_number": "LOCAL-MOCK-ORDER-901"]) else { throw URLError(.badURL) }
|
||||
var payload = orderData()
|
||||
payload["spot"] = [["scenic_spot_id": 301, "scenic_spot_name": "模拟点位", "available": true,
|
||||
"air_lines": [["air_line_id": 401, "air_line_name": "模拟航线",
|
||||
"available": true, "samples": []]]]]
|
||||
return try envelope(payload)
|
||||
}
|
||||
if request.httpMethod == "GET", url.path == "/api/app/airport/plane-status" {
|
||||
guard queryMatches(url, required: ["scenic_id": "128", "live_battery": "1"]) else { throw URLError(.badURL) }
|
||||
let plane: [String: Any] = ["id": 201, "name": "本地模拟无人机", "sn_number": "LOCAL-MOCK-PLANE-201",
|
||||
"online_status": 1, "work_status": 1, "work_status_label": "空闲(模拟)",
|
||||
"status_text": "本地模拟 · 电量 95%", "battery_percent": 95,
|
||||
"can_fly": true, "is_receive_order": 1]
|
||||
return try envelope(["scenic_id": 128, "connected": true, "planes": [plane],
|
||||
"recommend": plane, "poll_hint_ms": 30000])
|
||||
}
|
||||
if request.httpMethod == "POST", url.path == "/api/yf-handset-app/photog/multi-plane/tasks/create" {
|
||||
guard url.query == nil, let body = request.httpBody,
|
||||
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
|
||||
Set(object.keys) == ["scenic_id", "order_number", "scenic_spot_id", "air_line_id"],
|
||||
let values = try? JSONDecoder().decode(CreateBody.self, from: body),
|
||||
values.scenicID == 128, values.orderNumber == "LOCAL-MOCK-ORDER-901",
|
||||
values.spotID == 301, values.airLineID == 401 else { throw URLError(.badURL) }
|
||||
guard !hasCreated else { return try envelope([:], code: 100099, message: "本地模拟:任务已经创建") }
|
||||
hasCreated = true
|
||||
var payload = orderData()
|
||||
payload["task_id"] = 901
|
||||
return try envelope(payload)
|
||||
}
|
||||
if request.httpMethod == "POST", url.path == "/api/app/airport/shoot" {
|
||||
guard url.query == nil, let body = request.httpBody,
|
||||
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
|
||||
Set(object.keys) == ["id", "restart"],
|
||||
let values = try? JSONDecoder().decode(ShootBody.self, from: body),
|
||||
values.id == 901, !values.restart else { throw URLError(.badURL) }
|
||||
guard hasCreated, !hasSummoned else {
|
||||
return try envelope([:], code: 100099, message: "本地模拟:任务尚未创建或已召唤")
|
||||
}
|
||||
hasSummoned = true
|
||||
return try envelope(["order_flight_task": taskData(), "order_flight_task_id": 901,
|
||||
"plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
|
||||
"task_uuid": "LOCAL-MOCK-TASK-UUID-901",
|
||||
"ui": ["phase": "arrived_pending_start", "title": "无人机已到达(模拟)",
|
||||
"message": "本地模拟召唤成功,没有网络或设备指令。"]])
|
||||
}
|
||||
if request.httpMethod == "GET", url.path == "/api/app/airport/shooting" {
|
||||
let query = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
|
||||
guard query.filter({ $0.name == "id" }).map(\.value) == ["901"] else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
|
||||
return try envelope(shootingData())
|
||||
}
|
||||
guard request.httpMethod == "POST", url.path == "/api/app/airport/start-shoot",
|
||||
url.query == nil, let body = request.httpBody,
|
||||
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
|
||||
Set(object.keys) == ["id"],
|
||||
(try? JSONDecoder().decode(StartBody.self, from: body).id) == 901 else {
|
||||
throw URLError(.unsupportedURL)
|
||||
}
|
||||
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
|
||||
guard !hasStarted else {
|
||||
return try envelope([:], code: 100099, message: "本地模拟:该任务已开始,请读取任务状态")
|
||||
}
|
||||
switch result {
|
||||
case .businessFailure:
|
||||
return try envelope([:], code: 100099, message: "本地模拟:电量不足,暂不可开始拍摄")
|
||||
case .timeout:
|
||||
throw URLError(.timedOut)
|
||||
case .success:
|
||||
hasStarted = true
|
||||
return try envelope([
|
||||
"task_uuid": "LOCAL-MOCK-TASK-UUID-901", "order_flight_task_id": 901,
|
||||
"order_flight_task": taskData(), "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
|
||||
"ui": ["phase": "shooting", "title": "无人机正在拍摄中(模拟)",
|
||||
"message": "本地模拟开拍回执,不代表真实设备执行。", "primary_action": "shooting",
|
||||
"commands": [["command": "flighttask_pause", "label": "紧急暂停", "sub": "悬停待命"],
|
||||
["command": "return_home", "label": "立即返航", "sub": "中断任务"]]]
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
private func queryMatches(_ url: URL, required: [String: String]) -> Bool {
|
||||
let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
|
||||
return items.count == required.count && required.allSatisfy { key, value in
|
||||
items.filter { $0.name == key }.map(\.value) == [value]
|
||||
}
|
||||
}
|
||||
|
||||
private func orderData() -> [String: Any] {
|
||||
["order_number": "LOCAL-MOCK-ORDER-901", "project_id": 101, "project_name": "模拟五次套餐",
|
||||
"user_phone": "本地模拟游客", "shoot_count": 5, "shot_count": 0, "remaining_count": 5,
|
||||
"shoot_status": "processing", "order_status": 20, "can_create_task": true,
|
||||
"can_upload_film": false, "can_confirm": false, "film_count": 0]
|
||||
}
|
||||
|
||||
private func shootingData() -> [String: Any] {
|
||||
["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(),
|
||||
"scenic": ["id": 128, "name": "本地模拟景区"],
|
||||
"scenic_spot": ["id": 301, "name": "模拟点位"],
|
||||
"air_line": ["id": 401, "name": "模拟航线", "scenic_spot_id": 301],
|
||||
"header": ["order_number": "LOCAL-MOCK-ORDER-901", "title": "模拟点位 · 模拟航线",
|
||||
"tourist_label": "本地模拟,无设备指令", "package_name": "模拟套餐 · 含5次拍摄"],
|
||||
"current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-PLANE-201", "online_status": 1,
|
||||
"work_status": hasStarted ? 2 : 1, "work_status_label": hasStarted ? "拍摄中" : "空闲",
|
||||
"status_text": hasStarted ? "模拟拍摄中 · 电量95%" : "模拟就绪 · 电量95%"],
|
||||
"metrics": [["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"],
|
||||
["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"],
|
||||
["key": "signal", "value": "良好"], ["key": "satellite", "value": "36颗"]],
|
||||
"plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000],
|
||||
"execute_gate": ["can_execute": !hasStarted, "code": hasStarted ? "already_started" : "ok",
|
||||
"message": hasStarted ? "本地模拟:开拍已受理" : "本地模拟:允许验证开拍请求",
|
||||
"primary_action": hasStarted ? "shooting" : "start_shoot",
|
||||
"primary_action_label": hasStarted ? "拍摄中" : "开始拍摄"],
|
||||
"ui": ["phase": hasStarted ? "shooting" : "arrived_pending_start",
|
||||
"title": hasStarted ? "无人机正在拍摄中(模拟)" : "无人机已到达(模拟)",
|
||||
"message": hasStarted ? "本地模拟状态回查:拍摄中,未向设备发送指令。" : "点击开始拍摄,仅验证本地接口流程。"]]
|
||||
}
|
||||
|
||||
private func taskData() -> [String: Any] {
|
||||
["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128,
|
||||
"status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"]
|
||||
}
|
||||
|
||||
private func envelope(_ data: [String: Any], code: Int = 100000, message: String = "local mock success") throws -> Data {
|
||||
try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": data],
|
||||
options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
|
||||
}
|
||||
|
||||
/// 完整记录每次本地请求结果,数据不落到真实接口或共享会话中。
|
||||
private struct Exchange {
|
||||
let request: URLRequest
|
||||
let responseData: Data?
|
||||
let error: String?
|
||||
}
|
||||
|
||||
/// 创建模拟任务仍验证真实合同的四项身份,不接受其他订单或航线。
|
||||
private struct CreateBody: Decodable {
|
||||
let scenicID: Int
|
||||
let orderNumber: String
|
||||
let spotID: Int
|
||||
let airLineID: Int
|
||||
|
||||
/// 张工任务创建请求字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case scenicID = "scenic_id", orderNumber = "order_number"
|
||||
case spotID = "scenic_spot_id", airLineID = "air_line_id"
|
||||
}
|
||||
}
|
||||
|
||||
/// 召唤只接受同一模拟任务且禁止重启,不产生真实设备操作。
|
||||
private struct ShootBody: Decodable {
|
||||
let id: Int
|
||||
let restart: Bool
|
||||
}
|
||||
|
||||
/// 用强类型解码确认本地开拍请求的 id 为整数。
|
||||
private struct StartBody: Decodable {
|
||||
let id: Int
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,6 +1,34 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 缩略图上的选择圆圈,显式绘制白色勾选以免透出背景图片。
|
||||
@MainActor
|
||||
enum DroneMaterialSelectionIcon {
|
||||
/// 使用固定配色绘制选择状态,避免按钮重新应用系统 tint。
|
||||
static func image(selected: Bool, tint: UIColor, opacity: CGFloat = 1) -> UIImage {
|
||||
UIGraphicsImageRenderer(size: CGSize(width: 24, height: 24)).image { context in
|
||||
context.cgContext.setAlpha(opacity)
|
||||
let circle = UIBezierPath(ovalIn: CGRect(x: 1, y: 1, width: 22, height: 22))
|
||||
tint.set()
|
||||
if selected {
|
||||
circle.fill()
|
||||
UIColor.white.setStroke()
|
||||
let check = UIBezierPath()
|
||||
check.move(to: CGPoint(x: 6.5, y: 12))
|
||||
check.addLine(to: CGPoint(x: 10.5, y: 16))
|
||||
check.addLine(to: CGPoint(x: 17.5, y: 7.5))
|
||||
check.lineWidth = 2.2
|
||||
check.lineCapStyle = .round
|
||||
check.lineJoinStyle = .round
|
||||
check.stroke()
|
||||
} else {
|
||||
circle.lineWidth = 1.6
|
||||
circle.stroke()
|
||||
}
|
||||
}.withRenderingMode(.alwaysOriginal)
|
||||
}
|
||||
}
|
||||
|
||||
/// 素材库的订单摘要,保留拍摄履约与素材处理相互独立的表达。
|
||||
@MainActor
|
||||
final class DroneMaterialOrderCell: UICollectionViewCell {
|
||||
@@ -154,6 +182,15 @@ final class DroneMaterialSelectionCell: UICollectionViewCell {
|
||||
config.imagePadding = 6
|
||||
config.contentInsets = .zero
|
||||
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 15)
|
||||
let foreground = enabled ? DroneDockStyle.primary : UIColor(hex: 0xC2C9D4)
|
||||
config.baseForegroundColor = foreground
|
||||
config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
|
||||
var attributes = incoming
|
||||
attributes.font = .systemFont(ofSize: 12)
|
||||
attributes.foregroundColor = foreground
|
||||
return attributes
|
||||
}
|
||||
config.imageColorTransformer = UIConfigurationColorTransformer { _ in foreground }
|
||||
selectAllButton.configuration = config
|
||||
selectAllButton.isEnabled = enabled
|
||||
selectAllButton.accessibilityLabel = "全选可下载"
|
||||
@@ -181,6 +218,13 @@ final class DroneMaterialRecordHeaderView: UICollectionReusableView {
|
||||
config.imagePadding = 5
|
||||
config.contentInsets = .zero
|
||||
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13)
|
||||
config.baseForegroundColor = DroneDockStyle.primary
|
||||
config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
|
||||
var attributes = incoming
|
||||
attributes.font = .systemFont(ofSize: 12)
|
||||
attributes.foregroundColor = DroneDockStyle.primary
|
||||
return attributes
|
||||
}
|
||||
deliveryButton.configuration = config
|
||||
deliveryButton.tintColor = DroneDockStyle.primary
|
||||
deliveryButton.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside)
|
||||
@@ -193,7 +237,7 @@ final class DroneMaterialRecordHeaderView: UICollectionReusableView {
|
||||
deliveryButton.snp.makeConstraints { make in
|
||||
make.trailing.equalToSuperview()
|
||||
make.centerY.equalTo(titleLabel)
|
||||
make.height.equalTo(40)
|
||||
make.height.equalTo(44)
|
||||
}
|
||||
detailLabel.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
@@ -229,8 +273,10 @@ final class DroneMaterialCell: UICollectionViewCell {
|
||||
private let selectionButton = UIButton(type: .custom)
|
||||
private let placeholderIcon = UIImageView()
|
||||
private let videoBadge = UILabel()
|
||||
private let nameLabel = DroneDockStyle.label(size: 12, weight: .medium)
|
||||
private let statusLabel = DroneDockStyle.label(size: 11)
|
||||
private let nameLabel = DroneDockStyle.label(size: 13, weight: .medium)
|
||||
private let statusLabel = DroneDockStyle.label(size: 12)
|
||||
private let retryUploadButton = UIButton(type: .system)
|
||||
private let nameRow = UIStackView()
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
@@ -252,10 +298,23 @@ final class DroneMaterialCell: UICollectionViewCell {
|
||||
selectionButton.imageView?.contentMode = .scaleAspectFit
|
||||
selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
|
||||
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
|
||||
[thumbnail, placeholderIcon, previewButton, videoBadge, selectionButton, nameLabel, statusLabel].forEach(contentView.addSubview)
|
||||
retryUploadButton.setTitle("重试上传", for: .normal)
|
||||
retryUploadButton.titleLabel?.font = .systemFont(ofSize: 11)
|
||||
retryUploadButton.isEnabled = false
|
||||
retryUploadButton.setTitleColor(DroneDockStyle.primary.withAlphaComponent(0.55), for: .disabled)
|
||||
retryUploadButton.accessibilityHint = "当前演示不执行上传重试"
|
||||
nameRow.axis = .horizontal
|
||||
nameRow.alignment = .center
|
||||
nameRow.spacing = 6
|
||||
nameRow.addArrangedSubview(nameLabel)
|
||||
nameRow.addArrangedSubview(retryUploadButton)
|
||||
retryUploadButton.setContentHuggingPriority(.required, for: .horizontal)
|
||||
retryUploadButton.setContentCompressionResistancePriority(UILayoutPriority(999), for: .horizontal)
|
||||
retryUploadButton.snp.makeConstraints { make in make.height.equalTo(16) }
|
||||
[thumbnail, placeholderIcon, previewButton, videoBadge, selectionButton, nameRow, statusLabel].forEach(contentView.addSubview)
|
||||
thumbnail.snp.makeConstraints { make in
|
||||
make.leading.trailing.top.equalToSuperview()
|
||||
make.height.equalTo(thumbnail.snp.width).multipliedBy(0.57)
|
||||
make.height.equalTo(thumbnail.snp.width).multipliedBy(9.0 / 16.0)
|
||||
}
|
||||
previewButton.snp.makeConstraints { make in make.edges.equalTo(thumbnail) }
|
||||
placeholderIcon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(29) }
|
||||
@@ -269,13 +328,13 @@ final class DroneMaterialCell: UICollectionViewCell {
|
||||
make.top.trailing.equalTo(thumbnail)
|
||||
make.size.equalTo(44)
|
||||
}
|
||||
nameLabel.snp.makeConstraints { make in
|
||||
nameRow.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.top.equalTo(thumbnail.snp.bottom).offset(7)
|
||||
}
|
||||
statusLabel.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.top.equalTo(nameLabel.snp.bottom).offset(4)
|
||||
make.top.equalTo(nameRow.snp.bottom).offset(4)
|
||||
make.bottom.lessThanOrEqualToSuperview().inset(5)
|
||||
}
|
||||
}
|
||||
@@ -291,7 +350,10 @@ final class DroneMaterialCell: UICollectionViewCell {
|
||||
thumbnail.image = material.canPreview ? UIImage(named: material.previewAssetName) : nil
|
||||
thumbnail.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor
|
||||
placeholderIcon.isHidden = material.canPreview
|
||||
placeholderIcon.image = UIImage(systemName: material.uploadState == .failed ? "exclamationmark.icloud" : "play.fill")
|
||||
placeholderIcon.image = UIImage(systemName: material.uploadState == .failed ? "xmark.circle" : "play.fill")
|
||||
placeholderIcon.tintColor = material.uploadState == .failed ? DroneDockStyle.color(for: .red) : UIColor(hex: 0x9CA6B6)
|
||||
retryUploadButton.isHidden = material.uploadState != .failed
|
||||
retryUploadButton.accessibilityIdentifier = "drone.materials.retryUpload.\(material.id)"
|
||||
videoBadge.isHidden = material.kind != .video || !material.canPreview
|
||||
previewButton.isEnabled = material.canPreview
|
||||
previewButton.accessibilityIdentifier = "drone.materials.preview.\(material.id)"
|
||||
@@ -301,11 +363,9 @@ final class DroneMaterialCell: UICollectionViewCell {
|
||||
selectionButton.accessibilityIdentifier = "drone.materials.select.\(material.id)"
|
||||
selectionButton.accessibilityLabel = completed ? "\(material.title),演示完成,未写入相册" : "选择\(material.title)"
|
||||
selectionButton.accessibilityTraits = selected || completed ? [.button, .selected] : .button
|
||||
let symbol = UIImage(systemName: selected || completed ? "checkmark.circle.fill" : "circle",
|
||||
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22, weight: .regular))
|
||||
let tint = completed ? DroneDockStyle.success : selected ? DroneDockStyle.primary : UIColor.white
|
||||
selectionButton.setImage(symbol?.withTintColor(tint, renderingMode: .alwaysOriginal), for: .normal)
|
||||
selectionButton.setImage(symbol?.withTintColor(tint.withAlphaComponent(0.6), renderingMode: .alwaysOriginal), for: .disabled)
|
||||
selectionButton.setImage(DroneMaterialSelectionIcon.image(selected: selected || completed, tint: tint), for: .normal)
|
||||
selectionButton.setImage(DroneMaterialSelectionIcon.image(selected: selected || completed, tint: tint, opacity: 0.6), for: .disabled)
|
||||
selectionButton.imageView?.layer.shadowColor = UIColor.black.cgColor
|
||||
selectionButton.imageView?.layer.shadowOpacity = 0.22
|
||||
selectionButton.imageView?.layer.shadowRadius = 2
|
||||
@@ -375,6 +435,9 @@ final class DroneMaterialsFooterView: UIView {
|
||||
/// 返回选择状态或请求预留的交付入口。
|
||||
var onSecondaryTap: (() -> Void)?
|
||||
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
|
||||
private let trailingLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let resultIcon = UIImageView()
|
||||
private let titleRow = UIStackView()
|
||||
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let progressView = UIProgressView(progressViewStyle: .default)
|
||||
private let primaryButton = UIButton(type: .system)
|
||||
@@ -389,7 +452,19 @@ final class DroneMaterialsFooterView: UIView {
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 10
|
||||
titleLabel.numberOfLines = 2
|
||||
titleLabel.accessibilityIdentifier = "drone.materials.footer.title"
|
||||
trailingLabel.accessibilityIdentifier = "drone.materials.footer.trailing"
|
||||
trailingLabel.textAlignment = .right
|
||||
trailingLabel.setContentHuggingPriority(.required, for: .horizontal)
|
||||
trailingLabel.setContentCompressionResistancePriority(UILayoutPriority(999), for: .horizontal)
|
||||
resultIcon.contentMode = .scaleAspectFit
|
||||
resultIcon.accessibilityIdentifier = "drone.materials.footer.resultIcon"
|
||||
titleRow.axis = .horizontal
|
||||
titleRow.alignment = .center
|
||||
titleRow.spacing = 8
|
||||
[resultIcon, titleLabel, trailingLabel].forEach(titleRow.addArrangedSubview)
|
||||
detailLabel.numberOfLines = 2
|
||||
detailLabel.accessibilityIdentifier = "drone.materials.footer.detail"
|
||||
progressView.progressTintColor = DroneDockStyle.primary
|
||||
progressView.trackTintColor = UIColor(hex: 0xE8EDF7)
|
||||
progressView.accessibilityLabel = "本次演示下载完成项数"
|
||||
@@ -403,7 +478,7 @@ final class DroneMaterialsFooterView: UIView {
|
||||
secondaryButton.tintColor = DroneDockStyle.secondary
|
||||
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
|
||||
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
|
||||
[titleLabel, progressView, detailLabel, primaryButton, secondaryButton].forEach(stack.addArrangedSubview)
|
||||
[titleRow, progressView, detailLabel, primaryButton, secondaryButton].forEach(stack.addArrangedSubview)
|
||||
addSubview(divider)
|
||||
addSubview(stack)
|
||||
divider.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
|
||||
@@ -413,8 +488,9 @@ final class DroneMaterialsFooterView: UIView {
|
||||
make.bottom.equalTo(safeAreaLayoutGuide).inset(10)
|
||||
}
|
||||
primaryButton.snp.makeConstraints { make in make.height.equalTo(44) }
|
||||
secondaryButton.snp.makeConstraints { make in make.height.equalTo(24) }
|
||||
progressView.snp.makeConstraints { make in make.height.equalTo(3) }
|
||||
secondaryButton.snp.makeConstraints { make in make.height.equalTo(44).priority(999) }
|
||||
resultIcon.snp.makeConstraints { make in make.width.height.equalTo(21).priority(999) }
|
||||
progressView.snp.makeConstraints { make in make.height.equalTo(3).priority(999) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
@@ -423,9 +499,17 @@ final class DroneMaterialsFooterView: UIView {
|
||||
/// 只接受显示值,按钮语义和下载状态由控制器及 ViewModel 决定。
|
||||
func apply(title: String, detail: String, primaryTitle: String, primarySymbol: String,
|
||||
enabled: Bool, identifier: String, progress: Double?, secondaryTitle: String? = nil,
|
||||
tone: DroneDockStatusTone = .gray) {
|
||||
tone: DroneDockStatusTone = .gray, trailingText: String? = nil,
|
||||
resultSymbol: String? = nil, secondaryOutlined: Bool = false, secondaryEnabled: Bool = true) {
|
||||
titleLabel.text = title
|
||||
titleLabel.textColor = tone == .gray ? DroneDockStyle.text : DroneDockStyle.color(for: tone)
|
||||
titleLabel.textColor = DroneDockStyle.text
|
||||
titleLabel.font = .systemFont(ofSize: 13, weight: resultSymbol == nil ? .regular : .semibold)
|
||||
trailingLabel.text = trailingText
|
||||
trailingLabel.isHidden = trailingText == nil
|
||||
trailingLabel.textColor = progress == nil ? DroneDockStyle.secondary : DroneDockStyle.primary
|
||||
resultIcon.image = resultSymbol.flatMap(UIImage.init(systemName:))
|
||||
resultIcon.isHidden = resultSymbol == nil
|
||||
resultIcon.tintColor = DroneDockStyle.color(for: tone)
|
||||
detailLabel.text = detail
|
||||
detailLabel.isHidden = detail.isEmpty
|
||||
progressView.isHidden = progress == nil
|
||||
@@ -436,13 +520,47 @@ final class DroneMaterialsFooterView: UIView {
|
||||
config.imagePadding = 7
|
||||
config.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)
|
||||
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
|
||||
let primaryForeground: UIColor = enabled || progress == nil ? .white : DroneDockStyle.primary
|
||||
let primaryBackground = enabled ? DroneDockStyle.primary : UIColor(hex: 0xCEDBFC)
|
||||
config.cornerStyle = .fixed
|
||||
config.background.cornerRadius = 7
|
||||
config.background.backgroundColor = primaryBackground
|
||||
config.background.backgroundColorTransformer = UIConfigurationColorTransformer { _ in primaryBackground }
|
||||
config.baseForegroundColor = primaryForeground
|
||||
config.imageColorTransformer = UIConfigurationColorTransformer { _ in primaryForeground }
|
||||
config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
|
||||
var attributes = incoming
|
||||
attributes.font = .systemFont(ofSize: 15, weight: .medium)
|
||||
attributes.foregroundColor = primaryForeground
|
||||
return attributes
|
||||
}
|
||||
primaryButton.configuration = config
|
||||
primaryButton.isEnabled = enabled
|
||||
primaryButton.backgroundColor = enabled ? DroneDockStyle.primary : UIColor(hex: 0xCEDBFC)
|
||||
primaryButton.backgroundColor = .clear
|
||||
primaryButton.accessibilityIdentifier = identifier
|
||||
secondaryButton.setTitle(secondaryTitle, for: .normal)
|
||||
var secondary = UIButton.Configuration.plain()
|
||||
secondary.title = secondaryTitle
|
||||
secondary.image = secondaryOutlined ? UIImage(systemName: "play.rectangle") : nil
|
||||
secondary.imagePadding = 6
|
||||
secondary.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 14)
|
||||
let secondaryForeground = secondaryOutlined ? DroneDockStyle.primary : DroneDockStyle.secondary
|
||||
secondary.cornerStyle = .fixed
|
||||
secondary.background.cornerRadius = 7
|
||||
secondary.baseForegroundColor = secondaryForeground
|
||||
secondary.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
|
||||
var attributes = incoming
|
||||
attributes.font = .systemFont(ofSize: 12)
|
||||
attributes.foregroundColor = secondaryForeground
|
||||
return attributes
|
||||
}
|
||||
secondaryButton.configuration = secondary
|
||||
secondaryButton.tintColor = secondaryOutlined ? DroneDockStyle.primary : DroneDockStyle.secondary
|
||||
secondaryButton.layer.cornerRadius = 7
|
||||
secondaryButton.layer.borderWidth = secondaryOutlined ? 1 : 0
|
||||
secondaryButton.layer.borderColor = DroneDockStyle.primary.cgColor
|
||||
secondaryButton.isHidden = secondaryTitle == nil
|
||||
secondaryButton.accessibilityIdentifier = "drone.materials.continueSelecting"
|
||||
secondaryButton.isEnabled = secondaryEnabled
|
||||
secondaryButton.accessibilityIdentifier = secondaryOutlined ? "drone.materials.completedDelivery" : "drone.materials.continueSelecting"
|
||||
}
|
||||
|
||||
@objc private func primaryTapped() { onPrimaryTap?() }
|
||||
|
||||
@@ -83,7 +83,7 @@ final class DroneMaterialsViewController: BaseViewController {
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "订单素材库"
|
||||
title = "订单素材库 · 演示"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain,
|
||||
target: self, action: #selector(backTapped))
|
||||
@@ -170,6 +170,10 @@ final class DroneMaterialsViewController: BaseViewController {
|
||||
footerView.onPrimaryTap = { [weak self] in self?.performFooterAction() }
|
||||
footerView.onSecondaryTap = { [weak self] in
|
||||
guard let self else { return }
|
||||
if self.viewModel.downloadPhase == .completed {
|
||||
self.chooseCompletedDelivery()
|
||||
return
|
||||
}
|
||||
self.viewModel.clearBatch()
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
@@ -373,37 +377,41 @@ final class DroneMaterialsViewController: BaseViewController {
|
||||
footerAction = .permission
|
||||
footerView.apply(title: "无法保存到手机相册", detail: "演示相册权限未开启,恢复后请手动继续。",
|
||||
primaryTitle: "检查相册权限", primarySymbol: "lock", enabled: true,
|
||||
identifier: "drone.materials.permission", progress: nil, tone: .orange)
|
||||
identifier: "drone.materials.permission", progress: nil, tone: .blue, resultSymbol: "lock")
|
||||
return
|
||||
}
|
||||
switch viewModel.downloadPhase {
|
||||
case .idle:
|
||||
footerAction = .download
|
||||
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "仅可选择已上传素材 · 本次为本地演示",
|
||||
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "",
|
||||
primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line", enabled: viewModel.canStartDownload,
|
||||
identifier: "drone.materials.download", progress: nil)
|
||||
identifier: "drone.materials.download", progress: nil, trailingText: "仅可选择已上传素材")
|
||||
case .downloading, .awaitingSave, .saving:
|
||||
footerAction = .none
|
||||
footerView.apply(title: "本次下载\(viewModel.batchTotalCount)项 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
|
||||
footerView.apply(title: "本次下载\(viewModel.batchTotalCount)项",
|
||||
detail: "请保持本页开启,下载期间不可更改选择",
|
||||
primaryTitle: viewModel.downloadButtonTitle, primarySymbol: "arrow.triangle.2.circlepath", enabled: false,
|
||||
identifier: "drone.materials.download", progress: viewModel.batchProgress, tone: .blue)
|
||||
identifier: "drone.materials.download", progress: viewModel.batchProgress, tone: .blue,
|
||||
trailingText: "已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项")
|
||||
case .paused:
|
||||
footerAction = .resume
|
||||
footerView.apply(title: "下载已暂停 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
|
||||
footerView.apply(title: "下载已暂停",
|
||||
detail: "已完成项会保留;继续时仅处理未完成文件。",
|
||||
primaryTitle: "继续下载", primarySymbol: "play.fill", enabled: true,
|
||||
identifier: "drone.materials.continue", progress: viewModel.batchProgress, tone: .orange)
|
||||
identifier: "drone.materials.continue", progress: viewModel.batchProgress, tone: .orange,
|
||||
trailingText: "已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项", resultSymbol: "pause.circle")
|
||||
case .partialFailure:
|
||||
footerAction = .retry
|
||||
footerView.apply(title: "部分素材下载失败", detail: "演示完成\(viewModel.completedCount)项 · 失败\(viewModel.failedCount)项,重试仅处理失败项",
|
||||
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)
|
||||
identifier: "drone.materials.retry", progress: nil, secondaryTitle: "选择其他素材", tone: .orange,
|
||||
resultSymbol: "exclamationmark.triangle")
|
||||
case .completed:
|
||||
footerAction = .selectMore
|
||||
footerView.apply(title: "本次素材演示完成", detail: "\(viewModel.completedCount)项演示完成,未写入系统相册",
|
||||
primaryTitle: "继续选择素材", primarySymbol: "checkmark.circle", enabled: true,
|
||||
identifier: "drone.materials.continueSelecting", progress: nil, tone: .green)
|
||||
footerView.apply(title: "本次素材下载完成(演示)", detail: "\(viewModel.completedCount)项演示完成,未写入系统相册",
|
||||
primaryTitle: "继续选择素材", primarySymbol: "", enabled: true,
|
||||
identifier: "drone.materials.continueSelecting", progress: nil, secondaryTitle: "交付成片", tone: .green,
|
||||
resultSymbol: "checkmark.circle", secondaryOutlined: true, secondaryEnabled: delegate != nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,7 +427,7 @@ final class DroneMaterialsViewController: BaseViewController {
|
||||
case .selectMore:
|
||||
viewModel.clearBatch()
|
||||
case .permission:
|
||||
showAlert(title: "相册权限演示", message: "当前为本地演示,不读取或修改系统相册权限。可在右上角演示状态中选择“模拟相册权限恢复”,再手动继续下载。")
|
||||
showPermissionSimulation()
|
||||
case .none:
|
||||
return
|
||||
}
|
||||
@@ -432,6 +440,37 @@ final class DroneMaterialsViewController: BaseViewController {
|
||||
transferDriver.start(viewModel: viewModel) { [weak self] in self?.applySnapshot(animated: true) }
|
||||
}
|
||||
|
||||
/// 权限说明与恢复只作用于演示状态,不打开系统设置或请求真实 Photos 授权。
|
||||
private func showPermissionSimulation() {
|
||||
let alert = UIAlertController(title: "无法保存到手机相册",
|
||||
message: "相册权限未开启。当前为本地演示,不读取或修改系统相册权限;模拟恢复后请手动继续下载。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "暂不下载", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "模拟恢复权限", style: .default) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.viewModel.setPhotoPermission(.allowed)
|
||||
self.applySnapshot(animated: true)
|
||||
})
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
/// 完成底栏的交付入口先明确拍摄记录,不根据下载批次猜测目标点位。
|
||||
private func chooseCompletedDelivery() {
|
||||
guard delegate != nil, !viewModel.sections.isEmpty else { return }
|
||||
if viewModel.sections.count == 1, let record = viewModel.sections.first {
|
||||
delegate?.materialsViewController(self, didRequestDelivery: record)
|
||||
return
|
||||
}
|
||||
let sheet = UIAlertController(title: "选择拍摄记录", message: "选择需要交付成片的拍摄记录", preferredStyle: .actionSheet)
|
||||
for record in viewModel.sections {
|
||||
sheet.addAction(UIAlertAction(title: "\(record.pointName) · 记录\(record.sequenceNumber)", style: .default) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.delegate?.materialsViewController(self, didRequestDelivery: record)
|
||||
})
|
||||
}
|
||||
sheet.addAction(UIAlertAction(title: "取消", style: .cancel))
|
||||
present(sheet, animated: true)
|
||||
}
|
||||
|
||||
private func updateInteractivePopGesture() {
|
||||
guard let gesture = navigationController?.interactivePopGestureRecognizer else { return }
|
||||
if hasRunningDownload {
|
||||
|
||||
@@ -500,13 +500,15 @@ final class DronePreparationFooterView: UIView {
|
||||
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
|
||||
}
|
||||
|
||||
/// 按购买权限启用待飞任务创建;本阶段不提供无人机召唤或起飞入口。
|
||||
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false) {
|
||||
/// 绑定准备页提交许可;模拟来源仅影响文案,不改变业务权限或真实传输保护。
|
||||
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false,
|
||||
isLocalSimulation: Bool = false) {
|
||||
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
|
||||
selectionLabel.text = viewModel.selectionSummary
|
||||
selectionLabel.numberOfLines = 2
|
||||
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceTone)
|
||||
primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal)
|
||||
let title = isLocalSimulation && viewModel.canCreateTask ? "确认并召唤(模拟)" : viewModel.primaryButtonTitle
|
||||
primaryButton.setTitle(title, for: .normal)
|
||||
primaryButton.isEnabled = (viewModel.isPrimaryActionEnabled || viewModel.canOpenShootingTask) && !isRefreshing
|
||||
primaryButton.backgroundColor = primaryButton.isEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE1E7F0)
|
||||
primaryButton.setTitleColor(.white, for: .normal)
|
||||
@@ -516,6 +518,9 @@ final class DronePreparationFooterView: UIView {
|
||||
} else {
|
||||
messageLabel.text = viewModel.planeStatusErrorMessage.map { "无人机状态获取失败:\($0)" } ?? viewModel.admissionMessage
|
||||
}
|
||||
if isLocalSimulation {
|
||||
messageLabel.text = "本地模拟,不会向无人机发送指令\n" + (messageLabel.text ?? "")
|
||||
}
|
||||
messageLabel.textColor = DroneDockStyle.secondary
|
||||
refreshButton.isHidden = false
|
||||
refreshButton.isEnabled = !viewModel.isLoading && !viewModel.isCreatingTask && !viewModel.isSummoning && !isRefreshing
|
||||
|
||||
Reference in New Issue
Block a user