feat(drone-dock): 接通任务召唤与状态页并固定拍摄布局

接入 plane-status、tasks/create、shoot 与 shooting,保持同一任务 ID 串接、重复提交保护和只读单次刷新。拍摄任务页固定顶部参数与底部安全控制,中间状态区域适配小屏且不滚动;同步接口记录、脱敏响应及相关测试。
This commit is contained in:
2026-10-29 17:06:49 +08:00
parent 4d763ef5d1
commit 1173207756
47 changed files with 6723 additions and 81 deletions
@@ -306,6 +306,9 @@ final class DroneDockHomeViewController: BaseViewController {
DroneDockRemotePreparationViewController(viewModel: DroneDockPreparationViewModel(
context: context, order: order,
service: DroneDockPreparationAPI(client: NetworkServices.shared.apiClient),
planeStatusService: DroneDockPlaneStatusAPI(client: NetworkServices.shared.apiClient),
taskCreationService: DroneDockTaskCreationAPI(client: NetworkServices.shared.apiClient),
shootService: DroneDockShootAPI(client: NetworkServices.shared.apiClient),
currentContext: { Self.currentContext() }
))
}
@@ -6,6 +6,22 @@ import UIKit
enum DroneDockPreview {
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
static func navigationController(arguments: [String]) -> UINavigationController? {
// 仅打开已存在任务进行只读联调;不经过创建或召唤流程。
if let taskArgument = arguments.first(where: { $0.hasPrefix("--dock-task-live=") }),
let taskID = Int(taskArgument.dropFirst("--dock-task-live=".count)), taskID > 0,
let orderArgument = arguments.first(where: { $0.hasPrefix("--dock-task-order=") }),
AppStore.shared.session.isLoggedIn {
let number = String(orderArgument.dropFirst("--dock-task-order=".count)).trimmingCharacters(in: .whitespacesAndNewlines)
if !number.isEmpty,
let data = try? JSONEncoder().encode(["order_number": number]),
let order = try? JSONDecoder().decode(DroneDockHomeOrder.self, from: data) {
let task = DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order,
context: DroneDockHomeViewController.currentContext())
let navigation = UINavigationController()
navigation.setViewControllers([DroneDockHomeViewController(), task], animated: false)
return navigation
}
}
if let argument = arguments.first(where: { $0.hasPrefix("--dock-delivery-live=") }), AppStore.shared.session.isLoggedIn {
let number = String(argument.dropFirst("--dock-delivery-live=".count))
if let data = try? JSONEncoder().encode(["order_number": number]),
@@ -29,6 +45,18 @@ enum DroneDockPreview {
return navigation
}
if arguments.contains("--dock-home-live"), AppStore.shared.session.isLoggedIn {
// 显式联调既有任务,只读取 shooting,避免为检查响应额外创建订单任务。
if let argument = arguments.first(where: { $0.hasPrefix("--dock-shooting-probe=") }),
let taskID = Int(argument.dropFirst("--dock-shooting-probe=".count)), taskID > 0 {
Task { @MainActor in
do {
_ = try await DroneDockShootingAPI(client: NetworkServices.shared.apiClient)
.shooting(taskID: taskID, liveBattery: true)
} catch {
print("[DroneDockShooting] Existing task read failed: \(error.localizedDescription)")
}
}
}
return UINavigationController(rootViewController: DroneDockHomeViewController())
}
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview", "--dock-ui-materials-preview", "--dock-ui-delivery-preview", "--dock-ui-delivery-review-preview"]
@@ -1,27 +1,41 @@
import SnapKit
import UIKit
/// 进入页面后通过 project-info 读取已购套餐、点位和航线。
/// 展示准备信息并提交召唤;业务成功后携同一任务 ID 进入真实拍摄任务页。
@MainActor
final class DroneDockRemotePreparationViewController: BaseViewController {
/// 当前订单与准备页的真实读取状态。
/// 当前订单、准备信息及任务创建状态。
let viewModel: DroneDockPreparationViewModel
/// 点位与航线沿用原准备页顺序,状态区单独承载加载和错误说明。
private enum Section: Int, CaseIterable { case order, points, routes, status }
private enum Section: Int, CaseIterable { case order, points, routes, status, creationResult, shootResult }
/// 点位与航线使用后端稳定 ID,刷新时保留有效选择。
private enum Item: Hashable { case order, point(Int), route(Int), emptyPoints, emptyRoutes, status }
private enum Item: Hashable { case order, point(Int), route(Int), emptyPoints, emptyRoutes, status, creationResult, shootResult }
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 planeStatusTask: Task<Void, Never>?
private var creationTask: Task<Void, Never>?
private var isStartingCreation = false
private let planeStatusPollDelay: @Sendable (UInt64) async throws -> Void
private var isRefreshing = false
private var isPageVisible = false
private var isApplicationActive = false
private var automaticallyOpenedTaskID: Int?
private let taskControllerFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
/// 注入只读状态源,不初始化本地演示订单或任务。
init(viewModel: DroneDockPreparationViewModel) {
/// 注入准备页业务状态和轮询等待,便于验证任务创建及页面生命周期。
init(viewModel: DroneDockPreparationViewModel,
taskControllerFactory: (@MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
planeStatusPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.viewModel = viewModel
self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in
DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context)
}
self.planeStatusPollDelay = planeStatusPollDelay
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@@ -29,7 +43,12 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit { refreshTask?.cancel() }
deinit {
refreshTask?.cancel()
planeStatusTask?.cancel()
creationTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
override func setupNavigationBar() {
title = "拍摄准备"
@@ -47,6 +66,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
collectionView.register(DronePreparationPointCell.self, forCellWithReuseIdentifier: "point")
collectionView.register(DronePreparationRouteCell.self, forCellWithReuseIdentifier: "route")
collectionView.register(DronePreparationEmptyCell.self, forCellWithReuseIdentifier: "message")
collectionView.register(DroneDockTaskCreationResultCell.self, forCellWithReuseIdentifier: "creationResult")
collectionView.register(DronePreparationHeadingView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "heading")
@@ -70,22 +90,35 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
override func bindActions() {
refreshControl.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
footerView.onRefreshTap = { [weak self] in self?.refreshPreparation() }
footerView.onPrimaryTap = { [weak self] in self?.createSelectedTask() }
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isPageVisible = true
isApplicationActive = UIApplication.shared.applicationState == .active
refreshPreparation()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
stopPlaneStatusPolling()
refreshTask?.cancel()
creationTask?.cancel()
isStartingCreation = false
isRefreshing = false
refreshControl.endRefreshing()
viewModel.invalidate()
}
private func refreshPreparation() {
guard !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning else { refreshControl.endRefreshing(); return }
startPlaneStatusPolling()
guard !isRefreshing else { return }
isRefreshing = true
refreshTask = Task { @MainActor [weak self] in
@@ -109,13 +142,93 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
}
}
/// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。
private func createSelectedTask() {
guard !isRefreshing, !isStartingCreation else { return }
if viewModel.canOpenShootingTask {
_ = openShootingTask(automatically: false)
return
}
guard viewModel.isPrimaryActionEnabled else { return }
isStartingCreation = true
applySnapshot(animated: false)
creationTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.prepareAndSummon { [weak self] in self?.applySnapshot(animated: false) }
guard !Task.isCancelled else { return }
self.isStartingCreation = false
if self.openShootingTask(automatically: true) { return }
self.applySnapshot(animated: true) { [weak self] in
guard let self,
let path = self.dataSource.indexPath(for: .shootResult) ?? self.dataSource.indexPath(for: .creationResult) else { return }
self.collectionView.scrollToItem(at: path, at: .top, animated: true)
}
}
}
/// 只在准备页可见且召唤已成功时导航一次;返回后允许主动查看同一任务。
@discardableResult
private func openShootingTask(automatically: Bool) -> Bool {
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
let taskID = viewModel.createdTask?.taskID,
let navigationController, navigationController.topViewController === self,
!automatically || automaticallyOpenedTaskID != taskID else { return false }
automaticallyOpenedTaskID = taskID
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
navigationController.pushViewController(controller, animated: true)
return true
}
/// 设备请求与购买快照各自更新,轮询不重载列表或改变点位、航线选择。
private func startPlaneStatusPolling() {
guard isPageVisible, isApplicationActive else { return }
stopPlaneStatusPolling()
let delay = planeStatusPollDelay
planeStatusTask = Task { @MainActor [weak self] in
while !Task.isCancelled {
guard let interval = await self?.refreshPlaneStatusIfVisible() else { return }
do { try await delay(interval) }
catch { return }
}
}
}
private func refreshPlaneStatusIfVisible() async -> UInt64? {
guard isPageVisible, isApplicationActive, !Task.isCancelled else { return nil }
await viewModel.refreshPlaneStatus()
guard isPageVisible, isApplicationActive, !Task.isCancelled else { return nil }
if viewModel.errorMessage != nil {
applySnapshot(animated: false)
} else {
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
}
return viewModel.pollIntervalNanoseconds
}
private func stopPlaneStatusPolling() {
planeStatusTask?.cancel()
planeStatusTask = nil
viewModel.invalidatePlaneStatus()
}
@objc private func applicationWillResignActive() {
isApplicationActive = false
stopPlaneStatusPolling()
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
}
@objc private func applicationDidBecomeActive() {
isApplicationActive = true
startPlaneStatusPolling()
}
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, summary: self.viewModel.projectInfo?.order,
cell.apply(homeOrder: self.viewModel.order, summary: self.viewModel.latestOrderSummary,
usesHomeSnapshot: self.viewModel.projectInfo == nil && self.viewModel.errorMessage == nil)
return cell
case .point(let id):
@@ -130,6 +243,20 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
cell.apply(route: route, selected: self.viewModel.selectedRouteID == id)
}
return cell
case .creationResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.apply(task: self.viewModel.createdTask, errorMessage: self.viewModel.taskCreationErrorMessage,
outcomeUnknown: self.viewModel.taskCreationOutcomeUnknown)
return cell
case .shootResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.applyShoot(taskID: self.viewModel.createdTask?.taskID,
dataJSON: self.viewModel.shootDataJSON,
errorMessage: self.viewModel.shootErrorMessage,
isLoading: self.viewModel.isSummoning,
hasSucceeded: self.viewModel.shootResponse != nil,
outcomeUnknown: self.viewModel.summonOutcomeUnknown)
return cell
case .emptyPoints, .emptyRoutes, .status:
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell
if item == .status {
@@ -177,8 +304,15 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
} else {
snapshot.appendItems([.status], toSection: .status)
}
if viewModel.createdTask != nil || (viewModel.errorMessage == nil && viewModel.projectInfo != nil && viewModel.taskCreationErrorMessage != nil) {
snapshot.appendItems([.creationResult], toSection: .creationResult)
}
if viewModel.createdTask != nil,
viewModel.isSummoning || viewModel.shootResponse != nil || viewModel.shootErrorMessage != nil {
snapshot.appendItems([.shootResult], toSection: .shootResult)
}
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing)
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
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)
@@ -212,11 +346,13 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
height = self.viewModel.routes.isEmpty ? .absolute(160) : .estimated(64)
width = .fractionalWidth(1)
case .status: height = .absolute(160); width = .fractionalWidth(1)
case .creationResult: height = .absolute(380); width = .fractionalWidth(1)
case .shootResult: height = .absolute(420); 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)
layout.contentInsets = NSDirectionalEdgeInsets(top: section == .shootResult ? 12 : 0, leading: 16, bottom: section == .status ? 12 : 0, trailing: 16)
if section == .points, !self.viewModel.spots.isEmpty {
layout.orthogonalScrollingBehavior = .continuous
layout.interGroupSpacing = 8
@@ -265,7 +401,9 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
extension DroneDockRemotePreparationViewController: UICollectionViewDelegate {
/// 点位和航线只在当前成功快照中选择,刷新期间不切换旧配置。
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard !isRefreshing, viewModel.projectInfo != nil, viewModel.errorMessage == nil,
guard !isRefreshing, !isStartingCreation, !viewModel.isCreatingTask,
viewModel.createdTask == nil, !viewModel.taskCreationOutcomeUnknown,
viewModel.projectInfo != nil, viewModel.errorMessage == nil,
let item = dataSource.itemIdentifier(for: indexPath) else { return false }
switch item {
case .point(let id): return viewModel.spots.first { $0.id == id }?.available == true
@@ -276,7 +414,9 @@ extension DroneDockRemotePreparationViewController: UICollectionViewDelegate {
/// 更新本地点位、航线及底部摘要,不创建拍摄任务。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard !isRefreshing, let item = dataSource.itemIdentifier(for: indexPath) else { return }
guard !isRefreshing, !isStartingCreation, !viewModel.isCreatingTask,
viewModel.createdTask == nil, !viewModel.taskCreationOutcomeUnknown,
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)
@@ -0,0 +1,15 @@
import UIKit
/// 组装真实拍摄任务页;构造时不发请求,页面出现后才读取同一任务。
@MainActor
enum DroneDockShootingTaskEntry {
/// 使用当前共享网络服务读取已创建、已召唤任务,不创建或控制无人机。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
context: context, taskID: taskID, order: order,
service: DroneDockShootingAPI(client: NetworkServices.shared.apiClient),
currentContext: { DroneDockHomeViewController.currentContext() }
))
}
}
@@ -0,0 +1,344 @@
import SnapKit
import UIKit
/// 真实拍摄任务页:进入后仅查询同一任务,展示状态与遥测,不发送飞行控制。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
let viewModel: DroneDockShootingTaskViewModel
private let topView = UIView()
private let summaryView = UIView()
private let taskTitleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
private let subtitleLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let feedPlaceholder = DroneDockTaskFeedPlaceholderView()
private let telemetryView = DroneShootingTaskTelemetryView()
private let statusView = DroneDockTaskStatusView()
private let safetyView = DroneDockTaskSafetyView()
private var summaryHeight: Constraint?
private var safetyHeight: Constraint?
private var compactLayout: Bool?
private var bottomInset: CGFloat = -1
private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private var refreshTask: Task<Void, Never>?
private var requestGeneration = 0
private var isPageVisible = false
private var isApplicationActive = false
private var isRequesting = false
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
self.viewModel = viewModel
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
service: DroneDockMaterialsAPI(client: NetworkServices.shared.apiClient),
currentContext: { DroneDockHomeViewController.currentContext() }))
}
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit {
refreshTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
/// 使用常规导航返回准备页,不劫持返回手势或自动创建任务。
override func setupNavigationBar() {
title = "拍摄任务"
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
}
/// 顶部、中间状态和安全控制分开布局,状态切换不影响外部区域大小。
override func setupUI() {
view.backgroundColor = .white
topView.accessibilityIdentifier = "drone.task.remote.top"
summaryView.accessibilityIdentifier = "drone.task.remote.summary"
statusView.accessibilityIdentifier = "drone.task.remote.stateContainer"
safetyView.accessibilityIdentifier = "drone.task.remote.safety"
view.addSubview(topView)
view.addSubview(statusView)
view.addSubview(safetyView)
topView.addSubview(summaryView)
summaryView.addSubview(taskTitleLabel)
summaryView.addSubview(subtitleLabel)
taskTitleLabel.numberOfLines = 1
taskTitleLabel.lineBreakMode = .byTruncatingTail
taskTitleLabel.accessibilityIdentifier = "drone.task.remote.title"
subtitleLabel.numberOfLines = 1
subtitleLabel.lineBreakMode = .byTruncatingTail
subtitleLabel.accessibilityIdentifier = "drone.task.remote.subtitle"
topView.addSubview(feedPlaceholder)
topView.addSubview(telemetryView)
telemetryView.accessibilityIdentifier = "drone.task.remote.telemetry"
telemetryView.configureFixedLayout(compact: false)
applySnapshot()
}
/// 图传保持 16:9,底部贴安全区,中间占满剩余空间且没有滚动容器。
override func setupConstraints() {
topView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.equalToSuperview()
}
summaryView.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
summaryHeight = make.height.equalTo(60).constraint
}
taskTitleLabel.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.bottom.equalTo(summaryView.snp.centerY).offset(-1)
}
subtitleLabel.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.top.equalTo(summaryView.snp.centerY).offset(2)
}
feedPlaceholder.snp.makeConstraints { make in
make.top.equalTo(summaryView.snp.bottom)
make.leading.trailing.equalToSuperview()
make.height.equalTo(feedPlaceholder.snp.width).multipliedBy(9.0 / 16.0)
}
telemetryView.snp.makeConstraints { make in
make.top.equalTo(feedPlaceholder.snp.bottom)
make.leading.trailing.bottom.equalToSuperview()
}
safetyView.snp.makeConstraints { make in
make.leading.trailing.bottom.equalToSuperview()
safetyHeight = make.height.equalTo(104).constraint
}
statusView.snp.makeConstraints { make in
make.top.equalTo(topView.snp.bottom)
make.bottom.equalTo(safetyView.snp.top)
make.leading.trailing.equalToSuperview()
}
}
/// 只按设备可用尺寸调整固定区域,数据、错误和加载状态不会改变它们的高度。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let availableHeight = view.bounds.height - view.safeAreaInsets.top - view.safeAreaInsets.bottom
let compact = availableHeight < 680
let inset = view.safeAreaInsets.bottom
guard compactLayout != compact || bottomInset != inset else { return }
compactLayout = compact
bottomInset = inset
summaryHeight?.update(offset: compact ? 44 : 60)
safetyHeight?.update(offset: (compact ? 90 : 104) + inset)
telemetryView.configureFixedLayout(compact: compact)
safetyView.configure(compact: compact)
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() }
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification, object: nil)
}
/// 每次完整进入任务页只查询一次,不定时重读同一任务。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
isApplicationActive = UIApplication.shared.applicationState == .active
refreshTaskIfVisible()
}
/// 离页立即取消未完成的读取,使迟到响应失效。
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
cancelRefresh()
}
private func applySnapshot() {
guard isViewLoaded else { return }
let loading = isRequesting || viewModel.isLoading
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle
let telemetry = viewModel.telemetry
telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText],
isStale: loading || viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric")
let value = loading ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
statusView.apply(value)
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItem?.isEnabled = isPageVisible && isApplicationActive && !loading
}
private func primaryActionTriggered() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
let state = viewModel.presentation
guard state.isActionEnabled else { return }
switch state.action {
case .refresh:
refreshTaskIfVisible()
case .materials:
guard let navigationController, navigationController.topViewController === self else { return }
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
case .start, .resume, .none:
break
}
}
private func showStatusDetails() {
guard isPageVisible, isApplicationActive, presentedViewController == nil else { return }
let state = viewModel.presentation
let texts = [state.title, state.message, state.deviceStatus].filter { !$0.isEmpty && $0 != "—" }
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)
alert.addAction(UIAlertAction(title: "关闭", style: .cancel))
present(alert, animated: true)
}
/// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。
private func refreshTaskIfVisible() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
requestGeneration &+= 1
let generation = requestGeneration
isRequesting = true
applySnapshot()
refreshTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.refresh()
guard self.isPageVisible, self.isApplicationActive,
self.requestGeneration == generation, !Task.isCancelled else { return }
self.refreshTask = nil
self.isRequesting = false
self.applySnapshot()
}
}
private func cancelRefresh() {
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
isRequesting = false
viewModel.invalidate()
applySnapshot()
}
@objc private func refreshTriggered() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else {
return
}
refreshTaskIfVisible()
}
@objc private func applicationWillResignActive() {
isApplicationActive = false
cancelRefresh()
}
@objc private func applicationDidBecomeActive() {
guard !isApplicationActive else { return }
isApplicationActive = true
refreshTaskIfVisible()
}
}
/// 固定底部的安全控制占位,尚未接入控制接口时不提供可执行的飞控动作。
@MainActor
private final class DroneDockTaskSafetyView: UIView {
private let header = DroneDockStyle.label("安全控制", size: 11, color: DroneDockStyle.secondary)
private let pauseButton = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: UIColor(hex: 0xEC982A), filled: true)
private let returnButton = DroneShootingTaskSafetyButton(symbol: "arrow.uturn.backward", color: UIColor(hex: 0xD85762), filled: false)
private let buttons = UIStackView()
private var headerTop: Constraint?
private var headerHeight: Constraint?
private var buttonGap: Constraint?
private var buttonHeight: Constraint?
/// 复用安全按钮样式,按钮始终保留占位与明确的不可用状态。
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
let divider = UIView()
divider.backgroundColor = DroneDockStyle.border
addSubview(divider)
divider.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
make.height.equalTo(0.5)
}
header.textAlignment = .center
addSubview(header)
buttons.axis = .horizontal
buttons.spacing = 8
buttons.distribution = .fillEqually
buttons.addArrangedSubview(pauseButton)
buttons.addArrangedSubview(returnButton)
addSubview(buttons)
pauseButton.accessibilityIdentifier = "drone.task.remote.pause"
returnButton.accessibilityIdentifier = "drone.task.remote.return"
pauseButton.apply(title: "紧急暂停", subtitle: "暂不可用", enabled: false)
returnButton.apply(title: "立即返航", subtitle: "暂不可用", enabled: false)
header.snp.makeConstraints { make in
headerTop = make.top.equalToSuperview().offset(10).constraint
make.leading.trailing.equalToSuperview().inset(16)
headerHeight = make.height.equalTo(14).constraint
}
buttons.snp.makeConstraints { make in
buttonGap = make.top.equalTo(header.snp.bottom).offset(8).constraint
make.leading.trailing.equalToSuperview().inset(16)
buttonHeight = make.height.equalTo(62).constraint
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 高度仅依设备空间切换,不随任务状态、按钮文案或网络响应变化。
func configure(compact: Bool) {
headerTop?.update(offset: compact ? 8 : 10)
headerHeight?.update(offset: compact ? 12 : 14)
buttonGap?.update(offset: compact ? 6 : 8)
buttonHeight?.update(offset: compact ? 56 : 62)
}
}
/// 真实图传尚未接入时的中性占位,不使用演示图片、播放进度或虚假连接状态。
@MainActor
private final class DroneDockTaskFeedPlaceholderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(hex: 0x172033)
accessibilityIdentifier = "drone.task.remote.feedPlaceholder"
let icon = UIImageView(image: UIImage(systemName: "video.slash"))
icon.contentMode = .scaleAspectFit
icon.tintColor = UIColor.white.withAlphaComponent(0.6)
let title = DroneDockStyle.label("图传暂未接入", size: 15, weight: .medium, color: .white)
let detail = DroneDockStyle.label("任务状态将在下方更新", size: 12, color: .white.withAlphaComponent(0.65))
let stack = UIStackView(arrangedSubviews: [icon, title, detail])
stack.axis = .vertical
stack.spacing = 9
stack.alignment = .center
addSubview(stack)
icon.snp.makeConstraints { make in make.size.equalTo(31) }
stack.snp.makeConstraints { make in
make.center.equalToSuperview()
make.leading.greaterThanOrEqualToSuperview().offset(20)
make.trailing.lessThanOrEqualToSuperview().offset(-20)
}
isAccessibilityElement = true
accessibilityLabel = "图传暂未接入,任务状态将在下方更新"
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
@@ -0,0 +1,80 @@
import SnapKit
import UIKit
/// 在准备页展示任务创建或召唤请求的回执,保留 data 原文结构并支持滚动与选择文本。
@MainActor
final class DroneDockTaskCreationResultCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let responseView = UITextView()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = DroneDockStyle.background
contentView.layer.cornerRadius = 10
titleLabel.numberOfLines = 0
detailLabel.numberOfLines = 0
responseView.backgroundColor = .clear
responseView.isEditable = false
responseView.isSelectable = true
responseView.alwaysBounceVertical = true
responseView.textContainerInset = .zero
responseView.textContainer.lineFragmentPadding = 0
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
[titleLabel, detailLabel, responseView].forEach(contentView.addSubview)
titleLabel.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview().inset(12)
}
detailLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(6)
make.leading.trailing.equalTo(titleLabel)
}
responseView.snp.makeConstraints { make in
make.top.equalTo(detailLabel.snp.bottom).offset(12)
make.leading.trailing.equalTo(titleLabel)
make.bottom.equalToSuperview().inset(12)
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 成功保留完整 data,失败显示真实错误,不构造任务 ID 或成功响应。
func apply(task: DroneDockCreatedTask?, errorMessage: String?, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
if let task {
titleLabel.text = "任务已创建 · ID \(task.taskID)"
titleLabel.textColor = DroneDockStyle.success
detailLabel.text = "tasks/create 返回的 data"
responseView.font = .monospacedSystemFont(ofSize: 12, weight: .regular)
if responseView.text != task.dataJSON { responseView.text = task.dataJSON }
} else {
titleLabel.text = outcomeUnknown ? "任务创建结果待确认" : "任务创建未成功"
titleLabel.textColor = DroneDockStyle.warning
detailLabel.text = outcomeUnknown ? "请先核对订单任务,避免重复创建" : "接口返回的错误信息"
responseView.font = .systemFont(ofSize: 14)
responseView.text = errorMessage
}
responseView.textColor = DroneDockStyle.text
}
/// 展示 shoot 回执;提交成功不代表无人机已到达,结果未知不能引导直接重发。
func applyShoot(taskID: Int?, dataJSON: String?, errorMessage: String?, isLoading: Bool,
hasSucceeded: Bool, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.shootResponse"
let suffix = taskID.map { " · ID \($0)" } ?? ""
let title: String
if isLoading { title = "正在召唤无人机" }
else if hasSucceeded { title = "召唤请求已提交" }
else { title = outcomeUnknown ? "召唤结果待核对" : "召唤请求未成功" }
titleLabel.text = title + suffix
titleLabel.textColor = hasSucceeded ? DroneDockStyle.success : errorMessage == nil ? DroneDockStyle.text : DroneDockStyle.warning
if isLoading { detailLabel.text = "正在为已创建的任务提交召唤请求" }
else if hasSucceeded { detailLabel.text = "shoot 返回信息;飞行进度以任务状态为准" }
else { detailLabel.text = outcomeUnknown ? "请先核对任务状态,避免重复发送召唤" : "任务已保留,可重试召唤" }
responseView.font = dataJSON == nil ? .systemFont(ofSize: 14) : .monospacedSystemFont(ofSize: 12, weight: .regular)
let text = dataJSON ?? errorMessage ?? (hasSucceeded ? "接口已返回业务成功,未提供可展示的 data。" : "")
if responseView.text != text { responseView.text = text }
responseView.textColor = DroneDockStyle.text
}
}
@@ -0,0 +1,243 @@
import SnapKit
import UIKit
/// 固定区域内组合任务状态与主操作,根据可用高度收紧内容,不滚动或改变外部尺寸。
@MainActor
final class DroneDockTaskStatusView: UIView {
/// 当前状态的主操作,由页面协调执行,不在组件中调用接口。
var onPrimaryAction: (() -> Void)?
/// 展开完整状态说明,由页面提供详情展示。
var onDetails: (() -> Void)?
/// 当前内容采用的字号和间距参考比例,始终介于 0.8 与 1。
private(set) var effectiveScale: CGFloat = 1
/// 中间区域不足以显示常规内容时采用紧凑布局。
private(set) var usesCompactLayout = false
private let contentStack = UIStackView()
private let titleRow = UIView()
private let iconView = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold)
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
private let deviceLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let actionRow = UIView()
private let primaryButton = UIButton(type: .system)
private let detailsButton = UIButton(type: .system)
private var presentation: DroneDockTaskPresentation?
private var contentTop: Constraint?
private var contentLeading: Constraint?
private var contentTrailing: Constraint?
private var iconSize: Constraint?
private var titleLeading: Constraint?
private var titleRowHeight: Constraint?
private var messageHeight: Constraint?
private var deviceHeight: Constraint?
/// 创建稳定的标题、说明、设备摘要与操作槽,所有状态复用同一组视图。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 外部容器决定高度;状态内容不会通过固有尺寸推高底部安全区。
override var intrinsicContentSize: CGSize {
CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
/// 更新真实状态文案与动作许可,不补造百分比或自行推导飞行阶段。
func apply(_ presentation: DroneDockTaskPresentation) {
self.presentation = presentation
titleLabel.text = presentation.title
messageLabel.text = presentation.message
deviceLabel.text = presentation.deviceStatus
let style = Self.style(for: presentation.phase)
iconView.image = UIImage(systemName: style.symbol)
iconView.tintColor = style.color
let actionTitle = DroneDockHomeMetric.usableText(presentation.actionTitle)
primaryButton.isHidden = presentation.action == .none || actionTitle == nil
primaryButton.setTitle(actionTitle, for: .normal)
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden
primaryButton.backgroundColor = primaryButton.isEnabled
? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.35)
primaryButton.accessibilityIdentifier = presentation.action == .refresh
? "drone.task.remote.refresh" : "drone.task.remote.primary"
setNeedsLayout()
}
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
override func layoutSubviews() {
updateContentLayout()
super.layoutSubviews()
}
private func setupUI() {
backgroundColor = .white
contentStack.axis = .vertical
contentStack.alignment = .fill
contentStack.spacing = 10
addSubview(contentStack)
contentStack.addArrangedSubview(titleRow)
contentStack.addArrangedSubview(messageLabel)
contentStack.addArrangedSubview(deviceLabel)
contentStack.addArrangedSubview(actionRow)
titleRow.addSubview(iconView)
titleRow.addSubview(titleLabel)
iconView.contentMode = .scaleAspectFit
titleLabel.numberOfLines = 2
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.accessibilityTraits = .header
titleLabel.accessibilityIdentifier = "drone.task.remote.statusTitle"
messageLabel.numberOfLines = 3
messageLabel.lineBreakMode = .byTruncatingTail
messageLabel.accessibilityIdentifier = "drone.task.remote.statusMessage"
deviceLabel.numberOfLines = 1
deviceLabel.lineBreakMode = .byTruncatingTail
deviceLabel.accessibilityIdentifier = "drone.task.remote.deviceStatus"
actionRow.addSubview(primaryButton)
actionRow.addSubview(detailsButton)
primaryButton.layer.cornerRadius = 9
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled)
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
detailsButton.setTitle("详情", for: .normal)
detailsButton.setTitleColor(DroneDockStyle.primary, for: .normal)
detailsButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
detailsButton.backgroundColor = DroneDockStyle.background
detailsButton.layer.cornerRadius = 9
detailsButton.accessibilityIdentifier = "drone.task.remote.details"
detailsButton.accessibilityLabel = "查看完整任务状态"
detailsButton.addTarget(self, action: #selector(detailsTapped), for: .touchUpInside)
}
private func setupConstraints() {
contentStack.snp.makeConstraints { make in
contentTop = make.top.equalToSuperview().offset(12).constraint
contentLeading = make.leading.equalToSuperview().offset(16).constraint
contentTrailing = make.trailing.equalToSuperview().inset(16).constraint
}
titleRow.snp.makeConstraints { make in titleRowHeight = make.height.equalTo(36).priority(999).constraint }
iconView.snp.makeConstraints { make in
make.leading.centerY.equalToSuperview()
iconSize = make.size.equalTo(36).constraint
}
titleLabel.snp.makeConstraints { make in
titleLeading = make.leading.equalTo(iconView.snp.trailing).offset(10).constraint
make.trailing.centerY.equalToSuperview()
}
messageLabel.snp.makeConstraints { make in messageHeight = make.height.equalTo(34).priority(999).constraint }
deviceLabel.snp.makeConstraints { make in deviceHeight = make.height.equalTo(16).priority(999).constraint }
actionRow.snp.makeConstraints { make in make.height.equalTo(44) }
detailsButton.snp.makeConstraints { make in
make.top.trailing.bottom.equalToSuperview()
make.width.equalTo(64)
}
primaryButton.snp.makeConstraints { make in
make.top.leading.bottom.equalToSuperview()
make.trailing.equalTo(detailsButton.snp.leading).offset(-8)
}
}
private func updateContentLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
let isExtreme = bounds.height < 120
let horizontalInset: CGFloat = isExtreme ? 12 : 16
let verticalInset: CGFloat = isExtreme ? 6 : 12
let width = max(1, bounds.width - horizontalInset * 2)
let availableHeight = max(1, bounds.height - verticalInset * 2)
let message = DroneDockHomeMetric.usableText(presentation.message)
let hasMessage = message != nil && message != DroneDockHomeMetric.usableText(presentation.title)
let device = DroneDockHomeMetric.usableText(presentation.deviceStatus)
let hasDevice = device != nil && device != "—"
let naturalTitle = max(36, Self.textHeight(presentation.title, font: .systemFont(ofSize: 22, weight: .semibold),
width: width - 46, lines: 2))
let naturalMessage = hasMessage ? Self.textHeight(message, font: .systemFont(ofSize: 14), width: width, lines: 3) : 0
let naturalDevice = hasDevice ? UIFont.systemFont(ofSize: 12).lineHeight : 0
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10
let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps
effectiveScale = min(1, max(0.8, availableHeight / max(1, naturalHeight)))
usesCompactLayout = bounds.height < 190 || naturalHeight * effectiveScale > availableHeight
// 先收紧图标和间距;只有不足九成空间时才缩小文字。
let fontScale: CGFloat = effectiveScale >= 0.9 ? 1 : effectiveScale / 0.9
titleLabel.font = .systemFont(ofSize: max(17, 22 * fontScale), weight: .semibold)
messageLabel.font = .systemFont(ofSize: max(12, 14 * fontScale))
deviceLabel.font = .systemFont(ofSize: 12)
let icon: CGFloat = isExtreme ? 20 : usesCompactLayout ? 24 : 36 * effectiveScale
let gap: CGFloat = isExtreme ? 4 : max(4, 10 * effectiveScale)
let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale
titleLabel.numberOfLines = usesCompactLayout ? 1 : 2
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
messageLabel.isHidden = !hasMessage || isExtreme
deviceLabel.isHidden = !hasDevice || usesCompactLayout
let titleWidth = max(1, width - icon - titleGap)
var titleHeight = max(icon, Self.textHeight(presentation.title, font: titleLabel.font,
width: titleWidth, lines: titleLabel.numberOfLines))
var messageLineCount = messageLabel.numberOfLines
var bodyHeight = messageLabel.isHidden ? 0 : Self.textHeight(message, font: messageLabel.font,
width: width, lines: messageLineCount)
let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight)
var contentHeight: CGFloat {
titleHeight + bodyHeight + deviceTextHeight + 44
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap
}
while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden {
messageLineCount -= 1
bodyHeight = Self.textHeight(message, font: messageLabel.font, width: width, lines: messageLineCount)
}
if contentHeight > availableHeight && titleLabel.numberOfLines > 1 {
titleLabel.numberOfLines = 1
titleHeight = max(icon, ceil(titleLabel.font.lineHeight))
}
if contentHeight > availableHeight && !messageLabel.isHidden {
messageLabel.isHidden = true
bodyHeight = 0
}
messageLabel.numberOfLines = messageLineCount
let top = verticalInset + max(0, (availableHeight - contentHeight) / 2)
contentTop?.update(offset: top)
contentLeading?.update(offset: horizontalInset)
contentTrailing?.update(inset: horizontalInset)
iconSize?.update(offset: icon)
titleLeading?.update(offset: titleGap)
titleRowHeight?.update(offset: titleHeight)
messageHeight?.update(offset: max(1, bodyHeight))
deviceHeight?.update(offset: max(1, deviceTextHeight))
contentStack.spacing = gap
}
private static func textHeight(_ text: String?, font: UIFont, width: CGFloat, lines: Int) -> CGFloat {
guard let text, !text.isEmpty else { return ceil(font.lineHeight) }
let height = (text as NSString).boundingRect(with: CGSize(width: max(1, width), height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: [.font: font], context: nil).height
return ceil(min(height, font.lineHeight * CGFloat(lines)))
}
private static func style(for phase: DroneDockTaskDisplayPhase) -> (symbol: String, color: UIColor) {
switch phase {
case .loading: ("clock.arrow.circlepath", DroneDockStyle.primary)
case .navigating: ("paperplane.fill", DroneDockStyle.primary)
case .ready: ("checkmark.circle.fill", DroneDockStyle.success)
case .shooting: ("video.fill", DroneDockStyle.primary)
case .paused: ("pause.circle.fill", DroneDockStyle.warning)
case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning)
case .completed: ("checkmark.circle.fill", DroneDockStyle.success)
case .failed: ("xmark.circle.fill", UIColor(hex: 0xD46B62))
case .blocked, .readError: ("exclamationmark.circle.fill", DroneDockStyle.warning)
case .unknown: ("questionmark.circle.fill", DroneDockStyle.secondary)
}
}
@objc private func primaryTapped() {
guard primaryButton.isEnabled, !primaryButton.isHidden else { return }
onPrimaryAction?()
}
@objc private func detailsTapped() { onDetails?() }
}
@@ -416,6 +416,9 @@ final class DronePreparationFooterView: UIView {
let divider = UIView()
divider.backgroundColor = DroneDockStyle.border
let deviceRow = UIStackView(arrangedSubviews: [deviceCaption, deviceLabel, UIView()])
deviceLabel.accessibilityIdentifier = "drone.preparation.planeStatus"
deviceLabel.numberOfLines = 2
deviceLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
deviceRow.axis = .horizontal
deviceRow.alignment = .center
deviceRow.spacing = 3
@@ -497,20 +500,25 @@ final class DronePreparationFooterView: UIView {
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
}
/// 展示真实准备状态;本阶段保留召唤按钮文案,但尚不提供飞行执行入口。
/// 按购买权限启用待飞任务创建;本阶段不提供无人机召唤或起飞入口。
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: 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)
primaryButton.isEnabled = false
primaryButton.backgroundColor = UIColor(hex: 0xE1E7F0)
primaryButton.isEnabled = (viewModel.isPrimaryActionEnabled || viewModel.canOpenShootingTask) && !isRefreshing
primaryButton.backgroundColor = primaryButton.isEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE1E7F0)
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(UIColor(hex: 0x8792A5), for: .disabled)
messageLabel.text = viewModel.admissionMessage
if viewModel.isTaskSelectionLocked || viewModel.taskCreationErrorMessage != nil {
messageLabel.text = viewModel.admissionMessage
} else {
messageLabel.text = viewModel.planeStatusErrorMessage.map { "无人机状态获取失败:\($0)" } ?? viewModel.admissionMessage
}
messageLabel.textColor = DroneDockStyle.secondary
refreshButton.isHidden = false
refreshButton.isEnabled = !viewModel.isLoading && !isRefreshing
refreshButton.isEnabled = !viewModel.isLoading && !viewModel.isCreatingTask && !viewModel.isSummoning && !isRefreshing
}
@objc private func primaryTapped() { onPrimaryTap?() }
@@ -158,6 +158,9 @@ final class DroneShootingTaskTelemetryView: UIView {
private let stackView = UIStackView()
private let staleLabel = DroneDockStyle.label("ⓘ 状态暂未更新", size: 11, color: DroneDockStyle.secondary)
private var cells: [DroneShootingTaskTelemetryCell] = []
private var rowHeights: [Constraint] = []
private var contentEdges: Constraint?
private var usesFixedLayout = false
/// 以两行三列固定展示电量、温度、风速、雨量、信号与搜星。
override init(frame: CGRect) {
@@ -184,22 +187,38 @@ final class DroneShootingTaskTelemetryView: UIView {
row.addArrangedSubview(cell)
}
stackView.addArrangedSubview(row)
row.snp.makeConstraints { make in make.height.equalTo(55) }
row.snp.makeConstraints { make in rowHeights.append(make.height.equalTo(55).constraint) }
}
stackView.snp.makeConstraints { make in make.edges.equalToSuperview().inset(10) }
stackView.snp.makeConstraints { make in contentEdges = make.edges.equalToSuperview().inset(10).constraint }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 固定任务页不增减状态提示行;小屏仅压缩格子间距与留白,六项参数位置保持稳定。
func configureFixedLayout(compact: Bool) {
usesFixedLayout = true
staleLabel.isHidden = true
rowHeights.forEach { $0.update(offset: compact ? 46 : 55) }
stackView.spacing = compact ? 4 : 6
contentEdges?.update(inset: compact ? 8 : 10)
}
/// 新快照覆盖全部读数;不保留断网前的值冒充有效数据。
func apply(telemetry: DroneDockTelemetry, isStale: Bool) {
staleLabel.isHidden = !isStale
let values = isStale
? Array(repeating: "—", count: 6)
: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText, telemetry.rainText, telemetry.signalText, telemetry.satelliteText]
apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText], isStale: isStale)
}
/// 展示后端已格式化的六项读数,保留单位;缺项与过期读数显示破折号。
func apply(values: [String], isStale: Bool, accessibilityPrefix: String? = nil) {
staleLabel.isHidden = usesFixedLayout || !isStale
let keys = ["battery", "temperature", "wind", "rain", "signal", "satellite"]
for (index, cell) in cells.enumerated() {
cell.apply(value: values[index], isStale: isStale)
let value = !isStale && values.indices.contains(index)
? DroneDockHomeMetric.usableText(values[index]) ?? "—" : "—"
cell.apply(value: value, isStale: isStale)
if let accessibilityPrefix { cell.accessibilityIdentifier = "\(accessibilityPrefix).\(keys[index])" }
}
}
}