import Foundation /// 拍摄准备状态:明确点击创建待飞任务,再用同一任务 ID 召唤,保留回执并防止重复提交。 final class DroneDockPreparationViewModel { /// 页面进入时固定的账号、景区及门店范围。 let context: DroneDockHomeContext /// 首页订单仅提供身份和初次加载时的摘要。 let order: DroneDockHomeOrder /// 张工返回的订单购买范围及最新次数。 private(set) var projectInfo: DroneDockProjectInfoResponse? /// 购买配置是否尚未读取完成。 private(set) var isLoading = false /// 购买配置或请求身份错误。 private(set) var errorMessage: String? /// 已购且可用的当前点位。 private(set) var selectedSpotID: Int? /// 当前点位下已购且可用的航线。 private(set) var selectedRouteID: Int? /// 朱工返回的当前景区无人机快照,与购买配置独立刷新。 private(set) var planeStatus: DroneDockPlaneStatusResponse? /// 无人机状态读取失败时不沿用旧的空闲或电量信息。 private(set) var planeStatusErrorMessage: String? /// 同一页面只保留一个无人机状态请求,避免轮询与手动刷新重叠。 private(set) var isLoadingPlaneStatus = false /// 创建期间冻结选择和重复点击,不发送飞行指令。 private(set) var isCreatingTask = false /// 创建成功的任务回执,后续召唤应复用此任务 ID。 private(set) var createdTask: DroneDockCreatedTask? /// 创建预检或业务拒绝的具体提示。 private(set) var taskCreationErrorMessage: String? /// POST 结果不明确时禁止盲目重试,需核对服务端任务后再继续。 private(set) var taskCreationOutcomeUnknown = false /// 召唤提交期间禁用重复点击;请求成功不等于已经到达或开始拍摄。 private(set) var isSummoning = false /// 朱工接受召唤请求的回执,data 缺失时仍以明确业务成功为准。 private(set) var shootResponse: DroneDockShootResponse? /// 召唤业务拒绝或结果未知的提示,始终保留已创建任务身份。 private(set) var shootErrorMessage: String? /// 召唤写请求结果不明确时禁止重发,等待后续核对任务状态。 private(set) var summonOutcomeUnknown = false /// 后端明确说明原任务已结束时,转为查看原任务,禁止继续重复首次召唤。 private(set) var summonRequiresTaskReview = false /// 创建失败的用户提示;成功回执仅供业务与日志使用,不在页面输出。 var creationFailure: DroneDockPreparationFailure? { guard createdTask == nil, let message = taskCreationErrorMessage else { return nil } return DroneDockPreparationFailure(message: message, stage: .creation, outcomeUnknown: taskCreationOutcomeUnknown) } /// 召唤失败与创建失败分开表达,保留已经创建的任务。 var summonFailure: DroneDockPreparationFailure? { guard let message = shootErrorMessage else { return nil } return DroneDockPreparationFailure(message: message, stage: .summon, outcomeUnknown: summonOutcomeUnknown, code: shootErrorCode) } private let service: any DroneDockPreparationServing private let planeStatusService: any DroneDockPlaneStatusServing private let taskCreationService: any DroneDockTaskCreating private let shootService: any DroneDockShootServing private let allowsTaskSubmission: Bool private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext private var generation = 0 private var planeStatusGeneration = 0 private var taskCreationGeneration = 0 private var didSendTaskCreation = false private var hasCreatedTask = false private var creationContextInvalidated = false private var summonGeneration = 0 private var didSendSummon = false private var shootErrorCode: Int? private var hasSubmittedSummon = false private var primaryActionGeneration = 0 private var isPerformingPrimaryAction = false /// 注入购买、设备、任务创建与召唤服务及最新会话,不绑定默认 MainActor。 init(context: DroneDockHomeContext, order: DroneDockHomeOrder, service: any DroneDockPreparationServing, planeStatusService: any DroneDockPlaneStatusServing, taskCreationService: any DroneDockTaskCreating, shootService: any DroneDockShootServing, allowsTaskSubmission: Bool = true, currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) { self.context = context self.order = order self.service = service self.planeStatusService = planeStatusService self.taskCreationService = taskCreationService self.shootService = shootService self.allowsTaskSubmission = allowsTaskSubmission self.currentContext = currentContext } /// 当前阶段只创建待飞任务,不以设备电量或位置作为创建任务条件。 var canCreateTask: Bool { guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask, !hasCreatedTask, !taskCreationOutcomeUnknown, errorMessage == nil, let info = projectInfo, info.order.canCreateTask == true, let total = info.order.shotTotal, total > 0, let remaining = info.order.shotRemain, remaining > 0, selectedSpot?.available == true, selectedRoute?.available == true, let number = DroneDockHomeMetric.usableText(order.orderNumber), number.count <= 128, number.rangeOfCharacter(from: .controlCharacters) == nil, number == order.orderNumber, let projectID = order.projectID, projectID > 0 else { return false } return info.order.orderNumber == number && info.order.projectID == projectID } /// 当前入口是否被禁飞限制禁止提交,用于提供独立模拟入口而不放开真实写入。 var isTaskSubmissionBlocked: Bool { !allowsTaskSubmission } /// 提交中和已有回执/不确定结果时冻结点位航线,避免显示与任务归属不一致。 var isTaskSelectionLocked: Bool { isCreatingTask || isSummoning || isPerformingPrimaryAction || hasCreatedTask || taskCreationOutcomeUnknown } /// 为诊断保留实际 data JSON,正式准备页不展示此内容。 var creationDataJSON: String? { createdTask?.dataJSON } /// 仅保留 shoot 实际返回的 data;缺失时不拼造成功 JSON。 var shootDataJSON: String? { shootResponse?.dataJSON } /// 创建回执携带的最新订单摘要优先于创建前购买摘要。 var latestOrderSummary: DroneDockHomeOrder? { createdTask?.order ?? projectInfo?.order } /// 已受理或后端明确要求核对已结束的任务时允许查看,导航不重复提交召唤。 var canOpenShootingTask: Bool { context.canLoad && !creationContextInvalidated && !isLoading && !isCreatingTask && !isSummoning && !isPerformingPrimaryAction && !taskCreationOutcomeUnknown && !summonOutcomeUnknown && ((hasSubmittedSummon && shootResponse != nil) || summonRequiresTaskReview) && (createdTask?.taskID ?? 0) > 0 } /// 首次允许创建再召唤;明确业务拒绝后可对同任务重试,成功和未知结果锁定。 var isPrimaryActionEnabled: Bool { guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask, !isSummoning, !isPerformingPrimaryAction, !taskCreationOutcomeUnknown, !hasSubmittedSummon, !summonOutcomeUnknown, !summonRequiresTaskReview else { return false } if let createdTask { return createdTask.taskID > 0 } return canCreateTask } /// 主按钮串接创建与召唤;已有任务跳过创建,成功后的导航由页面处理。 @MainActor func prepareAndSummon(onStateChange: @escaping @MainActor () -> Void = {}) async { // 禁飞调试在整条链开始前阻断,避免先残留真实待飞任务再拦截召唤。 guard allowsTaskSubmission, isPrimaryActionEnabled else { return } primaryActionGeneration &+= 1 let actionGeneration = primaryActionGeneration isPerformingPrimaryAction = true onStateChange() defer { if primaryActionGeneration == actionGeneration { isPerformingPrimaryAction = false onStateChange() } } if createdTask == nil { await createTask(onStateChange: onStateChange) } guard primaryActionGeneration == actionGeneration, !Task.isCancelled else { return } await summonCreatedTask(onStateChange: onStateChange) } /// 对明确创建成功的任务发送一次召唤;只有明确业务拒绝允许之后再次提交。 @MainActor private func summonCreatedTask(onStateChange: @escaping @MainActor () -> Void) async { guard allowsTaskSubmission, !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown, !hasSubmittedSummon, !summonOutcomeUnknown, let taskID = createdTask?.taskID, taskID > 0 else { return } summonGeneration &+= 1 let requestGeneration = summonGeneration isSummoning = true didSendSummon = false shootErrorMessage = nil shootErrorCode = nil onStateChange() defer { if summonGeneration == requestGeneration { if Task.isCancelled && didSendSummon && !hasSubmittedSummon { markSummonUnknown() } isSummoning = false didSendSummon = false onStateChange() } } guard acceptsSummon(requestGeneration, taskID: taskID) else { return } do { didSendSummon = true let response = try await shootService.shoot(taskID: taskID) guard acceptsSummon(requestGeneration, taskID: taskID) else { return } shootResponse = response DroneDockDiagnostics.event("summon.receipt_accepted", taskID: taskID) hasSubmittedSummon = true summonOutcomeUnknown = false } catch { if error is DeviceCommandDebugBlockedError, summonGeneration == requestGeneration { didSendSummon = false } guard acceptsSummon(requestGeneration, taskID: taskID) else { return } if error is DeviceCommandDebugBlockedError { shootErrorMessage = DeviceCommandDebugPolicy.blockedMessage } else if case let APIError.serverCode(code, message) = error { shootErrorCode = code shootErrorMessage = message summonRequiresTaskReview = DroneDockPreparationFailure.requiresTaskReview(message) } else { markSummonUnknown(reason: error.localizedDescription) } } } /// 页面暂停使迟到召唤回执失效;已发送请求保留未知锁,成功回执和任务 ID 不清除。 @MainActor func invalidateSummon() { if isSummoning && didSendSummon && !hasSubmittedSummon { markSummonUnknown() } primaryActionGeneration &+= 1 isPerformingPrimaryAction = false summonGeneration &+= 1 isSummoning = false didSendSummon = false if creationContextInvalidated { shootResponse = nil shootErrorMessage = nil shootErrorCode = nil summonRequiresTaskReview = false } } /// 点击后先校验最新购买配置,再发送一次创建请求;成功留在准备页供核对。 @MainActor func createTask(onStateChange: @escaping @MainActor () -> Void = {}) async { guard allowsTaskSubmission, canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID, let number = order.orderNumber, let projectID = order.projectID else { return } taskCreationGeneration &+= 1 let requestGeneration = taskCreationGeneration isCreatingTask = true didSendTaskCreation = false taskCreationErrorMessage = nil onStateChange() defer { if taskCreationGeneration == requestGeneration { if Task.isCancelled && didSendTaskCreation && !hasCreatedTask { markTaskCreationUnknown() } isCreatingTask = false didSendTaskCreation = false onStateChange() } } guard acceptsTaskCreation(requestGeneration) else { return } do { let latest = try await service.projectInfo(scenicID: context.scenicID, projectID: projectID, orderNumber: number) guard acceptsTaskCreation(requestGeneration) else { return } guard latest.order.orderNumber == number, latest.order.projectID == projectID else { throw APIError.decodeFailed("购买配置与当前订单或项目不一致,请刷新重试") } projectInfo = latest guard latest.order.canCreateTask == true, let total = latest.order.shotTotal, total > 0, let remaining = latest.order.shotRemain, remaining > 0 else { taskCreationErrorMessage = "当前订单已不可新增拍摄任务,请刷新状态" return } guard let spot = latest.spots.first(where: { $0.id == spotID }), spot.available == true, spot.airLines.contains(where: { $0.id == routeID && $0.available == true }) else { restoreValidSelection() taskCreationErrorMessage = "所选点位或航线已不可用,请重新选择" return } guard acceptsTaskCreation(requestGeneration) else { return } didSendTaskCreation = true let response = try await taskCreationService.createTask(scenicID: context.scenicID, orderNumber: number, spotID: spotID, airLineID: routeID) guard acceptsTaskCreation(requestGeneration) else { return } guard response.taskID > 0, response.order.orderNumber == number, response.order.projectID == nil || response.order.projectID == projectID else { throw APIError.decodeFailed("创建回执与当前订单或项目不一致,请核对任务") } createdTask = response DroneDockDiagnostics.event("create.receipt_accepted", taskID: response.taskID) hasCreatedTask = true taskCreationOutcomeUnknown = false } catch { if error is DeviceCommandDebugBlockedError, taskCreationGeneration == requestGeneration { didSendTaskCreation = false } guard acceptsTaskCreation(requestGeneration) else { return } if error is DeviceCommandDebugBlockedError { taskCreationErrorMessage = DeviceCommandDebugPolicy.blockedMessage } else if didSendTaskCreation { if case APIError.serverCode = error { taskCreationErrorMessage = error.localizedDescription } else { markTaskCreationUnknown(reason: error.localizedDescription) } } else { taskCreationErrorMessage = Self.message(for: error) } } } /// 读取当前景区的无人机状态,不重读购买配置、不改变点位或航线选择。 @MainActor func refreshPlaneStatus() async { guard !isLoadingPlaneStatus else { return } planeStatusGeneration &+= 1 let requestGeneration = planeStatusGeneration isLoadingPlaneStatus = true planeStatusErrorMessage = nil defer { if planeStatusGeneration == requestGeneration { isLoadingPlaneStatus = false if Task.isCancelled { planeStatus = nil } } } guard acceptsPlaneStatus(requestGeneration) else { return } guard context.canLoad else { planeStatus = nil planeStatusErrorMessage = "缺少当前景区或登录信息,请返回工作台重新进入" return } do { let response = try await planeStatusService.planeStatus(scenicID: context.scenicID) guard acceptsPlaneStatus(requestGeneration) else { return } guard response.scenicID == context.scenicID else { planeStatus = nil planeStatusErrorMessage = "无人机状态与当前景区不一致,请刷新重试" return } planeStatus = response } catch { guard acceptsPlaneStatus(requestGeneration) else { return } planeStatus = nil planeStatusErrorMessage = Self.message(for: error) } } /// 采用服务端轮询建议;缺失使用五秒,限制到五至六十秒避免密集请求。 var pollIntervalNanoseconds: UInt64 { UInt64(min(60_000, max(5_000, planeStatus?.pollHintMS ?? 5_000))) * 1_000_000 } /// 暂停或离开时只使无人机请求失效,购买配置与选中航线继续保留。 @MainActor func invalidatePlaneStatus() { planeStatusGeneration &+= 1 isLoadingPlaneStatus = false planeStatus = nil planeStatusErrorMessage = nil } /// 只展示购买快照中的点位,保持张工返回顺序。 var spots: [DroneDockPurchasedSpot] { projectInfo?.spots ?? [] } /// 当前有效点位。 var selectedSpot: DroneDockPurchasedSpot? { spots.first { $0.id == selectedSpotID } } /// 只展示当前已购点位中的航线。 var routes: [DroneDockPurchasedAirLine] { selectedSpot?.airLines ?? [] } /// 当前有效航线。 var selectedRoute: DroneDockPurchasedAirLine? { routes.first { $0.id == selectedRouteID } } /// 进入页面后直接请求购买快照,不等待定位或设备接口。 func refresh() async { guard !isCreatingTask else { return } generation &+= 1 let requestGeneration = generation isLoading = true errorMessage = nil defer { if generation == requestGeneration { isLoading = false } } guard await accepts(requestGeneration) else { return } guard context.canLoad, let number = DroneDockHomeMetric.usableText(order.orderNumber), let projectID = order.projectID, projectID > 0 else { clearProject() errorMessage = "缺少当前景区、订单或套餐信息,请返回工作台重新进入" return } let projectResult: Result do { projectResult = .success(try await service.projectInfo(scenicID: context.scenicID, projectID: projectID, orderNumber: number)) } catch { projectResult = .failure(error) } guard await accepts(requestGeneration) else { return } switch projectResult { case .success(let value) where value.order.orderNumber == number && value.order.projectID == projectID: projectInfo = value restoreValidSelection() case .success: clearProject() errorMessage = "接口返回的订单或套餐与当前订单不一致,请刷新重试" case .failure(let error): clearProject() errorMessage = Self.message(for: error) } } /// 不可用或可用性未知的点位不能选中,切点后选择首条明确可用的已购航线。 func selectSpot(id: Int) { guard !isLoading, !isTaskSelectionLocked, spots.contains(where: { $0.id == id && $0.available == true }), selectedSpotID != id else { return } selectedSpotID = id selectedRouteID = routes.first(where: { $0.available == true })?.id } /// 忽略其他点位、不可用及身份不明的航线选择。 func selectRoute(id: Int) { guard !isLoading, !isTaskSelectionLocked, selectedSpot?.available == true, routes.contains(where: { $0.id == id && $0.available == true }) else { return } selectedRouteID = id } /// 离开后使请求失效,保留创建回执或不确定结果,避免返回后重复建任务。 @MainActor func invalidate() { if isCreatingTask && didSendTaskCreation { markTaskCreationUnknown() } taskCreationGeneration &+= 1 isCreatingTask = false didSendTaskCreation = false generation &+= 1 isLoading = false errorMessage = nil clearProject() invalidatePlaneStatus() invalidateSummon() } /// 连接状态仅使用 plane-status 的 connected,不由是否空闲推导。 var connectionTitle: String { switch planeStatus?.connected { case true: "机巢已连接" case false: "机巢未连接" default: "机巢连接待确认" } } /// 明确连接时标绿,离线或未知保持中性色。 var connectionTone: DroneDockStatusTone { planeStatus?.connected == true ? .green : .gray } /// 以购买快照中的名称展示当前选择。 var selectionSummary: String { guard let selectedSpot else { return "请选择拍摄点" } guard let selectedRoute else { return "\(selectedSpot.name) · 未选航线" } return "\(selectedSpot.name) · \(selectedRoute.name)" } /// 展示后端推荐设备,状态文案缺少电量时补充电量字段,不重选设备或把未知电量当零。 var deviceStatusText: String { guard let planeStatus else { return "状态待确认" } guard let recommendation = planeStatus.recommend else { return planeStatus.planes.isEmpty ? "暂无无人机" : "状态待确认" } let state = DroneDockHomeMetric.usableText(recommendation.statusText) ?? DroneDockHomeMetric.usableText(recommendation.workStatusLabel) ?? "状态待确认" let percent = recommendation.batteryPercent.flatMap { (0...100).contains($0) ? $0 : nil } let battery = DroneDockHomeMetric.usableText(recommendation.batteryLabel) ?? percent.map { "电量 \($0)%" } if state.contains("%") || state.contains("%") || battery.map({ state.contains($0) }) == true { return state } return battery.map { "\(state) · \($0)" } ?? state } /// 状态颜色只映射文档定义的工作状态,未知值不展示为空闲。 var deviceTone: DroneDockStatusTone { switch planeStatus?.recommend?.workStatus { case 1: .green case 2: .orange default: .gray } } /// 文案区分创建、召唤提交与待核对,不将请求被接受表述为到达或拍摄成功。 var primaryButtonTitle: String { if isCreatingTask { return "正在创建任务…" } if isSummoning { return "正在召唤无人机…" } if hasSubmittedSummon || summonRequiresTaskReview { return "查看拍摄任务" } if !allowsTaskSubmission { return "仅限模拟调试" } if summonOutcomeUnknown { return "召唤结果待核对" } if hasCreatedTask { return shootErrorMessage == nil ? "确认并召唤" : "重试召唤" } if taskCreationOutcomeUnknown { return "结果待核对" } if projectInfo?.order.shotRemain == 0 { return "拍摄次数已用完" } if let info = projectInfo, info.order.canCreateTask != true { return "暂不可召唤" } return "确认并召唤" } /// 说明创建与召唤提交结果,实际飞行状态需要后续任务状态核对。 var admissionMessage: String { if isCreatingTask { return "正在创建待飞任务,请勿重复点击" } if isSummoning { return "任务已创建,正在提交召唤请求" } if creationContextInvalidated, let errorMessage { return errorMessage } if !allowsTaskSubmission && !hasSubmittedSummon { return DeviceCommandDebugPolicy.blockedMessage } if createdTask != nil { if hasSubmittedSummon { return "召唤请求已提交,请等待任务状态更新" } if let summonFailure { return summonFailure.message } if summonOutcomeUnknown { return "召唤结果待核对,请勿重复提交" } return "任务已创建,等待召唤" } if let creationFailure { return creationFailure.message } if taskCreationOutcomeUnknown { return "创建结果待核对,请勿重复提交" } if isLoading { return "正在获取拍摄准备信息" } if let errorMessage { return errorMessage } guard let info = projectInfo else { return "正在加载拍摄准备信息" } if info.order.shotRemain == 0 { return "当前订单拍摄次数已用完" } guard let remaining = info.order.shotRemain, remaining > 0, let total = info.order.shotTotal, total > 0 else { return "拍摄次数待确认,请刷新状态" } guard info.order.canCreateTask == true else { return "当前订单暂不可新增拍摄任务,请刷新状态" } if spots.isEmpty { return "当前暂无可用拍摄点" } guard let spot = selectedSpot, spot.available == true else { return "请选择可用拍摄点" } if routes.isEmpty { return "当前拍摄点暂无可用航线" } guard selectedRoute?.available == true else { return "请选择可用航线" } return "点击后创建任务并召唤无人机" } private func restoreValidSelection() { guard !hasCreatedTask, !taskCreationOutcomeUnknown else { return } if !spots.contains(where: { $0.id == selectedSpotID && $0.available == true }) { selectedSpotID = spots.first(where: { $0.available == true })?.id selectedRouteID = nil } if !routes.contains(where: { $0.id == selectedRouteID && $0.available == true }) { selectedRouteID = routes.first(where: { $0.available == true })?.id } } private func clearProject() { projectInfo = nil // 已提交的任务仍归属原点位航线,暂时清空购买快照不能替它重新选项。 guard creationContextInvalidated || !isTaskSelectionLocked else { return } selectedSpotID = nil selectedRouteID = nil } private func accepts(_ requestGeneration: Int) async -> Bool { guard generation == requestGeneration, !Task.isCancelled else { return false } let latest = await currentContext() guard generation == requestGeneration, !Task.isCancelled else { return false } guard context.hasSameIdentity(as: latest) else { creationContextInvalidated = true createdTask = nil await invalidate() errorMessage = "账号或景区已变化,请返回工作台重新进入" return false } return true } /// 无人机回包独立验证请求代次、取消状态与当前登录身份。 @MainActor private func acceptsPlaneStatus(_ requestGeneration: Int) -> Bool { guard planeStatusGeneration == requestGeneration, !Task.isCancelled else { return false } guard context.hasSameIdentity(as: currentContext()) else { creationContextInvalidated = true createdTask = nil invalidate() let message = "账号或景区已变化,请返回工作台重新进入" errorMessage = message planeStatusErrorMessage = message return false } return true } /// 写请求代次和身份检查;取消或切换会话后不显示迟到的成功回执。 @MainActor private func acceptsTaskCreation(_ requestGeneration: Int) -> Bool { guard taskCreationGeneration == requestGeneration else { return false } guard !Task.isCancelled else { if didSendTaskCreation { markTaskCreationUnknown() } return false } guard context.hasSameIdentity(as: currentContext()), !creationContextInvalidated else { creationContextInvalidated = true createdTask = nil invalidate() errorMessage = "账号或景区已变化,请返回工作台重新进入" return false } return true } /// 召唤只接受同一任务、同一会话及当前请求代次;提交后取消保留未知锁。 @MainActor private func acceptsSummon(_ requestGeneration: Int, taskID: Int) -> Bool { guard summonGeneration == requestGeneration else { return false } guard !Task.isCancelled else { if didSendSummon && !hasSubmittedSummon { markSummonUnknown() } return false } guard createdTask?.taskID == taskID, !taskCreationOutcomeUnknown else { return false } guard context.hasSameIdentity(as: currentContext()), !creationContextInvalidated else { creationContextInvalidated = true createdTask = nil invalidate() errorMessage = "账号或景区已变化,请返回工作台重新进入" return false } return true } private func markSummonUnknown(reason: String? = nil) { DroneDockDiagnostics.event("summon.outcome_unknown", taskID: createdTask?.taskID) summonOutcomeUnknown = true shootErrorCode = nil shootErrorMessage = (reason.map { "\($0)。" } ?? "") + "召唤结果待核对,请先核对任务状态,勿重复提交" } private func markTaskCreationUnknown(reason: String? = nil) { DroneDockDiagnostics.event("taskcreation.outcome_unknown", taskID: createdTask?.taskID) taskCreationOutcomeUnknown = true taskCreationErrorMessage = (reason.map { "\($0)。" } ?? "") + "创建结果待核对,请先查看订单任务,勿重复提交" } private static func message(for error: Error) -> String? { error is CancellationError ? nil : error.localizedDescription } }