feat(drone-dock): 新增拍摄准备与当前任务页面

This commit is contained in:
2026-10-23 16:40:02 +08:00
parent 8072d95d3b
commit 7834b8bcbc
33 changed files with 3799 additions and 6 deletions
@@ -0,0 +1,3 @@
{
"info" : { "author" : "xcode", "version" : 1 }
}
@@ -0,0 +1,4 @@
{
"images" : [ { "filename" : "drone_demo_mountain.png", "idiom" : "universal" } ],
"info" : { "author" : "xcode", "version" : 1 }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

@@ -0,0 +1,4 @@
{
"images" : [ { "filename" : "drone_demo_pagoda.png", "idiom" : "universal" } ],
"info" : { "author" : "xcode", "version" : 1 }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

@@ -0,0 +1,4 @@
{
"images" : [ { "filename" : "drone_demo_tourists.png", "idiom" : "universal" } ],
"info" : { "author" : "xcode", "version" : 1 }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

@@ -0,0 +1,305 @@
import Foundation
/// 点位范围来自有效定位快照;选择点位不会改变范围判定。
enum DroneShootingRange: Hashable, Sendable {
case inside
case outside(distanceText: String?)
case unknown
/// 横向点位卡的距离或范围文字。
var title: String {
switch self {
case .inside: "范围内"
case .outside(let distance): distance ?? "范围外"
case .unknown: "位置待确认"
}
}
/// 底部许可栏的范围描述。
var admissionTitle: String {
switch self {
case .inside: "点位范围内"
case .outside: "尚未进入范围"
case .unknown: "位置待确认"
}
}
/// 范围标签的语义色。
var tone: DroneDockStatusTone { self == .inside ? .green : .orange }
}
/// 准备页一个稳定身份的拍摄点;同名点位不共享选择。
struct DroneShootingPoint: Hashable, Sendable {
/// 点位标识。
let id: String
/// 点位名称。
let name: String
/// 最新有效的定位与范围判定。
let range: DroneShootingRange
/// 本订单在该点已确认成功的次数。
let successfulCount: Int
/// 点位卡的拍摄记录摘要。
var successfulCountText: String { successfulCount > 0 ? "已拍 \(successfulCount) 次" : "未拍摄" }
}
/// 一条归属于单个点位的拍摄航线。
struct DroneShootingRoute: Hashable, Sendable {
/// 航线标识,在点位内匹配,不以名称恢复选择。
let id: String
/// 航线名称。
let name: String
}
/// 准备页召唤准入结果,页面只展示该结果,不自行合并设备和额度。
enum DroneShootingAdmission: Hashable, Sendable {
case ready, currentTask, summoning, summonUnconfirmed, orderUnavailable, noQuota, noPoints, noPoint, noRoutes, noRoute
case outOfRange, unknownRange, occupied, disconnected, noSignal, lowBattery, unknownDevice
/// 底部操作标题。
var title: String {
switch self {
case .currentTask: "查看当前任务"
case .summoning: "召唤处理中"
case .summonUnconfirmed: "召唤结果待确认"
default: "确认并召唤无人机"
}
}
/// 当前是否允许创建新任务。
var canSummon: Bool { self == .ready }
/// 准入提示语义色。
var tone: DroneDockStatusTone {
switch self {
case .ready: .gray
case .currentTask: .blue
case .noSignal: .red
default: .orange
}
}
/// 明确说明当前许可或阻断原因。
var message: String {
switch self {
case .ready: "每次拍摄成功后扣减 1 次,未成功不扣次数。"
case .currentTask: "本订单已有当前任务,请继续查看原任务。"
case .summoning: "等待设备确认召唤结果,请勿重复发送指令。"
case .summonUnconfirmed: "暂未确认是否已执行召唤,请同步原任务状态,勿重复召唤。"
case .orderUnavailable: "当前订单不可用,请返回工作台刷新。"
case .noQuota: "当前订单拍摄次数已用完"
case .noPoints: "当前景区暂无可用拍摄点,请稍后刷新。"
case .noPoint: "请选择拍摄点"
case .noRoutes: "当前拍摄点暂无可用航线"
case .noRoute: "请选择一条有效航线"
case .outOfRange: "请先进入所选拍摄点的范围"
case .unknownRange: "位置待确认,暂时无法召唤"
case .occupied: "无人机占用中,请稍后再试"
case .disconnected: "机巢未连接,请连接后重试"
case .noSignal: "无人机无信号,暂时无法召唤"
case .lowBattery: "电量不足,设备暂不允许执行"
case .unknownDevice: "无人机状态未知,请刷新确认"
}
}
}
/// 手机网络和图传分别保存连接过程;点击重连不代表已经恢复。
enum DroneShootingConnectionState: Hashable, Sendable {
case connected, disconnected, reconnecting, synchronizing
}
/// 可独立追踪结果的设备指令。
enum DroneShootingCommandKind: Hashable, Sendable {
case summon, start, pause, resume, returnHome
/// 指令进行中的展示文字。
var processingTitle: String {
switch self {
case .summon: "召唤处理中"
case .start: "开始拍摄处理中"
case .pause: "暂停处理中"
case .resume: "正在继续任务"
case .returnHome: "返航处理中"
}
}
}
/// 指令处理与任务失败分离,超时只能表达结果未知。
enum DroneShootingCommandStatus: Hashable, Sendable {
case processing, confirmed, unconfirmed, rejected(message: String)
/// 尚无明确回执时禁止重复发送同一指令。
var isUnresolved: Bool { self == .processing || self == .unconfirmed }
}
/// 某一种操作最近一次指令的回执状态。
struct DroneShootingCommand: Hashable, Sendable {
/// 操作类型。
let kind: DroneShootingCommandKind
/// 当前处理结果。
var status: DroneShootingCommandStatus
}
/// 一个本地拍摄会话,飞行、拍摄结果、连接与指令各自独立。
struct DroneShootingSession: Hashable, Sendable {
/// 任务稳定标识,重进页面不会变化。
let id: String
/// 本次任务固定的拍摄点快照。
let point: DroneShootingPoint
/// 本次任务固定的航线快照。
let route: DroneShootingRoute
/// 最近一次明确设备回执的飞行阶段。
var phase: DroneShootingTaskPhase
/// 拍摄结果,不通过飞行结束或超时推断成功。
var result: DroneShootingResult
/// 明确回执的飞行结束标记。
var isFlightFinished: Bool
/// 设备是否明确允许再次执行;不由电量百分比推导。
var deviceReady: Bool
/// 该会话成功是否已经入账,用于重复成功回执去重。
var successRecorded: Bool
/// 手机网络连接,不与图传合并。
var phoneConnection: DroneShootingConnectionState
/// 独立的图传连接。
var feedConnection: DroneShootingConnectionState
/// 最近有效的遥测;手机断网时页面显示未知占位。
var telemetry: DroneDockTelemetry
/// 各操作分别记录回执,安全指令不覆盖开始指令的未知结果。
var commands: [DroneShootingCommandKind: DroneShootingCommand]
/// 暂停前的明确阶段,用于恢复拍摄或返航。
var phaseBeforePause: DroneShootingTaskPhase?
/// 设备给出的明确失败原因。
var failureReason: String?
/// 设备触发的保护性返航原因。
var protectiveReturnReason: String?
/// 结果弹窗已由工作人员关闭;刷新不会重复弹出。
var resultNoticeDismissed: Bool
/// 优先呈现尚未解决的操作,保留其他类型的独立回执。
var command: DroneShootingCommand? {
let ordered = [DroneShootingCommandKind.returnHome, .pause, .resume, .start, .summon]
return ordered.compactMap { commands[$0] }.first { $0.status.isUnresolved }
?? ordered.compactMap { commands[$0] }.first {
if case .rejected = $0.status { return true }
return false
}
}
/// 飞行结束且结果明确后才移除当前任务入口。
var hasCurrentTask: Bool {
!isFlightFinished || result == .unknown || result == .inProgress
}
/// 卡片同步状态与手机连接、命令待确认保持一致,保留原设备阶段快照。
var taskReference: DroneShootingTask? {
guard hasCurrentTask else { return nil }
let isUnknown = phoneConnection != .connected || commands.values.contains { $0.status == .unconfirmed }
return DroneShootingTask(id: id, phase: isUnknown ? .unconfirmed : phase, shootingResult: result)
}
}
/// UI 主按钮的语义;导航由 Controller 执行。
enum DroneShootingTaskPrimaryAction: Hashable, Sendable {
case start, resume, viewMaterials, prepareAgain, none
}
/// 可去重展示的设备结果通知。
struct DroneShootingResultNotice: Hashable, Sendable {
/// 由任务及结果组成的稳定通知身份。
let id: String
/// 弹窗标题。
let title: String
/// 弹窗详情。
let message: String
/// 是否为明确拍摄成功。
let isSuccess: Bool
}
/// 显式本地设备回执;没有计时器,也不会向实际设备发送命令。
enum DroneShootingSessionEvent: Hashable, Sendable {
case commandConfirmed(DroneShootingCommandKind)
case commandRejected(DroneShootingCommandKind, message: String)
case commandResultUnknown(DroneShootingCommandKind)
case phaseConfirmed(DroneShootingTaskPhase)
case shootingSucceeded
case shootingFailed(reason: String)
case flightFinished(deviceReady: Bool)
case protectiveReturn(reason: String)
case phoneConnectionChanged(DroneShootingConnectionState)
case feedConnectionChanged(DroneShootingConnectionState)
case telemetryUpdated(DroneDockTelemetry)
case synchronized(phase: DroneShootingTaskPhase, result: DroneShootingResult, flightFinished: Bool, deviceReady: Bool)
}
/// 本地准备选择,按订单与点位身份保存。
struct DroneShootingPreparationState {
/// 当前订单可用点位及其范围快照。
var points: [DroneShootingPoint]
/// 每个点位当前有效的航线配置。
var routesByPointID: [String: [DroneShootingRoute]]
/// 所选点位身份,配置移除时清空。
var selectedPointID: String?
/// 按点位分别保存航线身份,失效时清除。
var selectedRouteIDs: [String: String]
}
/// 避免同名订单或景区切换共享错误会话的数据源键。
struct DroneShootingSessionKey: Hashable {
/// 会话所属的景区和工作人员。
let context: DroneDockContext
/// 本范围内的稳定订单标识。
let orderID: String
}
#if DEBUG
/// 准备页仅 Debug 可用的本地验收场景。
enum DroneShootingPreparationScenario: String, CaseIterable {
case ready, occupied, disconnected, noSignal, lowBattery, unknown
case outOfRange, unknownRange, noPoints, noRoutes, noQuota
/// 验收菜单标题。
var title: String {
switch self {
case .ready: "恢复正常准备"
case .occupied: "无人机占用中"
case .disconnected: "机巢未连接"
case .noSignal: "无人机无信号"
case .lowBattery: "电量不足"
case .unknown: "设备状态未知"
case .outOfRange: "不在拍摄范围"
case .unknownRange: "位置待确认"
case .noPoints: "暂无拍摄点"
case .noRoutes: "暂无可用航线"
case .noQuota: "拍摄次数用完"
}
}
}
/// 任务页仅 Debug 可用的显式设备事件组合。
enum DroneShootingTaskScenario: String, CaseIterable {
case navigating, arrived, shooting, pauseProcessing, shootingPaused, resumeProcessing
case returning, returnPaused, succeededReturning, succeededFinished, failedReturning, failedReady
case streamLost, phoneOffline, protectiveReturn, commandUnconfirmed, commandRejected, synchronized
/// 验收菜单标题。
var title: String {
switch self {
case .navigating: "前往拍摄点中"
case .arrived: "已到达,待拍摄"
case .shooting: "拍摄中"
case .pauseProcessing: "暂停处理中"
case .shootingPaused: "拍摄已暂停"
case .resumeProcessing: "恢复处理中"
case .returning: "返航中"
case .returnPaused: "返航已暂停"
case .succeededReturning: "拍摄成功 · 返航中"
case .succeededFinished: "拍摄成功 · 飞行结束"
case .failedReturning: "执行失败 · 返航中"
case .failedReady: "执行失败 · 设备可用"
case .streamLost: "画面断流"
case .phoneOffline: "手机断网"
case .protectiveReturn: "保护性返航"
case .commandUnconfirmed: "指令执行结果待确认"
case .commandRejected: "指令明确拒绝"
case .synchronized: "同步当前任务回执"
}
}
}
#endif
@@ -1,6 +1,6 @@
import Foundation
/// 两个机巢页面共享的本地数据源,不请求接口、不发送设备指令,也不自动推进任务。
/// 机巢工作台、订单、准备和任务页面共享的本地数据源;不请求接口或自动推进任务。
final class DroneDockDemoStore {
/// 当前登录用户与景区范围。
private(set) var context: DroneDockContext
@@ -8,6 +8,15 @@ final class DroneDockDemoStore {
private var ordersByContext: [DroneDockContext: [DroneShootingOrder]] = [:]
private var devicesByContext: [DroneDockContext: [DroneDockDevice]] = [:]
/// 按上下文与订单保存的点位、航线和人工选择。
var shootingPreparations: [DroneShootingSessionKey: DroneShootingPreparationState] = [:]
/// 当前或最近一次本地任务;飞行结束后仍保留结果页快照。
var shootingSessions: [DroneShootingSessionKey: DroneShootingSession] = [:]
#if DEBUG
/// 预览切换前的订单,恢复正常场景时不累计演示扣次。
var shootingScenarioBaselines: [DroneShootingSessionKey: DroneShootingOrder] = [:]
#endif
/// 注入初始上下文及可选数据,便于页面演示与独立规则测试。
init(
context: DroneDockContext = .demo,
@@ -29,6 +38,24 @@ final class DroneDockDemoStore {
/// 当前景区的无人机,不将横向浏览等同于执行资源选择。
var devices: [DroneDockDevice] { devicesByContext[context] ?? [] }
/// 读取当前用户、当前景区内的指定订单。
func shootingOrder(id: String) -> DroneShootingOrder? { orders.first { $0.id == id } }
/// 写回一个已校验归属的本地订单,使工作台与列表主动刷新时得到相同结果。
func replaceShootingOrder(_ order: DroneShootingOrder) {
guard order.scenicID == context.scenicID, order.assignedUserID == context.userID,
let index = ordersByContext[context]?.firstIndex(where: { $0.id == order.id }) else { return }
ordersByContext[context]?[index] = order
}
/// 更新本地执行资源状态;仅使用明确状态,不从电量或卡片浏览位置推导许可。
func setShootingDeviceState(_ state: DroneDockDeviceState, telemetry: DroneDockTelemetry? = nil) {
guard let device = devices.first else { return }
devicesByContext[context]?[0] = DroneDockDevice(
id: device.id, name: device.name, state: state, telemetry: telemetry ?? device.telemetry
)
}
/// 当前演示上下文的今日统计;空场景不保留误导的数值。
var statistics: DroneDockDailyStatistics {
orders.isEmpty
@@ -48,6 +75,9 @@ final class DroneDockDemoStore {
#if DEBUG
/// 只在 Debug 提供场景切换;不会触发扣次、真实设备或网络操作。
func applyScenario(_ scenario: DroneDockDemoScenario) {
shootingPreparations = shootingPreparations.filter { $0.key.context != context }
shootingSessions = shootingSessions.filter { $0.key.context != context }
shootingScenarioBaselines = shootingScenarioBaselines.filter { $0.key.context != context }
var orders = DroneDockDemoData.orders(context: context)
var devices = DroneDockDemoData.devices()
switch scenario {
@@ -0,0 +1,803 @@
import Foundation
/// 准备页的选择、恢复和准入规则;读取共享数据源后由 View 主动刷新。
final class DroneShootingPreparationViewModel {
/// 与工作台、订单及任务页面共享的本地数据源。
let store: DroneDockDemoStore
/// 固定入口订单,避免通过列表位置恢复错误任务。
let orderID: String
private let context: DroneDockContext
/// 当前可访问订单;切换到其他上下文时不可继续操作旧页面。
var order: DroneShootingOrder? { isCurrentContext ? store.shootingOrder(id: orderID) : nil }
/// 按配置顺序展示,不因距离更新自动重排。
var points: [DroneShootingPoint] { preparation?.points ?? [] }
/// 当前选择的点位。
var selectedPoint: DroneShootingPoint? { points.first { $0.id == preparation?.selectedPointID } }
/// 所选点的航线,不包含其他点位的同名航线。
var routes: [DroneShootingRoute] { selectedPoint.flatMap { preparation?.routesByPointID[$0.id] } ?? [] }
/// 当前有效航线,配置失效时为空。
var selectedRoute: DroneShootingRoute? {
guard let point = selectedPoint, let id = preparation?.selectedRouteIDs[point.id] else { return nil }
return routes.first { $0.id == id }
}
/// 当前设备明确状态;其他订单执行时仍允许浏览选择。
var deviceState: DroneDockDeviceState {
guard isCurrentContext else { return .unknown }
if store.orders.contains(where: { $0.activeTask != nil }) { return .occupied }
return store.devices.first?.state ?? .unknown
}
/// 本单已有尚未结束的任务,召唤确认处理中也保持唯一引用。
var hasCurrentTask: Bool { order?.activeTask != nil }
/// 召唤已经提交但尚无明确回执。
var hasPendingSummon: Bool {
guard let command = session?.commands[.summon] else { return false }
return command.status.isUnresolved
}
/// 超时只提供同步入口,不以超时当作召唤失败。
var shouldShowSummonRefresh: Bool { session?.commands[.summon]?.status == .unconfirmed }
/// 底部唯一准入结果。
var admission: DroneShootingAdmission {
guard let order else { return .orderUnavailable }
if hasPendingSummon {
return shouldShowSummonRefresh ? .summonUnconfirmed : .summoning
}
if hasCurrentTask { return .currentTask }
if order.remainingShootingCount == 0 { return .noQuota }
if points.isEmpty { return .noPoints }
guard let point = selectedPoint else { return .noPoint }
if routes.isEmpty { return .noRoutes }
guard selectedRoute != nil else { return .noRoute }
switch point.range {
case .outside: return .outOfRange
case .unknown: return .unknownRange
case .inside: break
}
switch deviceState {
case .ready: return .ready
case .occupied: return .occupied
case .disconnected: return .disconnected
case .noSignal: return .noSignal
case .lowBattery: return .lowBattery
case .unknown: return .unknownDevice
}
}
/// 底部连接文字,设备未知时不误报已连接。
var connectionTitle: String {
switch deviceState {
case .disconnected: "机巢未连接"
case .unknown: "机巢连接待确认"
default: "机巢已连接"
}
}
/// 底部连接语义色。
var connectionTone: DroneDockStatusTone {
switch deviceState {
case .disconnected, .unknown: .gray
default: .green
}
}
/// 底部所选点位范围文字。
var rangeTitle: String { selectedPoint?.range.admissionTitle ?? "未选择拍摄点" }
/// 底部范围语义色。
var rangeTone: DroneDockStatusTone { selectedPoint?.range.tone ?? .gray }
/// 设备与有效电量摘要,未知值不显示为零。
var deviceStatusText: String {
let value = store.devices.first?.telemetry.batteryText ?? "—"
return value == "—" ? deviceState.title : "\(deviceState.title) · 电量 \(value)"
}
/// 当前选择的点位与航线。
var selectionSummary: String { "\(selectedPoint?.name ?? "未选择拍摄点") · \(selectedRoute?.name ?? "未选择航线")" }
/// 主要按钮标题由准入结果统一提供。
var primaryButtonTitle: String { admission.title }
/// 仅有效召唤或查看已确认任务允许点击。
var primaryButtonEnabled: Bool { admission.canSummon || admission == .currentTask }
private var isCurrentContext: Bool { store.context == context }
private var key: DroneShootingSessionKey { DroneShootingSessionKey(context: context, orderID: orderID) }
private var preparation: DroneShootingPreparationState? { isCurrentContext ? store.shootingPreparations[key] : nil }
private var session: DroneShootingSession? { isCurrentContext ? store.shootingSession(orderID: orderID) : nil }
/// 载入指定订单的本地选择,不创建任务。
init(store: DroneDockDemoStore, orderID: String) {
self.store = store
self.orderID = orderID
context = store.context
refresh()
}
/// 页面出现时校验选择与当前订单;不自动补选失效航线。
func refresh() {
guard isCurrentContext, order != nil else { return }
store.ensureShootingPreparation(orderID: orderID)
_ = store.shootingSession(orderID: orderID)
store.validateShootingSelection(orderID: orderID)
}
/// 整卡选点;切回已选点恢复其仍有效的航线,不把上一点航线带过来。
func selectPoint(id: String) {
guard !hasPendingSummon, var state = preparation, state.points.contains(where: { $0.id == id }) else { return }
state.selectedPointID = id
let routes = state.routesByPointID[id] ?? []
if state.selectedRouteIDs[id] == nil { state.selectedRouteIDs[id] = routes.first?.id }
store.shootingPreparations[key] = state
store.validateShootingSelection(orderID: orderID)
}
/// 选择本点有效航线,重复点击不取消。
func selectRoute(id: String) {
guard !hasPendingSummon, var state = preparation, let point = selectedPoint,
routes.contains(where: { $0.id == id }) else { return }
state.selectedRouteIDs[point.id] = id
store.shootingPreparations[key] = state
}
/// 首次只提交本地召唤并返回 false;已有明确任务时返回 true 供页面导航。
@discardableResult
func summon() -> Bool {
refresh()
if admission == .currentTask { return true }
guard admission.canSummon, let point = selectedPoint, let route = selectedRoute else { return false }
store.beginShootingSession(orderID: orderID, point: point, route: route)
return false
}
/// 请求同步原召唤,不自动判定设备已执行。
func refreshSummonStatus() {
guard isCurrentContext, hasPendingSummon else { return }
store.receiveShootingEvent(.phoneConnectionChanged(.synchronizing), orderID: orderID, taskID: session?.id)
}
#if DEBUG
/// 显式模拟设备召唤确认;确认后才进入任务页。
@discardableResult
func confirmSummon() -> Bool {
guard isCurrentContext, let session, session.commands[.summon]?.status.isUnresolved == true else { return false }
store.receiveShootingEvent(.commandConfirmed(.summon), orderID: orderID, taskID: session.id)
store.receiveShootingEvent(.phoneConnectionChanged(.connected), orderID: orderID, taskID: session.id)
return true
}
/// 准备页本地验收入口;不连接网络或实际设备。
func applyScenario(_ scenario: DroneShootingPreparationScenario) {
guard isCurrentContext, order != nil else { return }
store.applyPreparationScenario(scenario, orderID: orderID)
refresh()
}
#endif
}
/// 当前任务的展示及指令入口;提交与设备确认严格分开。
final class DroneShootingTaskViewModel {
/// 与入口页面共享的本地数据源。
let store: DroneDockDemoStore
/// 本次入口订单。
let orderID: String
private let context: DroneDockContext
/// 当前上下文仍可访问的订单。
var order: DroneShootingOrder? { isCurrentContext ? store.shootingOrder(id: orderID) : nil }
/// 原任务或最近一次结果快照。
var session: DroneShootingSession? { isCurrentContext ? store.shootingSession(orderID: orderID) : nil }
/// 点位与航线标题。
var title: String { session.map { "\($0.point.name) · \($0.route.name)" } ?? "当前任务" }
/// 订单游客和次数摘要。
var subtitle: String { order.map { "\($0.customerName) · 含\($0.totalShootingCount)次拍摄" } ?? "当前订单不可用" }
/// 手机状态未同步时隐藏过期遥测,不将未知当作零。
var telemetry: DroneDockTelemetry { phoneConnection == .connected ? (session?.telemetry ?? .unknown) : .unknown }
/// 卡片一致的七阶段状态;手机断网时为待确认。
var phase: DroneShootingTaskPhase? { session?.taskReference?.phase ?? session?.phase }
/// 手机网络连接。
var phoneConnection: DroneShootingConnectionState { session?.phoneConnection ?? .disconnected }
/// 图传独立连接。
var feedConnection: DroneShootingConnectionState { session?.feedConnection ?? .disconnected }
/// 当前待处理或明确拒绝的指令,不混成拍摄失败。
var commandTitle: String? {
guard let command = session?.command else { return nil }
switch command.status {
case .processing: return command.kind.processingTitle
case .unconfirmed: return "执行结果待确认"
case .rejected: return "指令未执行"
case .confirmed: return nil
}
}
/// 指令处理提示,避免点击按钮后误称已经生效。
var commandMessage: String? {
guard let command = session?.command else { return nil }
switch command.status {
case .processing: return "等待设备确认,请勿重复发送指令。"
case .unconfirmed: return "暂未确认执行结果,请刷新任务状态,勿重复发送指令。"
case .rejected(let message): return message
case .confirmed: return nil
}
}
/// 用于按钮或提示区的处理指示器。
var commandIsProcessing: Bool { session?.command?.status == .processing }
/// 只有结果未知才提示同步原任务。
var shouldShowCommandRefresh: Bool { session?.commands.values.contains { $0.status == .unconfirmed } ?? false }
/// 主状态标题,拍摄结果和飞行返航同时可见。
var statusTitle: String {
guard let session else { return "当前任务不可用" }
if phoneConnection != .connected { return "任务状态待确认" }
if session.result == .succeeded { return "拍摄已完成" }
if session.result == .failed { return "任务执行失败" }
if session.isFlightFinished { return session.result == .unknown ? "拍摄结果待确认" : "本次任务已结束" }
if session.protectiveReturnReason != nil { return "无人机自动返航" }
switch session.phase {
case .navigating: return "无人机正在前往拍摄点"
case .arrived: return "无人机已到达"
case .shooting: return "无人机正在拍摄中"
case .shootingPaused: return "无人机已暂停"
case .returning: return "无人机正在返航"
case .returnPaused: return "无人机返航已暂停"
case .unconfirmed: return "任务状态待确认"
}
}
/// 独立说明结果、飞行或连接状态。
var statusMessage: String {
guard let session else { return "请返回工作台刷新当前订单。" }
if phoneConnection != .connected { return "连接中断不代表任务失败。恢复连接后需同步原任务。" }
if session.result == .succeeded {
if session.isFlightFinished { return "本次拍摄已结束,可前往查看素材。" }
let flightMessage: String
switch session.phase {
case .returning: flightMessage = "无人机返航中"
case .returnPaused: flightMessage = "无人机返航已暂停"
default: flightMessage = "无人机飞行任务尚未结束"
}
return "本次拍摄已完成。\(flightMessage),请留意现场。"
}
if session.result == .failed {
let reason = "失败原因:\(session.failureReason ?? "设备已确认本次拍摄失败")。"
if !session.isFlightFinished { return reason + "无人机尚未结束飞行,暂不可重新准备。" }
if order?.remainingShootingCount == 0 { return reason + "当前订单拍摄次数已用完。" }
return reason + (session.deviceReady ? "请排查后重新准备拍摄。" : "设备尚未恢复可用,请稍后刷新。")
}
if session.isFlightFinished {
if session.result == .unknown || session.result == .inProgress { return "飞行任务已结束,拍摄结果仍待确认。请同步原任务,勿重复召唤。" }
return "本次未开始拍摄,未扣减次数。\(session.deviceReady ? "可重新准备拍摄。" : "设备尚未恢复可用。")"
}
if let reason = session.protectiveReturnReason { return "返航原因:\(reason)。拍摄结果待确认,请留意现场。" }
switch session.phase {
case .navigating: return "请关注现场,等待设备确认到达。"
case .arrived: return "是否开始拍摄?确认游客站位与取景后开始。"
case .shooting: return feedConnection == .connected ? "请关注现场及实时画面。" : "当前仅画面中断,无人机状态仍在更新。"
case .shootingPaused: return "当前悬停待命。确认安全后,可继续任务或立即返航。"
case .returning: return "无人机返航中,请留意现场。拍摄结果单独确认。"
case .returnPaused: return "当前悬停待命,确认安全后可继续返航。"
case .unconfirmed: return "请同步原任务状态,勿重复创建任务。"
}
}
/// 主状态的语义色。
var statusTone: DroneDockStatusTone {
guard let session else { return .gray }
if phoneConnection != .connected { return .orange }
if session.result == .succeeded { return .green }
if session.result == .failed { return .red }
return session.phase.tone
}
/// 导航和指令的主按钮语义。
var primaryAction: DroneShootingTaskPrimaryAction {
guard let session, order != nil else { return .none }
if !session.isFlightFinished, session.phase == .returnPaused || session.phase == .shootingPaused { return .resume }
if session.result == .succeeded { return .viewMaterials }
if session.isFlightFinished, session.result == .failed || session.result == .notStarted { return .prepareAgain }
if session.result == .failed { return .prepareAgain }
switch session.phase {
case .arrived: return .start
case .shootingPaused, .returnPaused: return .resume
default: return .none
}
}
/// 主按钮标题,指令处理中与待确认时阻止重复操作。
var primaryTitle: String {
if phoneConnection != .connected { return "等待任务同步" }
switch primaryAction {
case .start:
if let command = session?.commands[.start], command.status.isUnresolved {
return command.status == .unconfirmed ? "执行结果待确认" : command.kind.processingTitle
}
return "开始拍摄"
case .resume:
if let command = session?.commands[.resume], command.status.isUnresolved {
return command.status == .unconfirmed ? "执行结果待确认" : command.kind.processingTitle
}
return session?.phase == .returnPaused ? "继续返航" : "继续任务"
case .viewMaterials: return "查看素材"
case .prepareAgain: return "重新准备拍摄"
case .none:
if session?.result == .unknown { return "结果待确认" }
if session?.phase == .navigating { return "前往拍摄点中" }
if session?.phase == .returning { return "返航中" }
return "拍摄中"
}
}
/// 新任务必须等待飞行结束、设备可用并有剩余次数。
var primaryEnabled: Bool {
guard let session, phoneConnection == .connected else { return false }
switch primaryAction {
case .viewMaterials: return true
case .prepareAgain:
return session.isFlightFinished && !session.hasCurrentTask && session.deviceReady
&& (order?.remainingShootingCount ?? 0) > 0 && store.shootingDeviceState(orderID: orderID) == .ready
case .start: return canSend(.start)
case .resume: return canSend(.resume)
case .none: return false
}
}
/// 暂停按钮标题,提交后仍不展示已暂停。
var pauseTitle: String {
if let command = session?.commands[.pause], command.status.isUnresolved {
return command.status == .processing ? "暂停处理中" : "暂停结果待确认"
}
return session?.phase == .shootingPaused || session?.phase == .returnPaused ? "已暂停" : "紧急暂停"
}
/// 暂停按钮补充说明。
var pauseSubtitle: String {
if phoneConnection != .connected { return "当前无法发送指令" }
if session?.isFlightFinished != false { return "当前未执行任务" }
if session?.commands[.pause]?.status.isUnresolved == true { return "尚未确认悬停" }
return "悬停待命"
}
/// 暂停按钮许可,不因图传断流而禁用。
var canPause: Bool { canSend(.pause) }
/// 返航按钮标题,等待明确回执才显示返航中。
var returnTitle: String {
if let command = session?.commands[.returnHome], command.status.isUnresolved {
return command.status == .processing ? "正在发送返航指令" : "返航结果待确认"
}
return session?.phase == .returning ? "返航中" : "立即返航"
}
/// 返航按钮补充说明。
var returnSubtitle: String {
if phoneConnection != .connected { return "当前无法发送指令" }
if session?.isFlightFinished != false { return "当前未执行任务" }
if session?.commands[.returnHome]?.status.isUnresolved == true { return "尚未确认返航" }
return session?.phase == .returning ? "返回机巢" : "中断任务"
}
/// 返航直接提交,无二次确认;提交与执行结果分开。
var canReturn: Bool { canSend(.returnHome) }
/// 结果弹窗是任务快照的一部分,关闭后重进不重复展示。
var resultNotice: DroneShootingResultNotice? {
guard let session, !session.resultNoticeDismissed else { return nil }
switch session.result {
case .succeeded:
return DroneShootingResultNotice(id: "\(session.id)-success", title: "拍摄完成", message: "本次拍摄已成功,扣减 1 次拍摄次数。飞行状态请继续留意现场。", isSuccess: true)
case .failed:
return DroneShootingResultNotice(id: "\(session.id)-failure", title: "任务执行失败", message: "\(session.failureReason ?? "设备已确认失败"),本次未扣减拍摄次数。", isSuccess: false)
default: return nil
}
}
private var isCurrentContext: Bool { store.context == context }
/// 只恢复原任务,构造页面不会自动创建、扣次或恢复执行。
init(store: DroneDockDemoStore, orderID: String) {
self.store = store
self.orderID = orderID
context = store.context
refresh()
}
/// 页面出现或手动操作后重新读取共享状态;没有自动进度。
func refresh() {
guard isCurrentContext else { return }
_ = store.shootingSession(orderID: orderID)
}
/// 直接提交开始请求,明确设备确认后才进入拍摄中。
@discardableResult
func startShooting() -> Bool { send(.start) }
/// 直接提交紧急暂停,不弹二次确认,不提前宣称悬停。
@discardableResult
func pause() -> Bool { send(.pause) }
/// 请求恢复暂停前阶段,收到回执前保持暂停。
@discardableResult
func resume() -> Bool { send(.resume) }
/// 按已确认交互直接提交返航请求,收到回执前保持原阶段。
@discardableResult
func requestReturn() -> Bool { send(.returnHome) }
/// 只开始手机重连,需明确同步回执才能恢复操作。
func reconnectPhone() { receive(.phoneConnectionChanged(.reconnecting)) }
/// 图传重连不改变任务结果、飞行阶段或手机连接。
func reconnectFeed() { receive(.feedConnectionChanged(.reconnecting)) }
/// 手动发起原任务同步;不清除未知结果或重复发送设备指令。
func refreshTaskStatus() { receive(.phoneConnectionChanged(.synchronizing)) }
/// 关闭本任务的结果通知,写回共享快照防止重复弹窗。
func dismissResultNotice() {
guard let session, isCurrentContext else { return }
store.dismissShootingResultNotice(orderID: orderID, taskID: session.id)
}
/// 注入显式本地回执,便于规则验证或后续数据源适配;过期任务回执会忽略。
func receive(_ event: DroneShootingSessionEvent) {
guard let session, isCurrentContext else { return }
store.receiveShootingEvent(event, orderID: orderID, taskID: session.id)
}
private func canSend(_ kind: DroneShootingCommandKind) -> Bool {
guard let session, order != nil, phoneConnection == .connected, !session.isFlightFinished,
session.commands[kind]?.status.isUnresolved != true,
session.commands[.summon]?.status.isUnresolved != true else { return false }
switch kind {
case .summon: return false
case .start:
return session.phase == .arrived && session.result == .notStarted
&& !session.commands.values.contains { $0.status.isUnresolved }
case .resume:
return (session.phase == .shootingPaused || session.phase == .returnPaused)
&& !session.commands.values.contains { $0.status.isUnresolved }
case .pause:
return session.phase != .shootingPaused && session.phase != .returnPaused && session.phase != .unconfirmed
case .returnHome: return session.phase != .returning && session.phase != .returnPaused && session.phase != .unconfirmed
}
}
private func send(_ kind: DroneShootingCommandKind) -> Bool {
guard canSend(kind) else { return false }
return store.submitShootingCommand(kind, orderID: orderID)
}
#if DEBUG
/// 显式模拟设备状态;场景切换不包含任何自动计时。
func applyScenario(_ scenario: DroneShootingTaskScenario) {
guard isCurrentContext else { return }
store.applyTaskScenario(scenario, orderID: orderID)
refresh()
}
#endif
}
/// 准备配置、会话与订单投影共享同一存储;页面间不存在独立任务副本。
extension DroneDockDemoStore {
/// 当前上下文中读取或恢复原任务,已有任务引用只补齐本地展示快照。
func shootingSession(orderID: String) -> DroneShootingSession? {
guard let order = shootingOrder(id: orderID) else { return nil }
let key = shootingKey(orderID)
if let session = shootingSessions[key], order.activeTask == nil || order.activeTask?.id == session.id { return session }
guard let task = order.activeTask else { return nil }
ensureShootingPreparation(orderID: orderID)
guard let state = shootingPreparations[key],
let point = state.points.first(where: { $0.id == state.selectedPointID }),
let route = state.routesByPointID[point.id]?.first(where: { $0.id == state.selectedRouteIDs[point.id] }) else { return nil }
let session = makeSession(id: task.id, point: point, route: route, phase: task.phase, result: task.shootingResult)
shootingSessions[key] = session
return session
}
/// 外部明确的点位配置或定位快照;原选择失效时清空而不偷偷换航线。
func updateShootingPoints(_ points: [DroneShootingPoint], routesByPointID: [String: [DroneShootingRoute]], orderID: String) {
guard shootingOrder(id: orderID) != nil else { return }
ensureShootingPreparation(orderID: orderID)
let key = shootingKey(orderID)
shootingPreparations[key]?.points = points
shootingPreparations[key]?.routesByPointID = routesByPointID
validateShootingSelection(orderID: orderID)
}
/// 明确范围与设备都有效后创建唯一待确认会话;不扣次、不假称起飞。
func beginShootingSession(orderID: String, point: DroneShootingPoint, route: DroneShootingRoute) {
guard let order = shootingOrder(id: orderID), order.activeTask == nil,
order.remainingShootingCount > 0, !orders.contains(where: { $0.activeTask != nil }),
point.range == .inside, shootingDeviceState(orderID: orderID) == .ready,
let state = shootingPreparations[shootingKey(orderID)],
state.points.contains(point), state.routesByPointID[point.id]?.contains(route) == true else { return }
var session = makeSession(id: UUID().uuidString, point: point, route: route, phase: .unconfirmed, result: .notStarted)
session.commands[.summon] = DroneShootingCommand(kind: .summon, status: .processing)
session.deviceReady = false
shootingSessions[shootingKey(orderID)] = session
setShootingDeviceState(.occupied)
projectShootingSession(orderID: orderID)
}
/// 记录一种已通过页面许可校验的本地指令,防止同一种指令重复提交。
@discardableResult
func submitShootingCommand(_ kind: DroneShootingCommandKind, orderID: String) -> Bool {
guard var session = shootingSession(orderID: orderID), !session.isFlightFinished,
session.phoneConnection == .connected, session.commands[kind]?.status.isUnresolved != true else { return false }
session.commands[kind] = DroneShootingCommand(kind: kind, status: .processing)
shootingSessions[shootingKey(orderID)] = session
projectShootingSession(orderID: orderID)
return true
}
/// 显式设备事件入口,任务身份不匹配时忽略迟到回执。
func receiveShootingEvent(_ event: DroneShootingSessionEvent, orderID: String, taskID: String?) {
guard var session = shootingSession(orderID: orderID), session.id == taskID else { return }
switch event {
case .commandConfirmed(let kind):
guard session.commands[kind]?.status.isUnresolved == true else { return }
session.commands[kind]?.status = .confirmed
if !session.isFlightFinished {
switch kind {
case .summon: session.phase = .navigating
case .start:
if session.result != .succeeded && session.result != .failed {
session.phase = .shooting
session.result = .inProgress
}
case .pause:
session.phaseBeforePause = session.phase
session.phase = session.phase == .returning ? .returnPaused : .shootingPaused
case .resume:
session.phase = session.phaseBeforePause ?? (session.phase == .returnPaused ? .returning : .shooting)
session.phaseBeforePause = nil
case .returnHome:
session.phase = .returning
if session.result == .inProgress { session.result = .unknown }
}
}
case .commandRejected(let kind, let message):
guard session.commands[kind]?.status.isUnresolved == true else { return }
session.commands[kind]?.status = .rejected(message: message)
if kind == .summon {
session.isFlightFinished = true
session.deviceReady = true
}
case .commandResultUnknown(let kind):
guard session.commands[kind]?.status.isUnresolved == true else { return }
session.commands[kind]?.status = .unconfirmed
case .phaseConfirmed(let phase): session.phase = phase
case .shootingSucceeded:
guard session.result != .failed else { return }
session.result = .succeeded
case .shootingFailed(let reason):
guard session.result != .succeeded else { return }
session.result = .failed
session.failureReason = reason
case .flightFinished(let deviceReady):
session.isFlightFinished = true
session.deviceReady = deviceReady
case .protectiveReturn(let reason):
session.phase = .returning
session.protectiveReturnReason = reason
if session.result != .succeeded && session.result != .failed { session.result = .unknown }
case .phoneConnectionChanged(let state): session.phoneConnection = state
case .feedConnectionChanged(let state): session.feedConnection = state
case .telemetryUpdated(let telemetry): session.telemetry = telemetry
case .synchronized(let phase, let result, let finished, let ready):
session.phase = phase
// 终态回执不被随后到达的非终态快照覆盖。
if session.result != .succeeded && session.result != .failed { session.result = result }
session.isFlightFinished = session.isFlightFinished || finished
session.deviceReady = ready
session.phoneConnection = .connected
for kind in session.commands.keys { session.commands[kind]?.status = .confirmed }
}
shootingSessions[shootingKey(orderID)] = session
projectShootingSession(orderID: orderID)
}
/// 关闭结果通知,后续页面只读取已关闭的同一快照。
func dismissShootingResultNotice(orderID: String, taskID: String) {
let key = shootingKey(orderID)
guard shootingSessions[key]?.id == taskID else { return }
shootingSessions[key]?.resultNoticeDismissed = true
}
/// 本地执行许可优先考虑其他活跃订单,不绑定工作台横向浏览的设备卡。
func shootingDeviceState(orderID: String) -> DroneDockDeviceState {
if orders.contains(where: { $0.id != orderID && $0.activeTask != nil }) { return .occupied }
return devices.first?.state ?? .unknown
}
/// 首次创建演示选择;后续进入保留每个点位的航线身份。
func ensureShootingPreparation(orderID: String) {
let key = shootingKey(orderID)
guard shootingPreparations[key] == nil, let order = shootingOrder(id: orderID) else { return }
shootingPreparations[key] = DroneShootingSessionDemoData.preparation(successfulCount: order.successfulShootingCount)
}
/// 配置失效时清除选择,不从其他同名点位恢复。
func validateShootingSelection(orderID: String) {
let key = shootingKey(orderID)
guard var state = shootingPreparations[key] else { return }
if !state.points.contains(where: { $0.id == state.selectedPointID }) { state.selectedPointID = nil }
state.selectedRouteIDs = state.selectedRouteIDs.filter { pointID, routeID in
state.points.contains { $0.id == pointID } && (state.routesByPointID[pointID] ?? []).contains { $0.id == routeID }
}
shootingPreparations[key] = state
}
private func shootingKey(_ orderID: String) -> DroneShootingSessionKey {
DroneShootingSessionKey(context: context, orderID: orderID)
}
private func makeSession(id: String, point: DroneShootingPoint, route: DroneShootingRoute, phase: DroneShootingTaskPhase, result: DroneShootingResult) -> DroneShootingSession {
DroneShootingSession(
id: id, point: point, route: route, phase: phase, result: result, isFlightFinished: false,
deviceReady: false, successRecorded: result == .succeeded, phoneConnection: .connected,
feedConnection: .connected, telemetry: devices.first?.telemetry ?? .unknown,
commands: [:], phaseBeforePause: nil, failureReason: nil, protectiveReturnReason: nil,
resultNoticeDismissed: result == .succeeded || result == .failed
)
}
private func projectShootingSession(orderID: String) {
let key = shootingKey(orderID)
guard var session = shootingSessions[key], let order = shootingOrder(id: orderID) else { return }
let shouldRecordSuccess = session.result == .succeeded && !session.successRecorded
if shouldRecordSuccess {
session.successRecorded = true
incrementShootingPointCount(orderID: orderID, pointID: session.point.id)
}
shootingSessions[key] = session
let successfulCount = shouldRecordSuccess ? min(order.totalShootingCount, order.successfulShootingCount + 1) : order.successfulShootingCount
replaceShootingOrder(order.replacingShootingState(
successfulCount: successfulCount, task: session.taskReference,
needsRepreparation: !session.hasCurrentTask && session.result != .succeeded,
materialState: shouldRecordSuccess ? .uploading : order.materialState
))
if !session.hasCurrentTask {
let hasOtherTask = orders.contains { $0.id != orderID && $0.activeTask != nil }
setShootingDeviceState(hasOtherTask ? .occupied : (session.deviceReady ? .ready : .unknown), telemetry: session.telemetry)
}
}
private func incrementShootingPointCount(orderID: String, pointID: String) {
let key = shootingKey(orderID)
guard var state = shootingPreparations[key], let index = state.points.firstIndex(where: { $0.id == pointID }) else { return }
let point = state.points[index]
state.points[index] = DroneShootingPoint(id: point.id, name: point.name, range: point.range, successfulCount: point.successfulCount + 1)
shootingPreparations[key] = state
}
}
/// 复制订单的会话相关字段,其余原素材和成片交付信息原样保留。
private extension DroneShootingOrder {
func replacingShootingState(successfulCount: Int, task: DroneShootingTask?, needsRepreparation: Bool, materialState: DroneShootingMaterialState) -> DroneShootingOrder {
DroneShootingOrder(
id: id, scenicID: scenicID, assignedUserID: assignedUserID, customerName: customerName,
orderNumber: orderNumber, createdAtText: createdAtText, packageName: packageName,
totalShootingCount: totalShootingCount, successfulShootingCount: successfulCount,
activeTask: task, needsRepreparation: needsRepreparation, materialState: materialState,
deliveredVideoCount: deliveredVideoCount, visitorConfirmationState: visitorConfirmationState
)
}
}
/// 无真实接口的首轮 UI 配置;航线数量严格来自各点自己的配置。
private enum DroneShootingSessionDemoData {
static func preparation(successfulCount: Int) -> DroneShootingPreparationState {
let points = [
DroneShootingPoint(id: "point-sanhuang", name: "三皇寨", range: .inside, successfulCount: successfulCount),
DroneShootingPoint(id: "point-jinque", name: "金阙云宫", range: .outside(distanceText: "800 m"), successfulCount: 0),
DroneShootingPoint(id: "point-shaoshi", name: "少室山", range: .outside(distanceText: "1.2 km"), successfulCount: 0),
DroneShootingPoint(id: "point-yingke", name: "迎客峰", range: .outside(distanceText: "1.8 km"), successfulCount: 0)
]
let routeNames = [
["经典航线", "环绕专线", "远景拉升", "全景环绕", "高空俯瞰", "山峰渐远", "峡谷穿行", "山脊侧拍"],
["云宫环绕", "金顶渐远", "云海全景"],
["山峦全景", "山间渐远"],
["迎客环绕", "山峰远景", "山谷俯瞰"]
]
var routesByPointID: [String: [DroneShootingRoute]] = [:]
for (index, point) in points.enumerated() {
routesByPointID[point.id] = routeNames[index].enumerated().map { DroneShootingRoute(id: "\(point.id)-route-\($0.offset)", name: $0.element) }
}
return DroneShootingPreparationState(points: points, routesByPointID: routesByPointID, selectedPointID: points.first?.id, selectedRouteIDs: [points[0].id: routesByPointID[points[0].id]![0].id])
}
}
#if DEBUG
/// 所有演示均由明确点击触发,不执行计时、API 或真实设备操作。
private extension DroneDockDemoStore {
func applyPreparationScenario(_ scenario: DroneShootingPreparationScenario, orderID: String) {
guard let order = shootingOrder(id: orderID) else { return }
let key = shootingKey(orderID)
if shootingScenarioBaselines[key] == nil { shootingScenarioBaselines[key] = order }
guard let baseline = shootingScenarioBaselines[key] else { return }
let count = scenario == .noQuota ? baseline.totalShootingCount : baseline.successfulShootingCount
replaceShootingOrder(baseline.replacingShootingState(successfulCount: count, task: baseline.activeTask, needsRepreparation: baseline.needsRepreparation, materialState: baseline.materialState))
if baseline.activeTask == nil { shootingSessions[key] = nil }
var state = DroneShootingSessionDemoData.preparation(successfulCount: count)
if let previous = shootingPreparations[key], state.points.contains(where: { $0.id == previous.selectedPointID }) {
state.selectedPointID = previous.selectedPointID
state.selectedRouteIDs.merge(previous.selectedRouteIDs) { _, previous in previous }
}
if let pointID = state.selectedPointID, let index = state.points.firstIndex(where: { $0.id == pointID }) {
let point = state.points[index]
let range: DroneShootingRange
switch scenario {
case .outOfRange: range = .outside(distanceText: "800 m")
case .unknownRange: range = .unknown
default: range = .inside
}
state.points[index] = DroneShootingPoint(id: point.id, name: point.name, range: range, successfulCount: point.successfulCount)
if scenario == .noRoutes {
state.routesByPointID[pointID] = []
state.selectedRouteIDs[pointID] = nil
}
}
shootingPreparations[key] = state
if scenario == .noPoints {
shootingPreparations[key]?.points = []
shootingPreparations[key]?.selectedPointID = nil
shootingPreparations[key]?.selectedRouteIDs = [:]
shootingPreparations[key]?.routesByPointID = [:]
}
let deviceState: DroneDockDeviceState
switch scenario {
case .occupied: deviceState = .occupied
case .disconnected: deviceState = .disconnected
case .noSignal: deviceState = .noSignal
case .lowBattery: deviceState = .lowBattery
case .unknown: deviceState = .unknown
default: deviceState = .ready
}
let telemetry = scenario == .unknown || scenario == .disconnected || scenario == .noSignal
? DroneDockTelemetry.unknown
: DroneDockTelemetry(batteryPercent: scenario == .lowBattery ? 18 : 95, temperatureCelsius: 20.3, windSpeed: 0, rainDescription: "无雨", signalDescription: "良好", satelliteCount: 36)
setShootingDeviceState(deviceState, telemetry: telemetry)
}
func applyTaskScenario(_ scenario: DroneShootingTaskScenario, orderID: String) {
guard var session = shootingSession(orderID: orderID) else { return }
let key = shootingKey(orderID)
if scenario == .synchronized {
let unresolvedStart = session.commands[.start]?.status.isUnresolved == true
receiveShootingEvent(.synchronized(
phase: unresolvedStart ? .shooting : session.phase,
result: unresolvedStart ? .inProgress : session.result,
flightFinished: session.isFlightFinished, deviceReady: session.deviceReady
), orderID: orderID, taskID: session.id)
return
}
session.phase = .arrived
session.result = .notStarted
session.isFlightFinished = false
session.deviceReady = false
session.phoneConnection = .connected
session.feedConnection = .connected
session.commands = [:]
session.failureReason = nil
session.protectiveReturnReason = nil
session.phaseBeforePause = nil
session.resultNoticeDismissed = false
session.telemetry = DroneDockTelemetry(batteryPercent: 95, temperatureCelsius: 20.3, windSpeed: 0, rainDescription: "无雨", signalDescription: "良好", satelliteCount: 36)
switch scenario {
case .navigating: session.phase = .navigating
case .arrived: break
case .shooting, .pauseProcessing, .streamLost:
session.phase = .shooting
session.result = .inProgress
if scenario == .pauseProcessing { session.commands[.pause] = DroneShootingCommand(kind: .pause, status: .processing) }
if scenario == .streamLost { session.feedConnection = .disconnected }
case .shootingPaused, .resumeProcessing:
session.phase = .shootingPaused
session.phaseBeforePause = .shooting
session.result = .inProgress
if scenario == .resumeProcessing { session.commands[.resume] = DroneShootingCommand(kind: .resume, status: .processing) }
case .returning: session.phase = .returning
case .returnPaused:
session.phase = .returnPaused
session.phaseBeforePause = .returning
case .succeededReturning, .succeededFinished:
session.phase = .returning
session.result = .succeeded
session.isFlightFinished = scenario == .succeededFinished
session.deviceReady = session.isFlightFinished
case .failedReturning, .failedReady:
session.phase = .returning
session.result = .failed
session.failureReason = "拍摄指令执行失败"
session.isFlightFinished = scenario == .failedReady
session.deviceReady = session.isFlightFinished
case .phoneOffline:
session.phase = .shooting
session.result = .inProgress
session.phoneConnection = .disconnected
case .protectiveReturn:
session.phase = .returning
session.result = .unknown
session.protectiveReturnReason = "电量不足"
session.telemetry = DroneDockTelemetry(batteryPercent: 18, temperatureCelsius: 20.3, windSpeed: 0, rainDescription: "无雨", signalDescription: "良好", satelliteCount: 36)
case .commandUnconfirmed: session.commands[.start] = DroneShootingCommand(kind: .start, status: .unconfirmed)
case .commandRejected: session.commands[.start] = DroneShootingCommand(kind: .start, status: .rejected(message: "设备拒绝开始拍摄,请检查当前状态。"))
case .synchronized: break
}
shootingSessions[key] = session
setShootingDeviceState(.occupied, telemetry: session.telemetry)
projectShootingSession(orderID: orderID)
}
}
#endif
+28 -1
View File
@@ -6,7 +6,8 @@ import UIKit
enum DroneDockPreview {
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
static func navigationController(arguments: [String]) -> UINavigationController? {
guard arguments.contains("--dock-ui-preview") || arguments.contains("--dock-ui-orders-preview") else { return nil }
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview"]
guard arguments.contains(where: { entryFlags.contains($0) }) else { return nil }
let store = DroneDockDemoStore()
if let argument = arguments.first(where: { $0.hasPrefix("--dock-ui-scenario=") }),
let scenario = DroneDockDemoScenario(rawValue: String(argument.dropFirst("--dock-ui-scenario=".count))) {
@@ -21,6 +22,32 @@ enum DroneDockPreview {
orders.delegate = workbench
navigation.setViewControllers([workbench, orders], animated: false)
}
if arguments.contains("--dock-ui-preparation-preview") || arguments.contains("--dock-ui-task-preview") {
guard let order = store.orders.first(where: { $0.activeTask != nil })
?? store.orders.first(where: { $0.id.hasSuffix("-order-2") }) else { return navigation }
let preparationViewModel = DroneShootingPreparationViewModel(store: store, orderID: order.id)
if let argument = arguments.first(where: { $0.hasPrefix("--dock-preparation-scenario=") }),
let scenario = DroneShootingPreparationScenario(rawValue: String(argument.dropFirst("--dock-preparation-scenario=".count))) {
preparationViewModel.applyScenario(scenario)
}
let preparation = DroneShootingPreparationViewController(viewModel: preparationViewModel)
preparation.delegate = workbench
var controllers: [UIViewController] = [workbench, preparation]
if arguments.contains("--dock-ui-task-preview") {
if store.shootingSession(orderID: order.id) == nil {
_ = preparationViewModel.summon()
_ = preparationViewModel.confirmSummon()
}
let taskViewModel = DroneShootingTaskViewModel(store: store, orderID: order.id)
let scenarioArgument = arguments.first { $0.hasPrefix("--dock-task-scenario=") }
let scenario = scenarioArgument.flatMap { DroneShootingTaskScenario(rawValue: String($0.dropFirst("--dock-task-scenario=".count))) } ?? .arrived
taskViewModel.applyScenario(scenario)
let task = DroneShootingTaskViewController(viewModel: taskViewModel)
task.delegate = workbench
controllers.append(task)
}
navigation.setViewControllers(controllers, animated: false)
}
return navigation
}
}
@@ -209,7 +209,7 @@ final class DroneDockWorkbenchViewController: BaseViewController {
navigationController?.pushViewController(controller, animated: true)
}
/// 当前任务、素材和交付将在后续页面实现;本轮点击只展示对应订单入口。
/// 拍摄进入本地准备/原任务,其他下级业务暂保留入口提示。
private enum OrderEntry { case shooting, materials, delivery }
private func showOrderEntry(id: String, action: OrderEntry) {
@@ -222,8 +222,8 @@ final class DroneDockWorkbenchViewController: BaseViewController {
let detail: String
switch action {
case .shooting:
title = order.primaryAction.title
detail = order.activeTask.map { "当前任务:\($0.phase.title)" } ?? "剩余 \(order.remainingShootingCount) 次拍摄"
openShootingOrder(id: order.id, from: presenter ?? self)
return
case .materials:
title = "查看素材"
detail = order.materialState.title
@@ -236,6 +236,28 @@ final class DroneDockWorkbenchViewController: BaseViewController {
(presenter ?? self).present(alert, animated: true)
}
/// 始终读取当前范围快照,恢复原任务而不因重新进入重复召唤。
private func openShootingOrder(id: String, from presenter: UIViewController) {
guard let order = viewModel.store.shootingOrder(id: id) else { return }
if order.activeTask != nil {
openTask(orderID: id, from: presenter)
} else if order.remainingShootingCount > 0 {
let controller = DroneShootingPreparationViewController(
viewModel: DroneShootingPreparationViewModel(store: viewModel.store, orderID: id)
)
controller.delegate = self
presenter.navigationController?.pushViewController(controller, animated: true)
}
}
private func openTask(orderID: String, from presenter: UIViewController) {
let controller = DroneShootingTaskViewController(
viewModel: DroneShootingTaskViewModel(store: viewModel.store, orderID: orderID)
)
controller.delegate = self
presenter.navigationController?.pushViewController(controller, animated: true)
}
@objc private func receiptTapped() {
showAlert(title: "收款码", message: "套餐收款页面将在后续搭建,当前不会创建订单或发起收款。")
}
@@ -268,6 +290,32 @@ extension DroneDockWorkbenchViewController: DroneShootingOrdersViewControllerDel
}
}
extension DroneDockWorkbenchViewController: DroneShootingPreparationViewControllerDelegate {
func shootingPreparationViewController(_ controller: DroneShootingPreparationViewController, didRequestTaskFor orderID: String) {
openTask(orderID: orderID, from: controller)
}
}
extension DroneDockWorkbenchViewController: DroneShootingTaskViewControllerDelegate {
func shootingTaskViewControllerDidRequestWorkbench(_ controller: DroneShootingTaskViewController) {
navigationController?.popToViewController(self, animated: true)
}
func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestPreparationFor order: DroneShootingOrder) {
guard let navigationController, let index = navigationController.viewControllers.firstIndex(where: { $0 === self }) else { return }
let preparation = DroneShootingPreparationViewController(
viewModel: DroneShootingPreparationViewModel(store: viewModel.store, orderID: order.id)
)
preparation.delegate = self
navigationController.setViewControllers(Array(navigationController.viewControllers.prefix(through: index)) + [preparation], animated: true)
}
func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestMaterialsFor order: DroneShootingOrder) {
guard let order = viewModel.store.shootingOrder(id: order.id) else { return }
showPreviewEntry(order: order, action: .materials, presenter: controller)
}
}
/// 工作台标题及查看全部入口。
private final class DroneDockSectionHeader: UICollectionReusableView {
var onViewAll: (() -> Void)?
@@ -0,0 +1,463 @@
import SnapKit
import UIKit
/// 准备页顶部订单额度摘要,成功次数与剩余次数分别展示。
@MainActor
final class DronePreparationOrderCell: UICollectionViewCell {
private let customerLabel = DroneDockStyle.label(size: 18, weight: .semibold)
private let packageLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
private let completedLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let remainingLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
let separator = UIView()
separator.backgroundColor = DroneDockStyle.border
[customerLabel, packageLabel, completedLabel, remainingLabel, separator].forEach(contentView.addSubview)
customerLabel.adjustsFontSizeToFitWidth = true
customerLabel.minimumScaleFactor = 0.8
customerLabel.snp.makeConstraints { make in
make.top.equalToSuperview().offset(18)
make.leading.equalToSuperview().offset(4)
make.trailing.lessThanOrEqualTo(separator.snp.leading).offset(-12)
}
packageLabel.snp.makeConstraints { make in
make.top.equalTo(customerLabel.snp.bottom).offset(8)
make.leading.equalTo(customerLabel)
make.bottom.equalToSuperview().inset(14)
}
separator.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(94)
make.centerY.equalToSuperview()
make.width.equalTo(1 / UIScreen.main.scale)
make.height.equalTo(54)
}
completedLabel.snp.makeConstraints { make in
make.leading.equalTo(separator.snp.trailing).offset(16)
make.top.equalTo(customerLabel)
make.trailing.lessThanOrEqualToSuperview()
}
remainingLabel.snp.makeConstraints { make in
make.leading.equalTo(completedLabel)
make.top.equalTo(completedLabel.snp.bottom).offset(3)
make.trailing.lessThanOrEqualToSuperview()
}
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 使用订单的权威计数填充摘要,不在视图层扣减额度。
func apply(order: DroneShootingOrder?) {
guard let order else {
customerLabel.text = "订单信息暂不可用"
packageLabel.text = "请返回订单列表重新进入"
completedLabel.text = "已拍摄 — 次"
remainingLabel.attributedText = remainingText("—")
accessibilityLabel = "订单信息暂不可用"
return
}
customerLabel.text = order.customerName
packageLabel.text = "含 \(order.totalShootingCount) 次拍摄"
completedLabel.text = "已拍摄 \(order.successfulShootingCount) 次"
remainingLabel.attributedText = remainingText(String(order.remainingShootingCount))
accessibilityLabel = "\(order.customerName),含\(order.totalShootingCount)次拍摄,已拍摄\(order.successfulShootingCount)次,剩余\(order.remainingShootingCount)次"
}
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]))
text.append(NSAttributedString(string: " 次", attributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: DroneDockStyle.secondary]))
return text
}
}
/// 横向点位小卡,使用原型同款本地缩略图展示演示点位。
@MainActor
final class DronePreparationPointCell: UICollectionViewCell {
private let nameLabel = DroneDockStyle.label(size: 13, weight: .semibold)
private let rangeLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let countLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let locationIcon = UIImageView(image: UIImage(systemName: "mappin.circle.fill"))
private let thumbnail = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.layer.cornerRadius = 7
contentView.layer.borderWidth = 1
contentView.layer.cornerCurve = .continuous
thumbnail.contentMode = .scaleAspectFill
thumbnail.backgroundColor = DroneDockStyle.background
thumbnail.layer.cornerRadius = 5
thumbnail.clipsToBounds = true
locationIcon.contentMode = .scaleAspectFit
[thumbnail, nameLabel, locationIcon, rangeLabel, countLabel].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(8)
make.centerY.equalToSuperview()
make.size.equalTo(48)
}
nameLabel.snp.makeConstraints { make in
make.top.equalToSuperview().offset(10)
make.leading.equalTo(thumbnail.snp.trailing).offset(8)
make.trailing.equalToSuperview().inset(6)
}
locationIcon.snp.makeConstraints { make in
make.leading.equalTo(nameLabel)
make.top.equalTo(nameLabel.snp.bottom).offset(5)
make.size.equalTo(10)
}
rangeLabel.snp.makeConstraints { make in
make.leading.equalTo(locationIcon.snp.trailing).offset(3)
make.centerY.equalTo(locationIcon)
make.trailing.equalToSuperview().inset(5)
}
countLabel.snp.makeConstraints { make in
make.top.equalTo(rangeLabel.snp.bottom).offset(4)
make.leading.equalTo(nameLabel)
make.trailing.equalToSuperview().inset(5)
}
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 仅映射模型提供的范围和次数,已拍摄的点位仍保持可选择。
func apply(point: DroneShootingPoint, selected: Bool) {
nameLabel.text = point.name
thumbnail.image = UIImage(named: point.id == "point-jinque" ? "drone_demo_pagoda" : "drone_demo_mountain")
rangeLabel.text = point.range.title
switch point.range {
case .inside: rangeLabel.textColor = DroneDockStyle.success
case .outside: rangeLabel.textColor = DroneDockStyle.secondary
case .unknown: rangeLabel.textColor = DroneDockStyle.warning
}
locationIcon.tintColor = rangeLabel.textColor
countLabel.text = point.successfulCountText
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : .white
contentView.layer.borderColor = (selected ? DroneDockStyle.primary : DroneDockStyle.border).cgColor
accessibilityLabel = "\(point.name),\(point.range.title),\(point.successfulCountText)"
accessibilityTraits = selected ? [.button, .selected] : .button
accessibilityIdentifier = "drone.preparation.point.\(point.id)"
}
}
/// 纵向单选航线行,点击整行后由 ViewModel 保留有效选择。
@MainActor
final class DronePreparationRouteCell: UICollectionViewCell {
private let nameLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let routeIcon = DronePreparationRouteIconView()
private let checkmark = UIImageView()
private let separator = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.layer.cornerRadius = 8
contentView.layer.cornerCurve = .continuous
checkmark.contentMode = .scaleAspectFit
separator.backgroundColor = DroneDockStyle.border
[routeIcon, nameLabel, checkmark, separator].forEach(contentView.addSubview)
routeIcon.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(12)
make.centerY.equalToSuperview()
make.size.equalTo(40)
}
nameLabel.snp.makeConstraints { make in
make.leading.equalTo(routeIcon.snp.trailing).offset(14)
make.centerY.equalToSuperview()
make.trailing.lessThanOrEqualTo(checkmark.snp.leading).offset(-12)
}
checkmark.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(14)
make.centerY.equalToSuperview()
make.size.equalTo(24)
}
separator.snp.makeConstraints { make in
make.leading.trailing.bottom.equalToSuperview()
make.height.equalTo(1 / UIScreen.main.scale)
}
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 选中样式仅反映现有选择,重复点击不会在视图中取消单选。
func apply(route: DroneShootingRoute, 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)"
}
}
/// 源码绘制的小航线图标,不依赖远程图片和拍摄素材。
@MainActor
final class DronePreparationRouteIconView: UIView {
private var lineColor = DroneDockStyle.secondary
override init(frame: CGRect) {
super.init(frame: frame)
layer.cornerRadius = 10
backgroundColor = UIColor(hex: 0xF0F2F6)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 图标跟随航线选中态使用统一主色。
func apply(selected: Bool) {
lineColor = selected ? DroneDockStyle.primary : UIColor(hex: 0x697487)
backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : UIColor(hex: 0xF0F2F6)
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
let scale = min(rect.width, rect.height) / 40
guard let context = UIGraphicsGetCurrentContext() else { return }
context.saveGState()
context.scaleBy(x: scale, y: scale)
lineColor.setStroke()
let path = UIBezierPath()
path.move(to: CGPoint(x: 22, y: 11))
path.addLine(to: CGPoint(x: 16, y: 11))
path.addCurve(to: CGPoint(x: 16, y: 20), controlPoint1: CGPoint(x: 8, y: 11), controlPoint2: CGPoint(x: 8, y: 20))
path.addLine(to: CGPoint(x: 24, y: 20))
path.addCurve(to: CGPoint(x: 24, y: 29), controlPoint1: CGPoint(x: 32, y: 20), controlPoint2: CGPoint(x: 32, y: 29))
path.addLine(to: CGPoint(x: 18, y: 29))
path.lineWidth = 1.8
path.lineCapStyle = .round
path.stroke()
UIBezierPath(ovalIn: CGRect(x: 25, y: 8, width: 5, height: 5)).stroke()
UIBezierPath(ovalIn: CGRect(x: 10, y: 26, width: 5, height: 5)).stroke()
context.restoreGState()
}
}
/// 点位与航线分区标题,数量来自当前点位的实际航线配置。
@MainActor
final class DronePreparationHeadingView: UICollectionReusableView {
private let titleLabel = DroneDockStyle.label(size: 18, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
let stack = UIStackView(arrangedSubviews: [titleLabel, detailLabel, UIView()])
stack.axis = .horizontal
stack.alignment = .firstBaseline
stack.spacing = 12
addSubview(stack)
stack.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(4)
make.trailing.equalToSuperview()
make.centerY.equalToSuperview().offset(3)
}
titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
accessibilityTraits = .header
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 分开展示标题与较浅的航线数量。
func apply(title: String, detail: String?) {
titleLabel.text = title
detailLabel.text = detail
detailLabel.isHidden = detail == nil
accessibilityLabel = [title, detail].compactMap { $0 }.joined(separator: ",")
}
}
/// 无点位或无航线时保留就地提示,不增加额外的选择弹窗。
@MainActor
final class DronePreparationEmptyCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: UIColor(hex: 0x697487))
private let detailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
let icon = DronePreparationRouteIconView()
icon.backgroundColor = .clear
let stack = UIStackView(arrangedSubviews: [icon, titleLabel, detailLabel])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 14
detailLabel.numberOfLines = 0
detailLabel.textAlignment = .center
contentView.addSubview(stack)
icon.snp.makeConstraints { make in make.size.equalTo(36) }
stack.snp.makeConstraints { make in
make.centerY.equalToSuperview().offset(-8)
make.leading.trailing.equalToSuperview().inset(8)
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 明确区分点位未配置与已选点位没有航线。
func apply(isPointEmpty: Bool) {
titleLabel.text = isPointEmpty ? "暂无可用拍摄点" : "暂无可用航线"
detailLabel.text = isPointEmpty ? "当前景区尚未配置拍摄点" : "请选择其他拍摄点,或稍后重试"
}
}
/// 固定底部许可栏,独立刷新连接、范围、设备与主按钮。
@MainActor
final class DronePreparationFooterView: UIView {
/// 工作人员主动点击主操作时通知控制器。
var onPrimaryTap: (() -> Void)?
/// 结果待确认时由工作人员主动请求同步原召唤状态。
var onRefreshTap: (() -> Void)?
private let connectionLabel = DronePreparationIndicatorView()
private let rangeLabel = DronePreparationIndicatorView()
private let selectionLabel = DroneDockStyle.label(size: 13, weight: .semibold)
private let deviceCaption = DroneDockStyle.label("无人机:", size: 11, color: DroneDockStyle.secondary)
private let deviceLabel = DroneDockStatusLabel()
private let primaryButton = UIButton(type: .system)
private let messageLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let refreshButton = UIButton(type: .system)
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
let statusRow = UIStackView(arrangedSubviews: [connectionLabel, rangeLabel])
statusRow.axis = .horizontal
statusRow.distribution = .fillEqually
let divider = UIView()
divider.backgroundColor = DroneDockStyle.border
let verticalDivider = UIView()
verticalDivider.backgroundColor = DroneDockStyle.border
let deviceRow = UIStackView(arrangedSubviews: [deviceCaption, deviceLabel, UIView()])
deviceRow.axis = .horizontal
deviceRow.alignment = .center
deviceRow.spacing = 3
let summary = UIStackView(arrangedSubviews: [selectionLabel, deviceRow])
summary.axis = .vertical
summary.spacing = 7
messageLabel.textAlignment = .center
messageLabel.numberOfLines = 2
messageLabel.accessibilityIdentifier = "drone.preparation.admission"
refreshButton.setTitle("刷新状态", for: .normal)
refreshButton.setTitleColor(DroneDockStyle.primary, for: .normal)
refreshButton.titleLabel?.font = .systemFont(ofSize: 12, weight: .medium)
refreshButton.accessibilityIdentifier = "drone.preparation.refreshSummon"
refreshButton.addTarget(self, action: #selector(refreshTapped), for: .touchUpInside)
let messageRow = UIStackView(arrangedSubviews: [messageLabel, refreshButton])
messageRow.axis = .horizontal
messageRow.alignment = .center
messageRow.spacing = 6
primaryButton.layer.cornerRadius = 8
primaryButton.layer.cornerCurve = .continuous
primaryButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
primaryButton.titleLabel?.adjustsFontSizeToFitWidth = true
primaryButton.titleLabel?.minimumScaleFactor = 0.85
primaryButton.accessibilityIdentifier = "drone.preparation.summon"
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
[statusRow, divider, summary, primaryButton, messageRow].forEach(addSubview)
statusRow.addSubview(verticalDivider)
statusRow.snp.makeConstraints { make in
make.leading.trailing.top.equalToSuperview()
make.height.equalTo(42)
}
verticalDivider.snp.makeConstraints { make in
make.center.equalToSuperview()
make.width.equalTo(1 / UIScreen.main.scale)
make.height.equalTo(18)
}
divider.snp.makeConstraints { make in
make.top.equalTo(statusRow.snp.bottom)
make.leading.trailing.equalToSuperview()
make.height.equalTo(1 / UIScreen.main.scale)
}
summary.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(20)
make.top.equalTo(divider.snp.bottom).offset(14)
make.trailing.equalTo(primaryButton.snp.leading).offset(-10)
}
primaryButton.snp.makeConstraints { make in
make.top.equalTo(divider.snp.bottom).offset(12)
make.trailing.equalToSuperview().inset(16)
make.width.equalTo(148)
make.height.equalTo(46)
}
refreshButton.snp.makeConstraints { make in
make.width.equalTo(62).priority(999)
make.height.equalTo(26)
}
messageRow.snp.makeConstraints { make in
make.top.equalTo(summary.snp.bottom).offset(10)
make.top.greaterThanOrEqualTo(primaryButton.snp.bottom).offset(9)
make.leading.trailing.equalToSuperview().inset(16)
make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom).inset(10)
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 只绑定 ViewModel 已计算的展示内容和许可,不按电量或连接自行判定可召唤。
func apply(viewModel: DroneShootingPreparationViewModel) {
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
rangeLabel.apply(title: viewModel.rangeTitle, tone: viewModel.rangeTone)
selectionLabel.text = viewModel.selectionSummary
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceState.tone)
primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal)
primaryButton.isEnabled = viewModel.primaryButtonEnabled
primaryButton.backgroundColor = viewModel.primaryButtonEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE1E7F0)
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(UIColor(hex: 0x8792A5), for: .disabled)
messageLabel.text = viewModel.admission.message
messageLabel.textColor = DroneDockStyle.color(for: viewModel.admission.tone)
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
}
@objc private func primaryTapped() { onPrimaryTap?() }
@objc private func refreshTapped() { onRefreshTap?() }
}
/// 连接与范围共用的小型状态图标,图标只映射语义色。
@MainActor
private final class DronePreparationIndicatorView: UIView {
private let icon = UIImageView()
private let label = DroneDockStyle.label(size: 13)
override init(frame: CGRect) {
super.init(frame: frame)
let stack = UIStackView(arrangedSubviews: [icon, label])
stack.axis = .horizontal
stack.alignment = .center
stack.spacing = 6
icon.contentMode = .scaleAspectFit
addSubview(stack)
icon.snp.makeConstraints { make in make.size.equalTo(16) }
stack.snp.makeConstraints { make in
make.center.equalToSuperview()
make.leading.greaterThanOrEqualToSuperview().offset(5)
make.trailing.lessThanOrEqualToSuperview().inset(5)
}
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 绿色为已满足状态,其他语义色保留各自的提示。
func apply(title: String, tone: DroneDockStatusTone) {
label.text = title
label.textColor = tone == .green ? DroneDockStyle.text : DroneDockStyle.color(for: tone)
icon.tintColor = DroneDockStyle.color(for: tone)
icon.image = UIImage(systemName: tone == .green ? "checkmark.circle.fill" : "exclamationmark.circle.fill")
accessibilityLabel = title
}
}
@@ -0,0 +1,260 @@
import SnapKit
import UIKit
/// 准备页只提出查看任务的导航请求,导航栈由机巢入口统一维护。
@MainActor
protocol DroneShootingPreparationViewControllerDelegate: AnyObject {
/// 召唤已明确确认,或工作人员主动查看本订单已有任务。
func shootingPreparationViewController(_ controller: DroneShootingPreparationViewController, didRequestTaskFor orderID: String)
}
/// 拍摄准备页:选择点位与航线,展示订单额度和设备执行许可。
@MainActor
final class DroneShootingPreparationViewController: BaseViewController {
/// 由入口注入的共享订单与准备状态。
let viewModel: DroneShootingPreparationViewModel
/// 将任务导航交回机巢入口,避免页面自行创建任务控制器。
weak var delegate: DroneShootingPreparationViewControllerDelegate?
/// 点位使用横向分区,航线使用纵向分区。
private enum Section: Int, CaseIterable { case order, points, routes }
/// 稳定标识让选择和许可刷新时保留点位的横向滚动位置。
private enum Item: Hashable {
case order, point(String), route(String), emptyPoints, emptyRoutes
}
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private let footerView = DronePreparationFooterView()
private let refreshControl = UIRefreshControl()
/// 准备页与订单页、任务页读取同一个本地状态源。
init(viewModel: DroneShootingPreparationViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 返回页面时刷新配额、选择与设备状态,不提交任何飞行操作。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.refresh()
if dataSource != nil { applySnapshot(animated: false) }
}
override func setupNavigationBar() {
title = "拍摄准备"
navigationItem.backButtonDisplayMode = .minimal
#if DEBUG
let scenarios = DroneShootingPreparationScenario.allCases.map { scenario in
UIAction(title: scenario.title) { [weak self] _ in
guard let self else { return }
self.viewModel.applyScenario(scenario)
self.applySnapshot(animated: true)
}
}
let confirmAction = UIAction(title: "模拟召唤确认", image: UIImage(systemName: "checkmark.circle")) { [weak self] _ in
guard let self else { return }
let confirmed = self.viewModel.confirmSummon()
self.applySnapshot(animated: true)
if confirmed {
self.delegate?.shootingPreparationViewController(self, didRequestTaskFor: self.viewModel.orderID)
}
}
let menu = UIMenu(title: "拍摄准备验收状态", children: [
UIMenu(options: .displayInline, children: scenarios),
UIMenu(options: .displayInline, children: [confirmAction])
])
let item = UIBarButtonItem(image: UIImage(systemName: "slider.horizontal.3"), menu: menu)
item.accessibilityLabel = "拍摄准备验收状态"
item.accessibilityIdentifier = "drone.preparation.scenarios"
navigationItem.rightBarButtonItem = item
#endif
}
override func setupUI() {
view.backgroundColor = DroneDockStyle.background
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.showsVerticalScrollIndicator = false
collectionView.delegate = self
collectionView.accessibilityIdentifier = "drone.preparation.list"
collectionView.register(DronePreparationOrderCell.self, forCellWithReuseIdentifier: "order")
collectionView.register(DronePreparationPointCell.self, forCellWithReuseIdentifier: "point")
collectionView.register(DronePreparationRouteCell.self, forCellWithReuseIdentifier: "route")
collectionView.register(DronePreparationEmptyCell.self, forCellWithReuseIdentifier: "empty")
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.onPrimaryTap = { [weak self] in
guard let self, self.viewModel.primaryButtonEnabled else { return }
let shouldShowTask = self.viewModel.summon()
self.applySnapshot(animated: true)
if shouldShowTask {
self.delegate?.shootingPreparationViewController(self, didRequestTaskFor: self.viewModel.orderID)
}
}
footerView.onRefreshTap = { [weak self] in
guard let self else { return }
self.viewModel.refreshSummonStatus()
self.applySnapshot(animated: true)
}
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] sectionIndex, _ in
guard let self, let section = Section(rawValue: sectionIndex) else { return nil }
let height: NSCollectionLayoutDimension
let width: NSCollectionLayoutDimension
switch section {
case .order:
width = .fractionalWidth(1)
height = .estimated(90)
case .points:
width = self.viewModel.points.isEmpty ? .fractionalWidth(1) : .absolute(144)
height = self.viewModel.points.isEmpty ? .absolute(124) : .absolute(80)
case .routes:
width = .fractionalWidth(1)
height = self.viewModel.routes.isEmpty ? .absolute(200) : .absolute(64)
}
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1), heightDimension: section == .order ? .estimated(90) : .fractionalHeight(1)
))
let group = NSCollectionLayoutGroup.vertical(
layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item]
)
let layoutSection = NSCollectionLayoutSection(group: group)
layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: section == .routes ? 16 : 0, trailing: 16)
if section == .points {
layoutSection.orthogonalScrollingBehavior = self.viewModel.points.isEmpty ? .none : .continuous
layoutSection.interGroupSpacing = 8
}
if section != .order {
let headerHeight: CGFloat = section == .points ? 46 : 64
layoutSection.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(headerHeight)),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top
)]
}
return layoutSection
}
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, indexPath, item in
guard let self else { return nil }
switch item {
case .order:
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: indexPath) as! DronePreparationOrderCell
cell.apply(order: self.viewModel.order)
return cell
case .point(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "point", for: indexPath) as! DronePreparationPointCell
if let point = self.viewModel.points.first(where: { $0.id == id }) {
cell.apply(point: point, selected: self.viewModel.selectedPoint?.id == id)
}
return cell
case .route(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "route", for: indexPath) as! DronePreparationRouteCell
if let route = self.viewModel.routes.first(where: { $0.id == id }) {
cell.apply(route: route, selected: self.viewModel.selectedRoute?.id == id)
}
return cell
case .emptyPoints, .emptyRoutes:
let cell = list.dequeueReusableCell(withReuseIdentifier: "empty", for: indexPath) as! DronePreparationEmptyCell
cell.apply(isPointEmpty: item == .emptyPoints)
return cell
}
}
dataSource.supplementaryViewProvider = { [weak self] list, kind, indexPath in
guard let self, kind == UICollectionView.elementKindSectionHeader else { return nil }
let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "heading", for: indexPath) as! DronePreparationHeadingView
self.applyHeading(header, section: Section(rawValue: indexPath.section))
return header
}
}
private func applySnapshot(animated: Bool) {
guard isViewLoaded, dataSource != nil else { return }
let previous = dataSource.snapshot()
let existingItems = Set(previous.itemIdentifiers)
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections(Section.allCases)
snapshot.appendItems([.order], toSection: .order)
snapshot.appendItems(viewModel.points.isEmpty ? [.emptyPoints] : viewModel.points.map { .point($0.id) }, toSection: .points)
snapshot.appendItems(viewModel.routes.isEmpty ? [.emptyRoutes] : viewModel.routes.map { .route($0.id) }, toSection: .routes)
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existingItems.contains($0) })
footerView.apply(viewModel: viewModel)
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
guard let self else { return }
let kind = UICollectionView.elementKindSectionHeader
for indexPath in self.collectionView.indexPathsForVisibleSupplementaryElements(ofKind: kind) {
guard let header = self.collectionView.supplementaryView(forElementKind: kind, at: indexPath) as? DronePreparationHeadingView else { continue }
self.applyHeading(header, section: Section(rawValue: indexPath.section))
}
}
let pointEmptinessChanged = previous.itemIdentifiers.contains(.emptyPoints) != snapshot.itemIdentifiers.contains(.emptyPoints)
let routeEmptinessChanged = previous.itemIdentifiers.contains(.emptyRoutes) != snapshot.itemIdentifiers.contains(.emptyRoutes)
if pointEmptinessChanged || routeEmptinessChanged { collectionView.collectionViewLayout.invalidateLayout() }
}
private func applyHeading(_ header: DronePreparationHeadingView, section: Section?) {
switch section {
case .points:
header.apply(title: "拍摄点", detail: nil)
case .routes:
let title = viewModel.selectedPoint.map { "\($0.name)的航线" } ?? "拍摄航线"
header.apply(title: title, detail: "共 \(viewModel.routes.count) 条")
default:
header.apply(title: "", detail: nil)
}
}
@objc private func refreshTriggered() {
viewModel.refresh()
applySnapshot(animated: true)
refreshControl.endRefreshing()
}
}
extension DroneShootingPreparationViewController: UICollectionViewDelegate {
/// 召唤处理中保留滚动浏览,但冻结已提交的点位与航线选择。
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
!viewModel.hasPendingSummon
}
/// 整卡点位与整行航线均可选择;实际有效性和选择恢复由 ViewModel 处理。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard !viewModel.hasPendingSummon, let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .point(let id): viewModel.selectPoint(id: id)
case .route(let id): viewModel.selectRoute(id: id)
default: return
}
applySnapshot(animated: true)
}
}
@@ -0,0 +1,481 @@
import SnapKit
import UIKit
/// 当前任务页面的导航意图;返回始终由工作台协调器处理。
@MainActor
protocol DroneShootingTaskViewControllerDelegate: AnyObject {
/// 直接回工作台,保留原任务,不弹离页确认。
func shootingTaskViewControllerDidRequestWorkbench(_ controller: DroneShootingTaskViewController)
/// 任务确认结束且仍有余次后,进入准备页恢复有效选择。
func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestPreparationFor order: DroneShootingOrder)
/// 查看当前订单的素材;首轮由入口协调器提供占位。
func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestMaterialsFor order: DroneShootingOrder)
}
/// 原任务控制页:独立展示飞行、拍摄结果、连接及指令确认状态。
@MainActor
final class DroneShootingTaskViewController: BaseViewController {
/// 协调工作台、重新准备与素材入口,不在页面内创建新任务。
weak var delegate: (any DroneShootingTaskViewControllerDelegate)?
private let viewModel: DroneShootingTaskViewModel
private let demoBar = UIView()
private let scrollView = UIScrollView()
private let contentStack = UIStackView()
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 feedView = DroneShootingTaskFeedView()
private let telemetryView = DroneShootingTaskTelemetryView()
private let controlPanel = UIView()
private let controlStack = UIStackView()
private let statusIconBackground = UIView()
private let statusIconView = UIImageView()
private let statusTitleLabel = DroneDockStyle.label(size: 21, weight: .semibold)
private let statusMessageLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let commandView = UIView()
private let commandTitleLabel = DroneDockStyle.label(size: 12, weight: .semibold, color: DroneDockStyle.warning)
private let commandMessageLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let refreshTaskButton = UIButton(type: .system)
private let primaryButton = UIButton(type: .system)
private let preparationButton = UIButton(type: .system)
private let materialsButton = UIButton(type: .system)
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 var displayedResultNoticeID: String?
private var interactivePopWasEnabled: Bool?
/// 注入共享数据源上的原任务 ViewModel;构造及页面出现不会发起召唤。
init(viewModel: DroneShootingTaskViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 重进时只读取原任务,等待明确状态,不重发控制指令。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if interactivePopWasEnabled == nil {
interactivePopWasEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled
}
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
viewModel.refresh()
applySnapshot()
}
/// 页面完整呈现后才显示本次结果提示,用户可以稍后查看素材。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
presentResultNoticeIfNeeded()
}
/// 恢复其他页面原有返回手势;本页返回统一直接回工作台。
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let interactivePopWasEnabled {
navigationController?.interactivePopGestureRecognizer?.isEnabled = interactivePopWasEnabled
self.interactivePopWasEnabled = nil
}
}
/// 配置直接返回工作台的导航入口。
override func setupNavigationBar() {
title = "拍摄任务"
navigationItem.hidesBackButton = true
let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(backTapped))
back.tintColor = DroneDockStyle.text
back.accessibilityLabel = "返回机巢工作台"
back.accessibilityIdentifier = "drone.task.back"
navigationItem.leftBarButtonItem = back
}
/// 依原型布局摘要、演示画面、遥测与固定控制区。
override func setupUI() {
view.backgroundColor = .white
setupDemoBar()
scrollView.showsVerticalScrollIndicator = false
scrollView.alwaysBounceVertical = false
scrollView.accessibilityIdentifier = "drone.task.overview"
view.addSubview(scrollView)
contentStack.axis = .vertical
contentStack.spacing = 0
scrollView.addSubview(contentStack)
contentStack.addArrangedSubview(summaryView)
summaryView.addSubview(taskTitleLabel)
summaryView.addSubview(subtitleLabel)
taskTitleLabel.numberOfLines = 2
subtitleLabel.numberOfLines = 1
subtitleLabel.adjustsFontSizeToFitWidth = true
subtitleLabel.minimumScaleFactor = 0.8
contentStack.addArrangedSubview(feedView)
contentStack.addArrangedSubview(telemetryView)
setupControlPanel()
}
/// 上部内容允许在小屏滚动,安全控制始终保持可见。
override func setupConstraints() {
demoBar.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.equalToSuperview()
make.height.equalTo(29)
}
scrollView.snp.makeConstraints { make in
make.top.equalTo(demoBar.snp.bottom)
make.leading.trailing.equalToSuperview()
make.bottom.equalTo(controlPanel.snp.top)
}
contentStack.snp.makeConstraints { make in
make.edges.equalTo(scrollView.contentLayoutGuide)
make.width.equalTo(scrollView.frameLayoutGuide)
}
taskTitleLabel.snp.makeConstraints { make in
make.top.equalToSuperview().offset(10)
make.leading.trailing.equalToSuperview().inset(16)
}
subtitleLabel.snp.makeConstraints { make in
make.top.equalTo(taskTitleLabel.snp.bottom).offset(5)
make.leading.trailing.equalToSuperview().inset(16)
make.bottom.equalToSuperview().inset(10)
}
feedView.snp.makeConstraints { make in
make.height.equalTo(feedView.snp.width).multipliedBy(9.0 / 16.0)
}
controlPanel.snp.makeConstraints { make in
make.leading.trailing.bottom.equalToSuperview()
}
controlStack.snp.makeConstraints { make in
make.top.equalToSuperview().offset(17)
make.leading.trailing.equalToSuperview().inset(16)
make.bottom.equalTo(view.safeAreaLayoutGuide).inset(12)
}
}
/// 将按钮操作交给 ViewModel,提交后主动刷新当前快照。
override func bindActions() {
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
preparationButton.addTarget(self, action: #selector(preparationTapped), for: .touchUpInside)
materialsButton.addTarget(self, action: #selector(materialsTapped), for: .touchUpInside)
pauseButton.addTarget(self, action: #selector(pauseTapped), for: .touchUpInside)
returnButton.addTarget(self, action: #selector(returnTapped), for: .touchUpInside)
refreshTaskButton.addTarget(self, action: #selector(refreshTaskTapped), for: .touchUpInside)
feedView.onExpand = { [weak self] in
let expanded = DroneShootingTaskExpandedFeedViewController()
expanded.modalPresentationStyle = .fullScreen
self?.present(expanded, animated: true)
}
feedView.onReconnect = { [weak self] in
guard let self else { return }
if self.viewModel.phoneConnection == .disconnected {
self.viewModel.reconnectPhone()
} else if self.viewModel.phoneConnection == .connected {
self.viewModel.reconnectFeed()
}
self.applySnapshot()
}
}
private func setupDemoBar() {
demoBar.backgroundColor = UIColor(hex: 0xF3F6FC)
view.addSubview(demoBar)
let label = DroneDockStyle.label("本地界面演示 · 无真实操作", size: 10, color: DroneDockStyle.secondary)
demoBar.addSubview(label)
label.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(16)
make.centerY.equalToSuperview()
}
#if DEBUG
let scenarioButton = UIButton(type: .system)
var configuration = UIButton.Configuration.plain()
configuration.title = "模拟状态"
configuration.image = UIImage(systemName: "slider.horizontal.3")
configuration.imagePadding = 4
configuration.baseForegroundColor = DroneDockStyle.primary
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 11)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = .systemFont(ofSize: 10)
return outgoing
}
scenarioButton.configuration = configuration
scenarioButton.showsMenuAsPrimaryAction = true
scenarioButton.menu = UIMenu(title: "本地模拟事件 · 不自动推进", children: DroneShootingTaskScenario.allCases.map { scenario in
UIAction(title: scenario.title) { [weak self] _ in
self?.viewModel.applyScenario(scenario)
self?.applySnapshot()
self?.presentResultNoticeIfNeeded()
}
})
scenarioButton.accessibilityIdentifier = "drone.task.scenarios"
demoBar.addSubview(scenarioButton)
scenarioButton.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(12)
make.top.bottom.equalToSuperview()
}
#endif
}
private func setupControlPanel() {
controlPanel.backgroundColor = .white
view.addSubview(controlPanel)
controlStack.axis = .vertical
controlStack.spacing = 11
controlPanel.addSubview(controlStack)
let statusRow = UIStackView()
statusRow.axis = .horizontal
statusRow.spacing = 12
statusRow.alignment = .top
statusIconBackground.layer.cornerRadius = 19
statusIconBackground.addSubview(statusIconView)
statusIconView.contentMode = .scaleAspectFit
statusIconView.snp.makeConstraints { make in
make.center.equalToSuperview()
make.size.equalTo(22)
}
statusIconBackground.snp.makeConstraints { make in make.size.equalTo(38) }
let statusTexts = UIStackView(arrangedSubviews: [statusTitleLabel, statusMessageLabel])
statusTexts.axis = .vertical
statusTexts.spacing = 6
statusTitleLabel.numberOfLines = 2
statusTitleLabel.accessibilityTraits = .header
statusTitleLabel.accessibilityIdentifier = "drone.task.statusTitle"
statusMessageLabel.numberOfLines = 0
statusMessageLabel.accessibilityIdentifier = "drone.task.statusMessage"
statusRow.addArrangedSubview(statusIconBackground)
statusRow.addArrangedSubview(statusTexts)
controlStack.addArrangedSubview(statusRow)
setupCommandView()
controlStack.addArrangedSubview(commandView)
controlStack.addArrangedSubview(primaryButton)
primaryButton.accessibilityIdentifier = "drone.task.primary"
primaryButton.snp.makeConstraints { make in make.height.equalTo(49) }
materialsButton.accessibilityIdentifier = "drone.task.materials"
materialsButton.setTitle("查看素材", for: .normal)
materialsButton.setTitleColor(DroneDockStyle.primary, for: .normal)
materialsButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
materialsButton.snp.makeConstraints { make in make.height.equalTo(30).priority(999) }
controlStack.addArrangedSubview(materialsButton)
preparationButton.accessibilityIdentifier = "drone.task.prepareAgain"
preparationButton.setTitle("继续准备拍摄", for: .normal)
preparationButton.setTitleColor(DroneDockStyle.primary, for: .normal)
preparationButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
preparationButton.snp.makeConstraints { make in make.height.equalTo(27).priority(999) }
controlStack.addArrangedSubview(preparationButton)
let safetyHeader = UIView()
let safetyLabel = DroneDockStyle.label("安全控制", size: 10, color: DroneDockStyle.secondary)
let leftLine = UIView()
let rightLine = UIView()
leftLine.backgroundColor = DroneDockStyle.border
rightLine.backgroundColor = DroneDockStyle.border
safetyHeader.addSubview(leftLine)
safetyHeader.addSubview(rightLine)
safetyHeader.addSubview(safetyLabel)
safetyLabel.snp.makeConstraints { make in make.center.equalToSuperview() }
leftLine.snp.makeConstraints { make in
make.leading.centerY.equalToSuperview()
make.trailing.equalTo(safetyLabel.snp.leading).offset(-9)
make.height.equalTo(0.5)
}
rightLine.snp.makeConstraints { make in
make.trailing.centerY.equalToSuperview()
make.leading.equalTo(safetyLabel.snp.trailing).offset(9)
make.height.equalTo(0.5)
}
safetyHeader.snp.makeConstraints { make in make.height.equalTo(13) }
controlStack.addArrangedSubview(safetyHeader)
controlStack.setCustomSpacing(5, after: primaryButton)
controlStack.setCustomSpacing(5, after: safetyHeader)
let safetyButtons = UIStackView(arrangedSubviews: [pauseButton, returnButton])
safetyButtons.axis = .horizontal
safetyButtons.spacing = 8
safetyButtons.distribution = .fillEqually
safetyButtons.snp.makeConstraints { make in make.height.equalTo(62) }
pauseButton.accessibilityIdentifier = "drone.task.pause"
returnButton.accessibilityIdentifier = "drone.task.return"
controlStack.addArrangedSubview(safetyButtons)
}
private func setupCommandView() {
commandView.backgroundColor = UIColor(hex: 0xFFF8EB)
commandView.layer.cornerRadius = 8
commandView.layer.borderColor = UIColor(hex: 0xF4E5C7).cgColor
commandView.layer.borderWidth = 1
let commandStack = UIStackView(arrangedSubviews: [commandTitleLabel, commandMessageLabel, refreshTaskButton])
commandStack.axis = .vertical
commandStack.spacing = 5
commandTitleLabel.numberOfLines = 0
commandMessageLabel.numberOfLines = 0
commandView.addSubview(commandStack)
commandStack.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview().inset(10)
make.bottom.equalToSuperview().inset(10).priority(999)
}
var configuration = UIButton.Configuration.bordered()
configuration.title = "刷新任务状态"
configuration.image = UIImage(systemName: "arrow.clockwise")
configuration.imagePadding = 6
configuration.baseForegroundColor = DroneDockStyle.primary
configuration.background.backgroundColor = .clear
configuration.background.strokeColor = DroneDockStyle.primary.withAlphaComponent(0.5)
configuration.background.strokeWidth = 1
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = .systemFont(ofSize: 12)
return outgoing
}
refreshTaskButton.configuration = configuration
refreshTaskButton.accessibilityIdentifier = "drone.task.sync"
refreshTaskButton.snp.makeConstraints { make in make.height.equalTo(34).priority(999) }
}
private func applySnapshot() {
guard isViewLoaded else { return }
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle
feedView.apply(phone: viewModel.phoneConnection, feed: viewModel.feedConnection, isFlightFinished: viewModel.session?.isFlightFinished == true)
telemetryView.apply(telemetry: viewModel.telemetry, isStale: viewModel.phoneConnection != .connected)
statusTitleLabel.text = viewModel.statusTitle
statusMessageLabel.text = viewModel.statusMessage
let statusColor = DroneDockStyle.color(for: viewModel.statusTone)
statusIconBackground.backgroundColor = statusColor.withAlphaComponent(0.1)
statusIconView.tintColor = statusColor
statusIconView.image = UIImage(systemName: statusSymbol)
commandView.isHidden = viewModel.commandTitle == nil
commandTitleLabel.text = viewModel.commandTitle
commandMessageLabel.text = viewModel.commandMessage
refreshTaskButton.isHidden = !viewModel.shouldShowCommandRefresh
configurePrimaryButton()
materialsButton.isHidden = !(viewModel.session?.result == .succeeded && viewModel.primaryAction != .viewMaterials)
preparationButton.isHidden = !(viewModel.session?.isFlightFinished == true && (viewModel.order?.remainingShootingCount ?? 0) > 0 && viewModel.primaryAction == .viewMaterials)
pauseButton.apply(title: viewModel.pauseTitle, subtitle: viewModel.pauseSubtitle, enabled: viewModel.canPause)
returnButton.apply(title: viewModel.returnTitle, subtitle: viewModel.returnSubtitle, enabled: viewModel.canReturn)
}
private var statusSymbol: String {
if viewModel.phoneConnection != .connected { return "questionmark.circle.fill" }
if viewModel.session?.result == .succeeded { return "checkmark.circle.fill" }
if viewModel.session?.result == .failed { return "exclamationmark.circle.fill" }
switch viewModel.phase {
case .navigating: return "paperplane.fill"
case .arrived: return "checkmark.circle.fill"
case .shooting: return "video.fill"
case .shootingPaused, .returnPaused: return "pause.fill"
case .returning: return "arrow.uturn.backward"
case .unconfirmed, .none: return "questionmark.circle.fill"
}
}
private func configurePrimaryButton() {
var configuration = UIButton.Configuration.filled()
configuration.title = viewModel.primaryTitle
configuration.image = UIImage(systemName: primarySymbol)
configuration.imagePadding = 9
configuration.baseBackgroundColor = DroneDockStyle.primary
configuration.baseForegroundColor = .white
configuration.cornerStyle = .medium
let command = viewModel.session?.command
configuration.showsActivityIndicator = command?.status == .processing && (
(viewModel.primaryAction == .start && command?.kind == .start)
|| (viewModel.primaryAction == .resume && command?.kind == .resume)
)
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 20)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = .systemFont(ofSize: 17, weight: .semibold)
return outgoing
}
primaryButton.configuration = configuration
primaryButton.isEnabled = viewModel.primaryEnabled
primaryButton.alpha = viewModel.primaryEnabled ? 1 : 0.46
}
private var primarySymbol: String {
switch viewModel.primaryAction {
case .start: "camera"
case .resume: "play.fill"
case .viewMaterials: "photo.on.rectangle"
case .prepareAgain: "arrow.clockwise"
case .none: "camera"
}
}
private func presentResultNoticeIfNeeded() {
guard viewIfLoaded?.window != nil, presentedViewController == nil,
let notice = viewModel.resultNotice, displayedResultNoticeID != notice.id else { return }
displayedResultNoticeID = notice.id
let alert = UIAlertController(title: notice.title, message: notice.message, preferredStyle: .alert)
if notice.isSuccess {
alert.addAction(UIAlertAction(title: "稍后再去", style: .cancel) { [weak self] _ in self?.viewModel.dismissResultNotice() })
alert.addAction(UIAlertAction(title: "去查看", style: .default) { [weak self] _ in
guard let self else { return }
self.viewModel.dismissResultNotice()
self.requestMaterials()
})
} else {
alert.addAction(UIAlertAction(title: "知道了", style: .default) { [weak self] _ in self?.viewModel.dismissResultNotice() })
}
present(alert, animated: true)
}
private func requestMaterials() {
guard let order = viewModel.order else { return }
if let delegate {
delegate.shootingTaskViewController(self, didRequestMaterialsFor: order)
} else {
showAlert(title: "素材库", message: "本地界面预览:素材入口将在后续接入。")
}
}
@objc private func materialsTapped() { requestMaterials() }
@objc private func backTapped() {
if let delegate {
delegate.shootingTaskViewControllerDidRequestWorkbench(self)
} else if let workbench = navigationController?.viewControllers.first(where: { $0 is DroneDockWorkbenchViewController }) {
navigationController?.popToViewController(workbench, animated: true)
} else {
navigationController?.popToRootViewController(animated: true)
}
}
@objc private func primaryTapped() {
guard viewModel.primaryEnabled else { return }
switch viewModel.primaryAction {
case .start: _ = viewModel.startShooting()
case .resume: _ = viewModel.resume()
case .viewMaterials: requestMaterials()
case .prepareAgain: preparationTapped()
case .none: break
}
applySnapshot()
}
@objc private func preparationTapped() {
guard let order = viewModel.order, order.remainingShootingCount > 0, viewModel.session?.isFlightFinished == true else { return }
delegate?.shootingTaskViewController(self, didRequestPreparationFor: order)
}
@objc private func pauseTapped() {
guard viewModel.canPause else { return }
_ = viewModel.pause()
applySnapshot()
}
@objc private func returnTapped() {
guard viewModel.canReturn else { return }
_ = viewModel.requestReturn()
applySnapshot()
}
@objc private func refreshTaskTapped() {
viewModel.refreshTaskStatus()
applySnapshot()
presentResultNoticeIfNeeded()
}
}
@@ -0,0 +1,349 @@
import SnapKit
import UIKit
/// 任务页的本地画面演示组件;连接、断流与任务结果分别展示。
@MainActor
final class DroneShootingTaskFeedView: UIView {
/// 用户请求查看本地静帧大图。
var onExpand: (() -> Void)?
/// 用户请求重连手机或画面,具体意图由当前连接状态决定。
var onReconnect: (() -> Void)?
private let imageView = UIImageView(image: UIImage(named: "drone_demo_tourists"))
private let captionLabel = DroneDockStyle.label("演示画面 · 本地静帧", size: 11, color: .white)
private let expandButton = UIButton(type: .system)
private let interruptionView = UIView()
private let interruptionIcon = UIImageView()
private let interruptionTitle = DroneDockStyle.label(size: 16, weight: .semibold)
private let interruptionMessage = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let reconnectButton = UIButton(type: .system)
/// 创建 16:9 本地图片画面,不请求网络,也不播放视频。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 独立应用手机连接与画面连接;完成任务只改变静帧说明。
func apply(phone: DroneShootingConnectionState, feed: DroneShootingConnectionState, isFlightFinished: Bool) {
let phoneUnavailable = phone != .connected
let feedUnavailable = feed != .connected
interruptionView.isHidden = !phoneUnavailable && !feedUnavailable
expandButton.isHidden = phoneUnavailable || feedUnavailable
captionLabel.text = isFlightFinished ? "上次任务画面 · 本地演示" : "演示画面 · 本地静帧"
if phoneUnavailable {
interruptionIcon.image = UIImage(systemName: "wifi.slash")
switch phone {
case .disconnected:
interruptionTitle.text = "手机网络连接中断"
interruptionMessage.text = "状态暂未更新,请恢复连接后同步当前任务"
configureReconnect(title: "重新连接", enabled: true)
case .reconnecting:
interruptionTitle.text = "正在重新连接"
interruptionMessage.text = "等待本地模拟连接回执"
configureReconnect(title: "正在连接", enabled: false)
case .synchronizing:
interruptionTitle.text = "正在同步当前任务"
interruptionMessage.text = "同步确认前请勿重复发送指令"
configureReconnect(title: "正在同步", enabled: false)
case .connected: break
}
} else if feedUnavailable {
interruptionIcon.image = UIImage(systemName: "video.slash")
interruptionTitle.text = feed == .disconnected ? "演示画面连接中断" : "正在重新连接画面"
interruptionMessage.text = "仅画面中断,任务与控制状态分别更新"
configureReconnect(title: feed == .disconnected ? "重新连接画面" : "正在连接画面", enabled: feed == .disconnected)
}
}
private func setupUI() {
backgroundColor = UIColor(hex: 0xE9EEF6)
clipsToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.accessibilityLabel = "游客取景示意,本地演示静帧"
addSubview(imageView)
let captionBackground = UIView()
captionBackground.backgroundColor = UIColor.black.withAlphaComponent(0.38)
captionBackground.layer.cornerRadius = 5
captionBackground.addSubview(captionLabel)
addSubview(captionBackground)
captionBackground.snp.makeConstraints { make in
make.leading.top.equalToSuperview().inset(12)
}
captionLabel.snp.makeConstraints { make in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 5, left: 7, bottom: 5, right: 7)) }
expandButton.setImage(UIImage(systemName: "arrow.up.left.and.arrow.down.right"), for: .normal)
expandButton.tintColor = .white
expandButton.backgroundColor = UIColor.black.withAlphaComponent(0.35)
expandButton.layer.cornerRadius = 18
expandButton.accessibilityLabel = "放大本地演示画面"
expandButton.accessibilityIdentifier = "drone.task.feed.expand"
expandButton.addTarget(self, action: #selector(expandTapped), for: .touchUpInside)
addSubview(expandButton)
interruptionView.backgroundColor = UIColor(hex: 0xE9EEF6)
addSubview(interruptionView)
interruptionIcon.contentMode = .scaleAspectFit
interruptionIcon.tintColor = UIColor(hex: 0x8992A3)
interruptionTitle.textAlignment = .center
interruptionMessage.textAlignment = .center
interruptionMessage.numberOfLines = 0
interruptionView.addSubview(interruptionIcon)
interruptionView.addSubview(interruptionTitle)
interruptionView.addSubview(interruptionMessage)
interruptionView.addSubview(reconnectButton)
reconnectButton.accessibilityIdentifier = "drone.task.feed.reconnect"
reconnectButton.addTarget(self, action: #selector(reconnectTapped), for: .touchUpInside)
}
private func setupConstraints() {
imageView.snp.makeConstraints { make in make.edges.equalToSuperview() }
expandButton.snp.makeConstraints { make in
make.trailing.bottom.equalToSuperview().inset(12)
make.size.equalTo(36)
}
interruptionView.snp.makeConstraints { make in make.edges.equalToSuperview() }
interruptionIcon.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.centerY.equalToSuperview().offset(-49)
make.size.equalTo(30)
}
interruptionTitle.snp.makeConstraints { make in
make.top.equalTo(interruptionIcon.snp.bottom).offset(11)
make.leading.trailing.equalToSuperview().inset(16)
}
interruptionMessage.snp.makeConstraints { make in
make.top.equalTo(interruptionTitle.snp.bottom).offset(5)
make.leading.trailing.equalToSuperview().inset(18)
}
reconnectButton.snp.makeConstraints { make in
make.top.equalTo(interruptionMessage.snp.bottom).offset(11)
make.centerX.equalToSuperview()
make.height.equalTo(34)
}
}
private func configureReconnect(title: String, enabled: Bool) {
var configuration = UIButton.Configuration.bordered()
configuration.title = title
configuration.baseForegroundColor = DroneDockStyle.primary
configuration.background.strokeColor = DroneDockStyle.primary.withAlphaComponent(0.5)
configuration.background.strokeWidth = 1
configuration.background.backgroundColor = .clear
configuration.cornerStyle = .medium
configuration.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 16, bottom: 6, trailing: 16)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = .systemFont(ofSize: 12, weight: .medium)
return outgoing
}
reconnectButton.configuration = configuration
reconnectButton.isEnabled = enabled
}
@objc private func expandTapped() { onExpand?() }
@objc private func reconnectTapped() { onReconnect?() }
}
/// 任务页六项遥测格;手机断网或读数缺失时保留未知值。
@MainActor
final class DroneShootingTaskTelemetryView: UIView {
private let stackView = UIStackView()
private let staleLabel = DroneDockStyle.label("ⓘ 状态暂未更新", size: 11, color: DroneDockStyle.secondary)
private var cells: [DroneShootingTaskTelemetryCell] = []
/// 以两行三列固定展示电量、温度、风速、雨量、信号与搜星。
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = DroneDockStyle.background
stackView.axis = .vertical
stackView.spacing = 6
stackView.alignment = .fill
addSubview(stackView)
stackView.addArrangedSubview(staleLabel)
let definitions = [
("电池电量", "battery.75percent"), ("环境温度", "thermometer.medium"), ("风速", "wind"),
("雨量", "cloud.rain"), ("信号状态", "cellularbars"), ("搜星状态", "location.north.circle")
]
for rowIndex in 0..<2 {
let row = UIStackView()
row.axis = .horizontal
row.distribution = .fillEqually
row.spacing = 6
for columnIndex in 0..<3 {
let definition = definitions[rowIndex * 3 + columnIndex]
let cell = DroneShootingTaskTelemetryCell(title: definition.0, symbol: definition.1)
cells.append(cell)
row.addArrangedSubview(cell)
}
stackView.addArrangedSubview(row)
row.snp.makeConstraints { make in make.height.equalTo(55) }
}
stackView.snp.makeConstraints { make in make.edges.equalToSuperview().inset(10) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 新快照覆盖全部读数;不保留断网前的值冒充有效数据。
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]
for (index, cell) in cells.enumerated() {
cell.apply(value: values[index], isStale: isStale)
}
}
}
/// 单项遥测读数,标题与图标保持稳定位置。
@MainActor
private final class DroneShootingTaskTelemetryCell: UIView {
private let valueLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let iconView: UIImageView
/// 创建标题、图标与数值的紧凑展示。
init(title: String, symbol: String) {
iconView = UIImageView(image: UIImage(systemName: symbol))
super.init(frame: .zero)
backgroundColor = .white
layer.cornerRadius = 7
let titleLabel = DroneDockStyle.label(title, size: 11, color: DroneDockStyle.secondary)
titleLabel.textAlignment = .center
iconView.contentMode = .scaleAspectFit
let valueRow = UIStackView(arrangedSubviews: [iconView, valueLabel])
valueRow.axis = .horizontal
valueRow.spacing = 6
valueRow.alignment = .center
addSubview(titleLabel)
addSubview(valueRow)
iconView.snp.makeConstraints { make in make.size.equalTo(17) }
titleLabel.snp.makeConstraints { make in
make.top.equalToSuperview().offset(7)
make.leading.trailing.equalToSuperview().inset(4)
}
valueRow.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.top.equalTo(titleLabel.snp.bottom).offset(4)
make.leading.greaterThanOrEqualToSuperview().offset(4)
make.trailing.lessThanOrEqualToSuperview().offset(-4)
}
valueLabel.adjustsFontSizeToFitWidth = true
valueLabel.minimumScaleFactor = 0.8
isAccessibilityElement = true
accessibilityLabel = title
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 更新数值和有效性,不根据电量自行推导执行许可。
func apply(value: String, isStale: Bool) {
valueLabel.text = value
valueLabel.textColor = isStale ? DroneDockStyle.secondary : DroneDockStyle.text
iconView.tintColor = isStale ? DroneDockStyle.secondary : DroneDockStyle.primary
accessibilityValue = value
}
}
/// 安全控制按钮,双行文案分别表达指令及当前执行状态。
@MainActor
final class DroneShootingTaskSafetyButton: UIButton {
private let controlTitleLabel = DroneDockStyle.label(size: 15, weight: .semibold)
private let controlSubtitleLabel = DroneDockStyle.label(size: 10)
private let controlIconView: UIImageView
/// 创建暂停或返航按钮;返回状态只由 ViewModel 决定。
init(symbol: String, color: UIColor, filled: Bool) {
controlIconView = UIImageView(image: UIImage(systemName: symbol))
super.init(frame: .zero)
layer.cornerRadius = 9
layer.borderWidth = filled ? 0 : 1
layer.borderColor = color.withAlphaComponent(0.6).cgColor
backgroundColor = filled ? color : color.withAlphaComponent(0.05)
controlTitleLabel.textColor = filled ? .white : color
controlSubtitleLabel.textColor = filled ? UIColor.white.withAlphaComponent(0.85) : DroneDockStyle.secondary
controlIconView.tintColor = filled ? .white : color
controlIconView.contentMode = .scaleAspectFit
let titles = UIStackView(arrangedSubviews: [controlTitleLabel, controlSubtitleLabel])
titles.axis = .vertical
titles.spacing = 3
titles.alignment = .leading
let content = UIStackView(arrangedSubviews: [controlIconView, titles])
content.axis = .horizontal
content.spacing = 10
content.alignment = .center
content.isUserInteractionEnabled = false
addSubview(content)
content.snp.makeConstraints { make in
make.center.equalToSuperview()
make.leading.greaterThanOrEqualToSuperview().offset(9)
make.trailing.lessThanOrEqualToSuperview().offset(-9)
}
controlIconView.snp.makeConstraints { make in make.size.equalTo(27) }
controlTitleLabel.adjustsFontSizeToFitWidth = true
controlTitleLabel.minimumScaleFactor = 0.8
controlSubtitleLabel.adjustsFontSizeToFitWidth = true
controlSubtitleLabel.minimumScaleFactor = 0.8
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 应用语义明确的按钮标题、辅助说明及防重复点击状态。
func apply(title: String, subtitle: String, enabled: Bool) {
controlTitleLabel.text = title
controlSubtitleLabel.text = subtitle
isEnabled = enabled
alpha = enabled ? 1 : 0.42
accessibilityLabel = title
accessibilityValue = subtitle
}
}
/// 任务本地静帧的全屏放大页,明确标记画面来源。
@MainActor
final class DroneShootingTaskExpandedFeedViewController: UIViewController {
/// 显示同一张本地静帧;不建立视频连接。
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(hex: 0x141923)
let imageView = UIImageView(image: UIImage(named: "drone_demo_tourists"))
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.accessibilityLabel = "游客取景示意,本地演示静帧"
let caption = DroneDockStyle.label("演示画面 · 本地静帧 · 16:9", size: 12, color: UIColor(hex: 0xA7AFBE))
caption.textAlignment = .center
let close = UIButton(type: .system)
close.setImage(UIImage(systemName: "xmark"), for: .normal)
close.tintColor = .white
close.accessibilityLabel = "关闭放大画面"
close.accessibilityIdentifier = "drone.task.closeExpandedFeed"
close.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
view.addSubview(imageView)
view.addSubview(caption)
view.addSubview(close)
imageView.snp.makeConstraints { make in
make.leading.trailing.centerY.equalToSuperview()
make.height.equalTo(imageView.snp.width).multipliedBy(9.0 / 16.0)
}
caption.snp.makeConstraints { make in
make.top.equalTo(imageView.snp.bottom).offset(16)
make.leading.trailing.equalToSuperview().inset(20)
}
close.snp.makeConstraints { make in
make.top.trailing.equalTo(view.safeAreaLayoutGuide).inset(12)
make.size.equalTo(44)
}
}
@objc private func closeTapped() { dismiss(animated: true) }
}