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