feat(drone-dock): 接入真实拍摄准备页

This commit is contained in:
2026-10-28 15:05:04 +08:00
parent f7a2a19dee
commit 79884cf588
12 changed files with 2041 additions and 39 deletions
@@ -6,6 +6,7 @@ final class DroneDockHomeViewController: BaseViewController {
/// 与演示数据源隔离的首页状态。
let viewModel: DroneDockHomeViewModel
private let paymentControllerFactory: (() -> UIViewController)?
private let preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)?
private var refreshTask: Task<Void, Never>?
private var isRefreshing = false
private var devicePage = 0
@@ -28,9 +29,11 @@ final class DroneDockHomeViewController: BaseViewController {
}
/// 注入可测试的数据源,不加载演示数据。
init(viewModel: DroneDockHomeViewModel, paymentControllerFactory: (() -> UIViewController)? = nil) {
init(viewModel: DroneDockHomeViewModel, paymentControllerFactory: (() -> UIViewController)? = nil,
preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
self.viewModel = viewModel
self.paymentControllerFactory = paymentControllerFactory
self.preparationControllerFactory = preparationControllerFactory
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@@ -131,7 +134,7 @@ final class DroneDockHomeViewController: BaseViewController {
if let order = self.viewModel.response?.orders.first(where: { $0.orderID == id }) {
cell.apply(homeOrder: order)
cell.onShootingTap = { [weak self] in
self?.showAlert(title: order.actionTitle ?? "拍摄订单", message: "拍摄流程暂未接入,请稍后再试")
self?.openPreparation(orderID: id)
}
cell.onMaterialsTap = { [weak self] in self?.showUnavailable("订单素材") }
}
@@ -246,6 +249,27 @@ final class DroneDockHomeViewController: BaseViewController {
showAlert(title: feature, message: "该功能暂未开放")
}
private func openPreparation(orderID: Int) {
guard !isRefreshing, let order = viewModel.response?.orders.first(where: { $0.orderID == orderID }) else { return }
guard order.primaryAction == "start_shoot" else {
showUnavailable(order.actionTitle ?? "拍摄订单")
return
}
guard DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
showAlert(title: "拍摄准备", message: "缺少订单号,请刷新工作台后重试")
return
}
let context = viewModel.context
let controller = preparationControllerFactory?(order, context) ?? DroneDockRemotePreparationViewController(
viewModel: DroneDockPreparationViewModel(
context: context, order: order,
service: DroneDockPreparationAPI(client: NetworkServices.shared.apiClient),
locationProvider: LocationProvider.shared,
currentContext: { Self.currentContext() }
))
navigationController?.pushViewController(controller, animated: true)
}
@objc private func receiptTapped() {
let controller = paymentControllerFactory?() ?? DroneDockPaymentViewController()
navigationController?.pushViewController(controller, animated: true)
@@ -0,0 +1,284 @@
import SnapKit
import UIKit
/// 读取 workbench 的真实拍摄准备页,点位和航线选择只影响页面展示。
@MainActor
final class DroneDockRemotePreparationViewController: BaseViewController {
/// 当前订单与准备页的真实读取状态。
let viewModel: DroneDockPreparationViewModel
/// 点位与航线沿用原准备页顺序,状态区单独承载加载、错误和定位说明。
private enum Section: Int, CaseIterable { case order, points, routes, status }
/// 点位与航线使用后端稳定 ID,刷新时保留有效选择。
private enum Item: Hashable { case order, point(Int), route(Int), emptyPoints, emptyRoutes, status }
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private let footerView = DronePreparationFooterView()
private let refreshControl = UIRefreshControl()
private var refreshTask: Task<Void, Never>?
private var isRefreshing = false
/// 注入只读状态源,不初始化本地演示订单或任务。
init(viewModel: DroneDockPreparationViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit { refreshTask?.cancel() }
override func setupNavigationBar() {
title = "拍摄准备"
navigationItem.backButtonDisplayMode = .minimal
}
override func setupUI() {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.showsVerticalScrollIndicator = false
collectionView.delegate = self
collectionView.accessibilityIdentifier = "drone.preparation.remote.list"
collectionView.register(DronePreparationOrderCell.self, forCellWithReuseIdentifier: "order")
collectionView.register(DronePreparationPointCell.self, forCellWithReuseIdentifier: "point")
collectionView.register(DronePreparationRouteCell.self, forCellWithReuseIdentifier: "route")
collectionView.register(DronePreparationEmptyCell.self, forCellWithReuseIdentifier: "message")
collectionView.register(DronePreparationHeadingView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "heading")
refreshControl.tintColor = DroneDockStyle.primary
collectionView.refreshControl = refreshControl
view.addSubview(collectionView)
view.addSubview(footerView)
configureDataSource()
applySnapshot(animated: false)
}
override func setupConstraints() {
collectionView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.equalToSuperview()
make.bottom.equalTo(footerView.snp.top)
}
footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
}
override func bindActions() {
refreshControl.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
footerView.onRefreshTap = { [weak self] in self?.refreshPreparation() }
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshPreparation()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
refreshTask?.cancel()
isRefreshing = false
refreshControl.endRefreshing()
viewModel.invalidate()
}
private func refreshPreparation() {
guard !isRefreshing else { return }
isRefreshing = true
refreshTask = Task { @MainActor [weak self] in
guard let self else { return }
let isInitialLoad = self.viewModel.response == nil
self.applySnapshot(animated: false)
await self.viewModel.refresh()
guard !Task.isCancelled else { return }
self.isRefreshing = false
self.refreshControl.endRefreshing()
self.applySnapshot(animated: true) { [weak self] in
guard let self else { return }
if isInitialLoad {
self.collectionView.layoutIfNeeded()
self.collectionView.setContentOffset(CGPoint(x: 0, y: -self.collectionView.adjustedContentInset.top), animated: false)
}
#if DEBUG
Task { @MainActor [weak self] in await self?.capturePreparationIfRequested() }
#endif
}
}
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
guard let self else { return nil }
switch item {
case .order:
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DronePreparationOrderCell
cell.apply(homeOrder: self.viewModel.order, progress: self.viewModel.response?.orderProgress,
usesHomeSnapshot: self.viewModel.response == nil && self.viewModel.errorMessage == nil)
return cell
case .point(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "point", for: path) as! DronePreparationPointCell
if let spot = self.viewModel.spots.first(where: { $0.id == id }) {
cell.apply(spot: spot, selected: self.viewModel.selectedSpotID == id, hasLocation: self.viewModel.hasLocation)
}
return cell
case .route(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "route", for: path) as! DronePreparationRouteCell
if let route = self.viewModel.routes.first(where: { $0.id == id }) {
cell.apply(route: route, selected: self.viewModel.selectedRouteID == id)
}
return cell
case .emptyPoints, .emptyRoutes, .status:
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell
if item == .status {
self.applyStatus(to: cell)
} else if item == .emptyPoints {
cell.apply(title: "暂无可用拍摄点", detail: "当前订单暂无拍摄点配置,请刷新重试")
} else if self.viewModel.selectedSpot == nil {
cell.apply(title: "请选择拍摄点", detail: "选择拍摄点后查看对应航线")
} else {
cell.apply(title: "暂无可用航线", detail: "请选择其他拍摄点,或稍后刷新重试")
}
return cell
}
}
dataSource.supplementaryViewProvider = { [weak self] list, kind, path in
guard let self else { return nil }
let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "heading", for: path) as! DronePreparationHeadingView
self.applyHeading(header, section: Section(rawValue: path.section))
return header
}
}
private func applyStatus(to cell: DronePreparationEmptyCell) {
if isRefreshing, viewModel.response == nil {
cell.apply(title: "正在加载", detail: "正在获取拍摄点、航线和设备状态")
} else if let error = viewModel.errorMessage {
cell.apply(title: "准备信息加载失败", detail: error + ",请下拉或点击刷新状态重试")
} else if let message = viewModel.locationMessage, viewModel.response != nil {
cell.apply(title: "位置待确认", detail: message)
} else {
cell.apply(title: "正在加载", detail: "正在获取拍摄准备信息")
}
}
private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) {
guard dataSource != nil else { return }
let previous = dataSource.snapshot()
let existing = Set(previous.itemIdentifiers)
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections(Section.allCases)
snapshot.appendItems([.order], toSection: .order)
if viewModel.response != nil, viewModel.errorMessage == nil {
snapshot.appendItems(viewModel.spots.isEmpty ? [.emptyPoints] : viewModel.spots.map { .point($0.id) }, toSection: .points)
if !viewModel.spots.isEmpty {
snapshot.appendItems(viewModel.routes.isEmpty ? [.emptyRoutes] : viewModel.routes.map { .route($0.id) }, toSection: .routes)
}
if viewModel.locationMessage != nil { snapshot.appendItems([.status], toSection: .status) }
} else {
snapshot.appendItems([.status], toSection: .status)
}
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing)
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)
|| previous.itemIdentifiers.contains(.emptyPoints) != snapshot.itemIdentifiers.contains(.emptyPoints)
|| previous.itemIdentifiers.contains(.emptyRoutes) != snapshot.itemIdentifiers.contains(.emptyRoutes)
|| previousRouteCount != snapshot.numberOfItems(inSection: .routes)
if layoutChanged { collectionView.collectionViewLayout.invalidateLayout() }
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
guard let self else { return }
let kind = UICollectionView.elementKindSectionHeader
for path in self.collectionView.indexPathsForVisibleSupplementaryElements(ofKind: kind) {
if let header = self.collectionView.supplementaryView(forElementKind: kind, at: path) as? DronePreparationHeadingView {
self.applyHeading(header, section: Section(rawValue: path.section))
}
}
completion?()
}
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, _ in
guard let self, let section = Section(rawValue: index) else { return nil }
let height: NSCollectionLayoutDimension
let width: NSCollectionLayoutDimension
switch section {
case .order: height = .estimated(100); width = .fractionalWidth(1)
case .points:
height = .absolute(self.viewModel.spots.isEmpty ? 150 : 80)
width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(160)
case .routes:
height = .absolute(self.viewModel.routes.isEmpty ? 160 : 64)
width = .fractionalWidth(1)
case .status: height = .absolute(160); width = .fractionalWidth(1)
}
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
let layout = NSCollectionLayoutSection(group: group)
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: section == .status ? 12 : 0, trailing: 16)
if section == .points, !self.viewModel.spots.isEmpty {
layout.orthogonalScrollingBehavior = .continuous
layout.interGroupSpacing = 8
}
let showsHeading = self.viewModel.response != nil && self.viewModel.errorMessage == nil
&& (section == .points || (section == .routes && !self.viewModel.spots.isEmpty))
if showsHeading {
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .points ? 46 : 64)),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
}
return layout
}
}
private func applyHeading(_ header: DronePreparationHeadingView, section: Section?) {
switch section {
case .points: header.apply(title: "拍摄点", detail: nil)
case .routes:
header.apply(title: viewModel.selectedSpot.map { "\($0.name)的航线" } ?? "拍摄航线", detail: "共 \(viewModel.routes.count) 条")
default: header.apply(title: "", detail: nil)
}
}
@objc private func refreshTriggered() { refreshPreparation() }
#if DEBUG
/// 显式联调时只保存本应用窗口,不截取其他应用内容。
private func capturePreparationIfRequested() async {
guard ProcessInfo.processInfo.arguments.contains("--dock-preparation-capture") else { return }
try? await Task.sleep(nanoseconds: 400_000_000)
guard !Task.isCancelled, !isRefreshing, let window = view.window else { return }
window.layoutIfNeeded()
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) }
do {
let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
.appendingPathComponent("DronePreparationDiagnostics", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
try image.pngData()?.write(to: directory.appendingPathComponent("preparation-real.png"), options: .atomic)
print("[DronePreparation] App window screenshot saved")
} catch { print("[DronePreparation] Screenshot failed: \(error.localizedDescription)") }
}
#endif
}
extension DroneDockRemotePreparationViewController: UICollectionViewDelegate {
/// 点位和航线只在当前成功快照中选择,刷新期间不切换旧配置。
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
!isRefreshing && viewModel.response != nil && viewModel.errorMessage == nil
}
/// 更新本地点位、航线及底部摘要,不创建拍摄任务。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard !isRefreshing, let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .point(let id): viewModel.selectSpot(id: id)
case .route(let id): viewModel.selectRoute(id: id)
default: return
}
applySnapshot(animated: true)
}
}
@@ -24,8 +24,10 @@ final class DronePreparationOrderCell: UICollectionViewCell {
packageLabel.snp.makeConstraints { make in
make.top.equalTo(customerLabel.snp.bottom).offset(8)
make.leading.equalTo(customerLabel)
make.trailing.lessThanOrEqualTo(separator.snp.leading).offset(-12)
make.bottom.equalToSuperview().inset(14)
}
packageLabel.numberOfLines = 2
separator.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(94)
make.centerY.equalToSuperview()
@@ -65,6 +67,20 @@ final class DronePreparationOrderCell: UICollectionViewCell {
accessibilityLabel = "\(order.customerName),含\(order.totalShootingCount)次拍摄,已拍摄\(order.successfulShootingCount)次,剩余\(order.remainingShootingCount)次"
}
/// 使用真实首页游客信息与准备页最新次数;准备响应中的未知次数不回填成旧值。
func apply(homeOrder: DroneDockHomeOrder, progress: DroneDockPreparationOrderProgress?, usesHomeSnapshot: Bool = false) {
let total = usesHomeSnapshot ? homeOrder.shotTotal : progress?.shotTotal
let used = usesHomeSnapshot ? homeOrder.shotUsed : progress?.shotUsed
let remaining = usesHomeSnapshot ? homeOrder.shotRemain : progress?.shotRemain
let package = progress == nil ? homeOrder.packageTitle : progress?.packageName
customerLabel.text = homeOrder.touristTitle
packageLabel.text = package?.isEmpty == false ? package : "含 \(total.map(String.init) ?? "—") 次拍摄"
completedLabel.text = "已拍摄 \(used.map(String.init) ?? "—") 次"
remainingLabel.attributedText = remainingText(remaining.map(String.init) ?? "—")
accessibilityLabel = "\(homeOrder.touristTitle),\(packageLabel.text ?? ""),已拍摄\(used.map(String.init) ?? "—")次,剩余\(remaining.map(String.init) ?? "—")次"
accessibilityIdentifier = "drone.preparation.order"
}
private func remainingText(_ value: String) -> NSAttributedString {
let text = NSMutableAttributedString(string: "剩余 ", attributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: DroneDockStyle.secondary])
text.append(NSAttributedString(string: value, attributes: [.font: UIFont.systemFont(ofSize: 26, weight: .medium), .foregroundColor: DroneDockStyle.primary]))
@@ -73,7 +89,7 @@ final class DronePreparationOrderCell: UICollectionViewCell {
}
}
/// 横向点位小卡,使用原型同款本地缩略图展示演示点位。
/// 横向点位小卡,展示点位、距离与拍摄记录,真实数据缺图时使用中性占位。
@MainActor
final class DronePreparationPointCell: UICollectionViewCell {
private let nameLabel = DroneDockStyle.label(size: 13, weight: .semibold)
@@ -127,6 +143,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
/// 仅映射模型提供的范围和次数,已拍摄的点位仍保持可选择。
func apply(point: DroneShootingPoint, selected: Bool) {
nameLabel.text = point.name
thumbnail.contentMode = .scaleAspectFill
thumbnail.image = UIImage(named: point.id == "point-jinque" ? "drone_demo_pagoda" : "drone_demo_mountain")
rangeLabel.text = point.range.title
switch point.range {
@@ -142,6 +159,34 @@ final class DronePreparationPointCell: UICollectionViewCell {
accessibilityTraits = selected ? [.button, .selected] : .button
accessibilityIdentifier = "drone.preparation.point.\(point.id)"
}
/// 距离只在请求携带有效定位时展示,服务端未提供点位图片时不使用演示山景。
func apply(spot: DroneDockPreparationSpot, selected: Bool, hasLocation: Bool) {
nameLabel.text = spot.name
thumbnail.image = UIImage(systemName: "mappin.and.ellipse")
thumbnail.contentMode = .center
thumbnail.tintColor = DroneDockStyle.secondary
if hasLocation {
rangeLabel.text = spot.distanceLabel?.isEmpty == false ? spot.distanceLabel : "距离待确认"
rangeLabel.textColor = spot.inRange == true ? DroneDockStyle.success : DroneDockStyle.secondary
} else {
rangeLabel.text = "待定位"
rangeLabel.textColor = DroneDockStyle.warning
}
locationIcon.tintColor = rangeLabel.textColor
if let status = spot.shotStatusLabel, !status.isEmpty {
countLabel.text = status
} else if let count = spot.shotCount {
countLabel.text = count == 0 ? "未拍摄" : "已拍摄 \(count) 次"
} else {
countLabel.text = "已拍摄 — 次"
}
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : .white
contentView.layer.borderColor = (selected ? DroneDockStyle.primary : DroneDockStyle.border).cgColor
accessibilityLabel = "\(spot.name),\(rangeLabel.text ?? ""),\(countLabel.text ?? "")"
accessibilityTraits = selected ? [.button, .selected] : .button
accessibilityIdentifier = "drone.preparation.point.\(spot.id)"
}
}
/// 纵向单选航线行,点击整行后由 ViewModel 保留有效选择。
@@ -197,6 +242,20 @@ final class DronePreparationRouteCell: UICollectionViewCell {
accessibilityTraits = selected ? [.button, .selected] : .button
accessibilityIdentifier = "drone.preparation.route.\(route.id)"
}
/// 展示当前真实点位的航线选择,不从行点击发起任何飞行操作。
func apply(route: DroneDockPreparationAirLine, selected: Bool) {
nameLabel.text = route.name
nameLabel.textColor = selected ? DroneDockStyle.primary : DroneDockStyle.text
routeIcon.apply(selected: selected)
checkmark.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
checkmark.tintColor = selected ? DroneDockStyle.primary : UIColor(hex: 0xA4ABB8)
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.08) : .white
separator.isHidden = selected
accessibilityLabel = route.name
accessibilityTraits = selected ? [.button, .selected] : .button
accessibilityIdentifier = "drone.preparation.route.\(route.id)"
}
}
/// 源码绘制的小航线图标,不依赖远程图片和拍摄素材。
@@ -309,6 +368,12 @@ final class DronePreparationEmptyCell: UICollectionViewCell {
titleLabel.text = isPointEmpty ? "暂无可用拍摄点" : "暂无可用航线"
detailLabel.text = isPointEmpty ? "当前景区尚未配置拍摄点" : "请选择其他拍摄点,或稍后重试"
}
/// 展示真实页面的加载、失败或未配置状态,不将请求失败描述为空数据。
func apply(title: String, detail: String) {
titleLabel.text = title
detailLabel.text = detail
}
}
/// 固定底部许可栏,独立刷新连接、范围、设备与主按钮。
@@ -422,6 +487,23 @@ final class DronePreparationFooterView: UIView {
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
}
/// 展示真实准备状态;本阶段保留召唤按钮文案,但尚不提供飞行执行入口。
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false) {
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
rangeLabel.apply(title: viewModel.rangeTitle, tone: viewModel.rangeTone)
selectionLabel.text = viewModel.selectionSummary
selectionLabel.numberOfLines = 2
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceTone)
primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal)
primaryButton.isEnabled = false
primaryButton.backgroundColor = UIColor(hex: 0xE1E7F0)
primaryButton.setTitleColor(UIColor(hex: 0x8792A5), for: .disabled)
messageLabel.text = viewModel.admissionMessage
messageLabel.textColor = DroneDockStyle.secondary
refreshButton.isHidden = false
refreshButton.isEnabled = !viewModel.isLoading && !isRefreshing
}
@objc private func primaryTapped() { onPrimaryTap?() }
@objc private func refreshTapped() { onRefreshTap?() }
}