704 lines
35 KiB
Swift
704 lines
35 KiB
Swift
import Foundation
|
|
|
|
/// 拍摄任务状态及可选控制流程,始终复用同一任务;禁飞调试仅为本地模拟注入操作服务。
|
|
final class DroneDockShootingTaskViewModel {
|
|
/// 页面绑定的账号、景区和门店身份。
|
|
let context: DroneDockHomeContext
|
|
/// 创建并召唤时使用的同一订单飞行任务 ID。
|
|
let taskID: Int
|
|
/// 进入页面携带的订单摘要,仅作未返回展示字段时的订单文案备用。
|
|
let order: DroneDockHomeOrder
|
|
/// 最近一次通过身份检查的服务端快照,刷新期间保留,成功后整体替换。
|
|
private(set) var response: DroneDockShootingResponse?
|
|
/// 同一页面最多存在一个读取请求。
|
|
private(set) var isLoading = false
|
|
/// 读取失败或身份变化时的提示。
|
|
private(set) var errorMessage: String?
|
|
/// 开拍提交及其后单次状态核对期间禁用重复操作,保留之前的显示快照。
|
|
private(set) var isStartingShooting = false
|
|
/// 开拍业务拒绝、本地拦截或结果待核对的说明。
|
|
private(set) var startErrorMessage: String?
|
|
/// 已发送但无法确认的开拍请求,不因后续读取仍允许开始而自动解除。
|
|
private(set) var startOutcomeUnknown = false
|
|
/// 当前页面是否已收到明确开拍受理回执,收到后不会再次提交。
|
|
private(set) var hasSubmittedStart = false
|
|
/// 同任务开拍回执;受理成功不直接替代 shooting 的完整状态快照。
|
|
private(set) var startResponse: DroneDockStartShootResponse?
|
|
/// 指令提交及其后单次回查期间锁定控制动作,旧状态继续展示。
|
|
private(set) var isSendingCommand = false
|
|
/// 当前正在提交或核对的指令;结束后清空。
|
|
private(set) var activeCommand: DroneDockSafetyCommand?
|
|
/// 最近一次明确受理且身份一致的指令回执,不作为设备已执行的证据。
|
|
private(set) var commandResponse: DroneDockCommandResponse?
|
|
/// 指令业务拒绝、本地拦截或结果待核对提示。
|
|
private(set) var commandErrorMessage: String?
|
|
/// 已发但结果不明确时保持锁定,普通读取不能自动解除或重发。
|
|
private(set) var commandOutcomeUnknown = false
|
|
/// 重新召唤提交及其后单次回查期间保留旧画面并锁定其他操作。
|
|
private(set) var isResummoning = false
|
|
/// 重新召唤明确拒绝、本地拦截或待核对的说明。
|
|
private(set) var resummonErrorMessage: String?
|
|
/// 请求已发送但受理结果未知,普通刷新不能解除重发锁。
|
|
private(set) var resummonOutcomeUnknown = false
|
|
/// 当前页面已受理一次重召唤;旧失败快照不能使同一请求再次提交。
|
|
private(set) var hasSubmittedResummon = false
|
|
/// 重新召唤的原始受理回执,不替代 shooting 的设备状态。
|
|
private(set) var resummonResponse: DroneDockShootResponse?
|
|
|
|
private let service: any DroneDockShootingServing
|
|
private let startService: (any DroneDockStartShooting)?
|
|
private let commandService: (any DroneDockCommandSending)?
|
|
private let resummonService: (any DroneDockResummonServing)?
|
|
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
|
private var generation = 0
|
|
private var identityInvalidated = false
|
|
private var startGeneration = 0
|
|
private var didSendStart = false
|
|
private var commandGeneration = 0
|
|
private var didSendCommand = false
|
|
private var resummonGeneration = 0
|
|
private var didSendResummon = false
|
|
private var awaitingResummonSnapshot = false
|
|
// 回查仍提供的已受理指令分别保留防重锁,避免另一条指令受理覆盖旧锁。
|
|
private var pendingAcceptedCommands: Set<DroneDockSafetyCommand> = []
|
|
|
|
/// 默认只读;仅显式注入模拟操作服务时开放对应动作,当前正式入口不注入。
|
|
init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder,
|
|
service: any DroneDockShootingServing,
|
|
startService: (any DroneDockStartShooting)? = nil,
|
|
commandService: (any DroneDockCommandSending)? = nil,
|
|
resummonService: (any DroneDockResummonServing)? = nil,
|
|
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
|
self.context = context
|
|
self.taskID = taskID
|
|
self.order = order
|
|
self.service = service
|
|
self.startService = startService
|
|
self.commandService = commandService
|
|
self.resummonService = resummonService
|
|
self.currentContext = currentContext
|
|
}
|
|
|
|
/// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。
|
|
@MainActor
|
|
func refresh() async {
|
|
await refreshSnapshot(allowWhileStarting: false)
|
|
}
|
|
|
|
@MainActor
|
|
private func refreshSnapshot(allowWhileStarting: Bool, allowWhileCommand: Bool = false,
|
|
allowWhileResummoning: Bool = false) async {
|
|
guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting,
|
|
!isSendingCommand || allowWhileCommand, !isResummoning || allowWhileResummoning else { return }
|
|
generation &+= 1
|
|
let requestGeneration = generation
|
|
isLoading = true
|
|
errorMessage = nil
|
|
defer {
|
|
if generation == requestGeneration {
|
|
isLoading = false
|
|
}
|
|
}
|
|
guard accepts(requestGeneration) else { return }
|
|
guard context.canLoad, taskID > 0,
|
|
DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
|
|
response = nil
|
|
errorMessage = "缺少有效任务、订单或景区信息,请返回工作台重新进入"
|
|
return
|
|
}
|
|
do {
|
|
let value = try await service.shooting(taskID: taskID, liveBattery: false)
|
|
guard accepts(requestGeneration) else { return }
|
|
guard matchesIdentity(value) else {
|
|
response = nil
|
|
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
|
|
}
|
|
response = value
|
|
if awaitingResummonSnapshot, [.navigating, .ready, .shooting, .paused, .returning, .completed].contains(resolvedDisplayPhase().0) {
|
|
awaitingResummonSnapshot = false
|
|
}
|
|
pendingAcceptedCommands.formIntersection(availableSafetyCommands)
|
|
} catch {
|
|
guard accepts(requestGeneration) else { return }
|
|
errorMessage = error is CancellationError ? nil : error.localizedDescription
|
|
}
|
|
}
|
|
|
|
/// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。
|
|
@MainActor
|
|
func invalidate(preservingSnapshot: Bool = false) {
|
|
invalidateStartShooting()
|
|
invalidateCommand()
|
|
invalidateResummon()
|
|
generation &+= 1
|
|
isLoading = false
|
|
if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true }
|
|
if identityInvalidated {
|
|
response = nil
|
|
startResponse = nil
|
|
startErrorMessage = nil
|
|
commandResponse = nil
|
|
commandErrorMessage = nil
|
|
resummonResponse = nil
|
|
resummonErrorMessage = nil
|
|
pendingAcceptedCommands.removeAll()
|
|
errorMessage = "账号或景区已变化,请返回工作台重新进入"
|
|
} else {
|
|
if !preservingSnapshot { response = nil }
|
|
errorMessage = nil
|
|
}
|
|
}
|
|
|
|
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。
|
|
var canStartShooting: Bool {
|
|
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
|
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
|
&& !hasSubmittedStart && !startOutcomeUnknown
|
|
&& !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot && pendingAcceptedCommands.isEmpty
|
|
&& resolvedDisplayPhase().0 == .ready
|
|
&& response?.executeGate?.canExecute == true
|
|
&& response?.executeGate?.primaryAction == "start_shoot"
|
|
&& (response?.currentPlane?.id ?? 0) > 0
|
|
}
|
|
|
|
/// 提交一次开拍并单次读取同任务;失败保留原快照,不轮询、不重建、不自动重发。
|
|
@MainActor
|
|
func startShooting(onStateChange: @escaping @MainActor () -> Void = {}) async {
|
|
guard canStartShooting, let startService else { return }
|
|
guard context.hasSameIdentity(as: currentContext()) else {
|
|
identityInvalidated = true
|
|
invalidate()
|
|
onStateChange()
|
|
return
|
|
}
|
|
guard !Task.isCancelled else { return }
|
|
let planeID = response?.currentPlane?.id
|
|
startGeneration &+= 1
|
|
let requestGeneration = startGeneration
|
|
isStartingShooting = true
|
|
didSendStart = false
|
|
startErrorMessage = nil
|
|
onStateChange()
|
|
defer {
|
|
if startGeneration == requestGeneration {
|
|
if Task.isCancelled && didSendStart && !hasSubmittedStart { markStartUnknown() }
|
|
isStartingShooting = false
|
|
didSendStart = false
|
|
onStateChange()
|
|
}
|
|
}
|
|
guard acceptsStart(requestGeneration) else { return }
|
|
do {
|
|
didSendStart = true
|
|
let value = try await startService.startShooting(taskID: taskID)
|
|
guard acceptsStart(requestGeneration) else { return }
|
|
guard value.orderFlightTaskID == taskID,
|
|
value.orderFlightTask?.id == nil || value.orderFlightTask?.id == taskID,
|
|
value.orderFlightTask?.orderNumber == nil || value.orderFlightTask?.orderNumber == order.orderNumber,
|
|
value.orderFlightTask?.scenicID == nil || value.orderFlightTask?.scenicID == context.scenicID,
|
|
value.planeID == nil || value.planeID == planeID else {
|
|
throw APIError.decodeFailed("开始拍摄回执与当前任务或飞机不一致,请先核对任务状态")
|
|
}
|
|
startResponse = value
|
|
hasSubmittedStart = true
|
|
startOutcomeUnknown = false
|
|
onStateChange()
|
|
guard acceptsStart(requestGeneration) else { return }
|
|
await refreshSnapshot(allowWhileStarting: true)
|
|
} catch {
|
|
if error is DeviceCommandDebugBlockedError, startGeneration == requestGeneration { didSendStart = false }
|
|
guard acceptsStart(requestGeneration) else { return }
|
|
if error is DeviceCommandDebugBlockedError {
|
|
startErrorMessage = DeviceCommandDebugPolicy.blockedMessage
|
|
} else if case APIError.serverCode = error {
|
|
startErrorMessage = error.localizedDescription
|
|
} else {
|
|
markStartUnknown(reason: error.localizedDescription)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 离页或进入后台后拒绝迟到回执;已发而未确认的请求保留待核对锁。
|
|
@MainActor
|
|
func invalidateStartShooting() {
|
|
if isStartingShooting && didSendStart && !hasSubmittedStart { markStartUnknown() }
|
|
startGeneration &+= 1
|
|
isStartingShooting = false
|
|
didSendStart = false
|
|
}
|
|
|
|
/// 只识别当前快照明确提供的四种指令,未知值忽略,同一指令只展示一次。
|
|
var availableSafetyCommands: [DroneDockSafetyCommand] {
|
|
var commands: [DroneDockSafetyCommand] = []
|
|
for item in response?.ui?.commands ?? [] {
|
|
guard let raw = item.command, let command = DroneDockSafetyCommand(rawValue: raw),
|
|
!commands.contains(command) else { continue }
|
|
commands.append(command)
|
|
}
|
|
return commands
|
|
}
|
|
|
|
/// 安全指令不借用开拍门禁;需明确任务、锁定飞机、当前指令及注入的本地服务。
|
|
func canSendCommand(_ command: DroneDockSafetyCommand) -> Bool {
|
|
commandService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
|
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
|
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown && !awaitingResummonSnapshot
|
|
&& !pendingAcceptedCommands.contains(command)
|
|
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
|
|
&& (response?.currentPlane?.id ?? 0) > 0
|
|
&& availableSafetyCommands.contains(command)
|
|
}
|
|
|
|
/// 只提交当前任务的一次指令,受理后单次回查;不轮询、不改派飞机、不自动重试。
|
|
@MainActor
|
|
func sendCommand(_ command: DroneDockSafetyCommand,
|
|
onStateChange: @escaping @MainActor () -> Void = {}) async {
|
|
guard canSendCommand(command), let commandService else { return }
|
|
guard context.hasSameIdentity(as: currentContext()) else {
|
|
identityInvalidated = true
|
|
invalidate()
|
|
onStateChange()
|
|
return
|
|
}
|
|
guard !Task.isCancelled else { return }
|
|
commandGeneration &+= 1
|
|
let requestGeneration = commandGeneration
|
|
isSendingCommand = true
|
|
activeCommand = command
|
|
didSendCommand = false
|
|
commandResponse = nil
|
|
commandErrorMessage = nil
|
|
onStateChange()
|
|
defer {
|
|
if commandGeneration == requestGeneration {
|
|
if Task.isCancelled && didSendCommand && commandResponse == nil { markCommandUnknown() }
|
|
isSendingCommand = false
|
|
activeCommand = nil
|
|
didSendCommand = false
|
|
onStateChange()
|
|
}
|
|
}
|
|
guard acceptsCommand(requestGeneration) else { return }
|
|
do {
|
|
didSendCommand = true
|
|
let value = try await commandService.sendCommand(taskID: taskID, command: command)
|
|
guard acceptsCommand(requestGeneration) else { return }
|
|
guard value.orderFlightTaskID == taskID, value.command == command.rawValue else {
|
|
throw APIError.decodeFailed("安全指令回执与当前任务或指令不一致,请先核对任务状态")
|
|
}
|
|
commandResponse = value
|
|
pendingAcceptedCommands.insert(command)
|
|
commandOutcomeUnknown = false
|
|
onStateChange()
|
|
guard acceptsCommand(requestGeneration) else { return }
|
|
await refreshSnapshot(allowWhileStarting: false, allowWhileCommand: true)
|
|
} catch {
|
|
if error is DeviceCommandDebugBlockedError, commandGeneration == requestGeneration { didSendCommand = false }
|
|
guard acceptsCommand(requestGeneration) else { return }
|
|
if error is DeviceCommandDebugBlockedError {
|
|
commandErrorMessage = DeviceCommandDebugPolicy.blockedMessage
|
|
} else if case APIError.serverCode = error {
|
|
commandErrorMessage = error.localizedDescription
|
|
} else {
|
|
markCommandUnknown(reason: error.localizedDescription)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 离页或后台取消控制流程;已发而未受理时保留未知结果锁,忽略迟到回执。
|
|
@MainActor
|
|
func invalidateCommand() {
|
|
if isSendingCommand && didSendCommand && commandResponse == nil { markCommandUnknown() }
|
|
commandGeneration &+= 1
|
|
isSendingCommand = false
|
|
activeCommand = nil
|
|
didSendCommand = false
|
|
}
|
|
|
|
/// 本地模拟服务显式注入、当前任务明确失败且没有在途或未知操作时才可重召唤。
|
|
/// 此门禁用于客户端模拟交互,不代表后端已提供真实重试许可。
|
|
var canResummon: Bool {
|
|
resummonService != nil && context.canLoad && taskID > 0 && !identityInvalidated
|
|
&& !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && errorMessage == nil
|
|
&& !startOutcomeUnknown && !commandOutcomeUnknown && !resummonOutcomeUnknown
|
|
&& !hasSubmittedResummon && pendingAcceptedCommands.isEmpty
|
|
&& resolvedDisplayPhase().0 == .failed
|
|
&& (response?.orderFlightTask?.id == taskID || response?.task?.id == taskID)
|
|
&& (response?.currentPlane?.id ?? 0) > 0
|
|
&& !isResummonDeviceUnavailable
|
|
}
|
|
|
|
/// 复用同一任务提交一次 restart=true;受理后只查询一次 shooting,不推断已经到达。
|
|
@MainActor
|
|
func resummon(onStateChange: @escaping @MainActor () -> Void = {}) async {
|
|
guard canResummon, let resummonService else { return }
|
|
guard context.hasSameIdentity(as: currentContext()) else {
|
|
identityInvalidated = true
|
|
invalidate()
|
|
onStateChange()
|
|
return
|
|
}
|
|
guard !Task.isCancelled else { return }
|
|
resummonGeneration &+= 1
|
|
let requestGeneration = resummonGeneration
|
|
isResummoning = true
|
|
didSendResummon = false
|
|
resummonResponse = nil
|
|
resummonErrorMessage = nil
|
|
onStateChange()
|
|
defer {
|
|
if resummonGeneration == requestGeneration {
|
|
if Task.isCancelled && didSendResummon && !hasSubmittedResummon { markResummonUnknown() }
|
|
isResummoning = false
|
|
didSendResummon = false
|
|
onStateChange()
|
|
}
|
|
}
|
|
guard acceptsResummon(requestGeneration) else { return }
|
|
do {
|
|
didSendResummon = true
|
|
let value = try await resummonService.resummon(taskID: taskID)
|
|
guard acceptsResummon(requestGeneration) else { return }
|
|
guard try matchesResummonReceipt(value) else {
|
|
throw APIError.decodeFailed("重新召唤回执与当前任务或订单不一致,请先核对任务状态")
|
|
}
|
|
resummonResponse = value
|
|
hasSubmittedResummon = true
|
|
resummonOutcomeUnknown = false
|
|
awaitingResummonSnapshot = true
|
|
hasSubmittedStart = false
|
|
startResponse = nil
|
|
startErrorMessage = nil
|
|
commandResponse = nil
|
|
commandErrorMessage = nil
|
|
onStateChange()
|
|
guard acceptsResummon(requestGeneration) else { return }
|
|
await refreshSnapshot(allowWhileStarting: false, allowWhileResummoning: true)
|
|
} catch {
|
|
if error is DeviceCommandDebugBlockedError, resummonGeneration == requestGeneration { didSendResummon = false }
|
|
guard acceptsResummon(requestGeneration) else { return }
|
|
if error is DeviceCommandDebugBlockedError {
|
|
resummonErrorMessage = DeviceCommandDebugPolicy.blockedMessage
|
|
} else if case APIError.serverCode = error {
|
|
didSendResummon = false
|
|
resummonErrorMessage = error.localizedDescription
|
|
} else {
|
|
markResummonUnknown(reason: error.localizedDescription)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 离页或进入后台后忽略旧回执;发出后未确认的重新召唤继续保持待核对锁。
|
|
@MainActor
|
|
func invalidateResummon() {
|
|
if isResummoning && didSendResummon && !hasSubmittedResummon { markResummonUnknown() }
|
|
resummonGeneration &+= 1
|
|
isResummoning = false
|
|
didSendResummon = false
|
|
}
|
|
|
|
/// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。
|
|
var title: String {
|
|
if let title = usable(response?.header?.title) { return title }
|
|
let names = [usable(response?.scenicSpot?.name), usable(response?.airLine?.name)].compactMap { $0 }
|
|
return names.isEmpty ? "拍摄任务" : names.joined(separator: " · ")
|
|
}
|
|
|
|
/// 服务端游客和套餐文案优先,后端已返回的套餐不被进入页摘要覆盖。
|
|
var subtitle: String {
|
|
let tourist = usable(response?.header?.touristLabel) ?? usable(order.touristPhoneMask)
|
|
let package = usable(response?.header?.packageName) ?? usable(order.packageName)
|
|
let parts = [tourist, package].compactMap { $0 }
|
|
return parts.isEmpty ? "—" : parts.joined(separator: " · ")
|
|
}
|
|
|
|
/// 只展示本任务当前设备状态,不以景区推荐设备替代任务锁定设备。
|
|
var deviceStatusText: String {
|
|
usable(response?.currentPlane?.statusText) ?? usable(response?.currentPlane?.workStatusLabel) ?? "—"
|
|
}
|
|
|
|
/// 使用服务端阶段标题或任务状态,不从 GET 成功推导到达或拍摄完成。
|
|
var statusTitle: String {
|
|
if response == nil {
|
|
if errorMessage != nil { return "任务状态读取失败" }
|
|
if isLoading { return "正在获取任务状态" }
|
|
}
|
|
if resolvedDisplayPhase().0 == .failed { return "任务执行失败" }
|
|
return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel)
|
|
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
|
|
}
|
|
|
|
/// 保留服务端阶段说明;操作结果未知时优先提示核对,不伪装为设备已执行。
|
|
var statusMessage: String {
|
|
if response == nil {
|
|
if let errorMessage { return errorMessage }
|
|
if isLoading { return "正在读取当前拍摄任务" }
|
|
}
|
|
if let resummonErrorMessage { return resummonErrorMessage }
|
|
if awaitingResummonSnapshot { return "重新召唤请求已受理,请刷新核对任务状态" }
|
|
if let commandErrorMessage { return commandErrorMessage }
|
|
if resolvedDisplayPhase().0 == .failed { return failureMessage }
|
|
if startOutcomeUnknown, let startErrorMessage { return startErrorMessage }
|
|
if resolvedDisplayPhase().0 == .ready {
|
|
if let startErrorMessage { return startErrorMessage }
|
|
if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" }
|
|
}
|
|
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
|
|
}
|
|
|
|
/// 组合可信阶段与本轮可用动作,不从请求成功、执行中或指令列表推断飞行进度。
|
|
var presentation: DroneDockTaskPresentation {
|
|
if response == nil, isLoading {
|
|
return DroneDockTaskPresentation(phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
|
|
deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false)
|
|
}
|
|
if response == nil, let errorMessage {
|
|
return DroneDockTaskPresentation(phase: .readError, title: "任务状态读取失败", message: errorMessage,
|
|
deviceStatus: deviceStatusText, action: .refresh, actionTitle: "重新读取", isActionEnabled: !identityInvalidated)
|
|
}
|
|
let (phase, conflict) = resolvedDisplayPhase()
|
|
let message = conflict ? "任务状态信息不一致,请刷新后确认。" + (statusMessage == "—" ? "" : statusMessage) : statusMessage
|
|
let title = presentationTitle(for: phase, conflict: conflict)
|
|
let action: DroneDockTaskDisplayAction
|
|
let actionTitle: String?
|
|
let enabled: Bool
|
|
switch phase {
|
|
case .ready where hasSubmittedStart || startOutcomeUnknown || commandOutcomeUnknown || resummonOutcomeUnknown:
|
|
action = .refresh
|
|
actionTitle = "刷新状态"
|
|
enabled = !identityInvalidated
|
|
case .ready:
|
|
action = .start
|
|
actionTitle = isStartingShooting ? "正在提交开拍…"
|
|
: startErrorMessage == nil ? (usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄") : "重试开始拍摄"
|
|
enabled = canStartShooting
|
|
case .paused where response?.executeGate?.canExecute == true:
|
|
action = .resume
|
|
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "继续拍摄"
|
|
enabled = false
|
|
case .completed:
|
|
action = .materials
|
|
actionTitle = "查看素材"
|
|
enabled = true
|
|
case .failed where hasSubmittedResummon || resummonOutcomeUnknown:
|
|
action = .refresh
|
|
actionTitle = "刷新状态"
|
|
enabled = !identityInvalidated
|
|
case .failed:
|
|
action = .retry
|
|
actionTitle = isResummoning ? "正在重新召唤…" : "重新召唤无人机"
|
|
enabled = canResummon
|
|
default:
|
|
action = .refresh
|
|
actionTitle = "刷新状态"
|
|
enabled = !identityInvalidated
|
|
}
|
|
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
|
|
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
|
|
isActionEnabled: enabled && !isLoading && !isStartingShooting && !isSendingCommand && !isResummoning && !identityInvalidated && (errorMessage == nil || action == .refresh),
|
|
actionNote: phase == .failed && action == .retry && !canResummon && !isResummoning ? retryUnavailableNote : nil)
|
|
}
|
|
|
|
/// 后端六项展示读数,不解析文案反推设备状态或数值单位。
|
|
var telemetry: DroneDockShootingTelemetry {
|
|
func text(_ key: String) -> String { response?.metrics.first(where: { $0.key == key })?.displayText ?? "—" }
|
|
return DroneDockShootingTelemetry(batteryText: text("battery"), temperatureText: text("env_temp"),
|
|
windText: text("wind_speed"), rainText: text("rainfall"), signalText: text("signal"), satelliteText: text("satellite"))
|
|
}
|
|
|
|
/// 仅无快照时使用未知读数;刷新期间继续展示最近一次成功快照。
|
|
var isTelemetryStale: Bool { response == nil }
|
|
/// 完整服务端 data,供页面展示和联调查看。
|
|
var dataJSON: String? { response?.dataJSON }
|
|
|
|
@MainActor
|
|
private func accepts(_ requestGeneration: Int) -> Bool {
|
|
guard generation == requestGeneration else { return false }
|
|
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
|
|
identityInvalidated = true
|
|
invalidate()
|
|
errorMessage = "账号或景区已变化,请返回工作台重新进入"
|
|
return false
|
|
}
|
|
return !Task.isCancelled
|
|
}
|
|
|
|
@MainActor
|
|
private func acceptsStart(_ requestGeneration: Int) -> Bool {
|
|
guard startGeneration == requestGeneration else { return false }
|
|
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
|
|
identityInvalidated = true
|
|
invalidate()
|
|
return false
|
|
}
|
|
return !Task.isCancelled
|
|
}
|
|
|
|
@MainActor
|
|
private func acceptsCommand(_ requestGeneration: Int) -> Bool {
|
|
guard commandGeneration == requestGeneration else { return false }
|
|
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
|
|
identityInvalidated = true
|
|
invalidate()
|
|
return false
|
|
}
|
|
return !Task.isCancelled
|
|
}
|
|
|
|
@MainActor
|
|
private func acceptsResummon(_ requestGeneration: Int) -> Bool {
|
|
guard resummonGeneration == requestGeneration else { return false }
|
|
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
|
|
identityInvalidated = true
|
|
invalidate()
|
|
return false
|
|
}
|
|
return !Task.isCancelled
|
|
}
|
|
|
|
private func markResummonUnknown(reason: String? = nil) {
|
|
resummonOutcomeUnknown = true
|
|
resummonErrorMessage = (reason.map { "\($0)。" } ?? "") + "重新召唤结果待核对,请刷新任务状态,勿重复提交"
|
|
}
|
|
|
|
/// shoot 顶层 task_id 是实际航线任务 ID;只核对明确的订单任务身份,不混淆两种任务。
|
|
private func matchesResummonReceipt(_ value: DroneDockShootResponse) throws -> Bool {
|
|
guard let json = value.dataJSON else { return true }
|
|
let data = Data(json.utf8)
|
|
guard case .object = try JSONDecoder().decode(DroneDockHomeJSONValue.self, from: data) else { return true }
|
|
let identity = try JSONDecoder().decode(DroneDockResummonReceiptIdentity.self, from: data)
|
|
return (identity.orderFlightTaskID == nil || identity.orderFlightTaskID == taskID)
|
|
&& (identity.orderFlightTask?.id == nil || identity.orderFlightTask?.id == taskID)
|
|
&& (identity.orderFlightTask?.orderNumber == nil || identity.orderFlightTask?.orderNumber == order.orderNumber)
|
|
&& (identity.orderFlightTask?.scenicID == nil || identity.orderFlightTask?.scenicID == context.scenicID)
|
|
&& (identity.planeID == nil || identity.planeID == response?.currentPlane?.id)
|
|
}
|
|
|
|
private func markCommandUnknown(reason: String? = nil) {
|
|
commandOutcomeUnknown = true
|
|
commandErrorMessage = (reason.map { "\($0)。" } ?? "") + "安全指令结果待核对,请刷新任务状态,勿重复提交"
|
|
}
|
|
|
|
private func markStartUnknown(reason: String? = nil) {
|
|
startOutcomeUnknown = true
|
|
startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交"
|
|
}
|
|
|
|
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
|
|
let taskIDs = [value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
|
|
let orderNumbers = [value.orderNumber, value.orderFlightTask?.orderNumber,
|
|
value.task?.orderNumber, value.header?.orderNumber].compactMap { $0 }
|
|
let scenicIDs = [value.scenic?.id, value.orderFlightTask?.scenicID,
|
|
value.task?.scenicID, value.planeStatus?.scenicID].compactMap { $0 }
|
|
return taskIDs.allSatisfy { $0 == taskID }
|
|
&& orderNumbers.allSatisfy { $0 == order.orderNumber }
|
|
&& scenicIDs.allSatisfy { $0 == context.scenicID }
|
|
}
|
|
|
|
/// 只认识显式阶段和已确认任务状态;91 为真实航线执行失败,不把订单状态 20 当作正在拍摄。
|
|
private func resolvedDisplayPhase() -> (DroneDockTaskDisplayPhase, Bool) {
|
|
guard let response else { return (.unknown, false) }
|
|
let tasks = [response.task, response.orderFlightTask].compactMap { $0 }
|
|
let statuses = Set(tasks.compactMap(\.status))
|
|
if tasks.contains(where: { $0.waylineStatus == 91 }) || statuses.contains(40) { return (.failed, false) }
|
|
if statuses.contains(50) { return (.blocked, false) }
|
|
if statuses.count > 1 { return (.unknown, true) }
|
|
let known: [String: DroneDockTaskDisplayPhase] = [
|
|
"navigating": .navigating, "arrived_pending_start": .ready, "shooting": .shooting,
|
|
"paused": .paused, "returning": .returning, "completed": .completed, "failed": .failed, "blocked": .blocked
|
|
]
|
|
let rawPhase = usable(response.ui?.phase)
|
|
let phase = rawPhase.flatMap { known[$0] }
|
|
if rawPhase != nil && phase == nil { return (.unknown, false) }
|
|
if phase == .failed { return (.failed, false) }
|
|
if statuses.contains(30) {
|
|
if phase == .returning { return (.returning, false) }
|
|
if let phase, [.navigating, .ready, .shooting, .paused].contains(phase) { return (.unknown, true) }
|
|
return (.completed, false)
|
|
}
|
|
if phase == .completed {
|
|
return statuses.isEmpty ? (.completed, false) : (.unknown, true)
|
|
}
|
|
if phase == .ready {
|
|
guard let allowed = response.executeGate?.canExecute else { return (.unknown, false) }
|
|
if !allowed { return (.blocked, false) }
|
|
if let action = usable(response.executeGate?.primaryAction), action != "start_shoot" {
|
|
return (.unknown, true)
|
|
}
|
|
}
|
|
if phase == .paused, response.executeGate?.canExecute == true,
|
|
response.executeGate?.primaryAction == "blocked" { return (.unknown, true) }
|
|
return (phase ?? .unknown, false)
|
|
}
|
|
|
|
private func presentationTitle(for phase: DroneDockTaskDisplayPhase, conflict: Bool) -> String {
|
|
if conflict { return "状态待确认" }
|
|
let tasks = [response?.task, response?.orderFlightTask].compactMap { $0 }
|
|
if phase == .failed { return "任务执行失败" }
|
|
if phase == .blocked, let cancelled = tasks.first(where: { $0.status == 50 }) {
|
|
return usable(cancelled.statusLabel) ?? "任务已取消"
|
|
}
|
|
if phase == .blocked, response?.ui?.phase == "arrived_pending_start" { return "暂不可开始拍摄" }
|
|
if phase == .completed {
|
|
return usable(response?.ui?.phase == "completed" ? response?.ui?.title : nil)
|
|
?? tasks.first(where: { $0.status == 30 }).flatMap { usable($0.statusLabel) } ?? "拍摄已完成"
|
|
}
|
|
if phase == .unknown { return "状态待确认" }
|
|
if let title = usable(response?.ui?.title) { return title }
|
|
switch phase {
|
|
case .navigating: return "无人机正在前往拍摄点"
|
|
case .ready: return "无人机已到达"
|
|
case .shooting: return "正在拍摄"
|
|
case .paused: return "拍摄已暂停"
|
|
case .returning: return "无人机正在返航"
|
|
case .failed: return "任务执行失败"
|
|
case .blocked: return "当前任务暂不可执行"
|
|
default: return "状态待确认"
|
|
}
|
|
}
|
|
|
|
private func usable(_ value: String?) -> String? { DroneDockHomeMetric.usableText(value) }
|
|
|
|
/// 明确失败后优先展示任务结果原因,再保留执行门禁的实际限制,不用通用阶段标题充当原因。
|
|
private var failureMessage: String {
|
|
usable(response?.orderFlightTask?.resultMessage) ?? usable(response?.task?.resultMessage)
|
|
?? usable(response?.executeGate?.message) ?? usable(response?.ui?.message) ?? "暂未返回具体失败原因"
|
|
}
|
|
|
|
/// 明确离线或返航时保持禁用,不从普通空闲文案推导后端重试许可。
|
|
private var isResummonDeviceUnavailable: Bool {
|
|
let plane = response?.currentPlane
|
|
return response?.planeStatus?.connected == false || plane?.onlineStatus == 2 || plane?.workStatus == 0
|
|
|| ["离线", "返航中", "正在返航"].contains(usable(plane?.workStatusLabel) ?? "")
|
|
|| response?.ui?.phase == "returning"
|
|
}
|
|
|
|
/// 正式入口未注入操作服务时说明当前限制;模拟页保留实际设备不可用原因。
|
|
private var retryUnavailableNote: String {
|
|
let plane = response?.currentPlane
|
|
if plane?.onlineStatus == 2 || plane?.workStatus == 0 || usable(plane?.workStatusLabel) == "离线" {
|
|
return "无人机离线,暂不可召唤"
|
|
}
|
|
if let status = usable(plane?.workStatusLabel), ["返航中", "正在返航"].contains(status) {
|
|
return "无人机返航中,暂不可召唤"
|
|
}
|
|
return "暂不可重新召唤,请返回准备页确认设备状态"
|
|
}
|
|
}
|
|
|
|
/// 任务页六项读数的后端展示文本,保持服务端单位与零值。
|
|
struct DroneDockShootingTelemetry: Equatable, Sendable {
|
|
/// 电量读数。
|
|
let batteryText: String
|
|
/// 环境温度读数。
|
|
let temperatureText: String
|
|
/// 风速读数。
|
|
let windText: String
|
|
/// 雨量读数。
|
|
let rainText: String
|
|
/// 信号状态。
|
|
let signalText: String
|
|
/// 搜星状态。
|
|
let satelliteText: String
|
|
}
|