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

接入 plane-status、tasks/create、shoot 与 shooting,保持同一任务 ID 串接、重复提交保护和只读单次刷新。拍摄任务页固定顶部参数与底部安全控制,中间状态区域适配小屏且不滚动;同步接口记录、脱敏响应及相关测试。
This commit is contained in:
2026-10-29 17:06:49 +08:00
parent 4d763ef5d1
commit 1173207756
47 changed files with 6723 additions and 81 deletions
@@ -0,0 +1,32 @@
import Foundation
/// 准备页的独立无人机状态只读服务,不读取定位或创建飞行任务。
protocol DroneDockPlaneStatusServing: Sendable {
/// 读取当前景区可展示的设备状态与实时电量。
@MainActor
func planeStatus(scenicID: Int) async throws -> DroneDockPlaneStatusResponse
}
/// 朱工 plane-status 接口适配,复用统一 Token 与业务错误处理。
@MainActor
final class DroneDockPlaneStatusAPI: DroneDockPlaneStatusServing {
private let client: APIClient
/// 注入统一客户端,便于替换网络测试依赖。
init(client: APIClient) { self.client = client }
/// 明确请求实时电量,返回景区不一致时拒绝将状态回填当前页面。
func planeStatus(scenicID: Int) async throws -> DroneDockPlaneStatusResponse {
guard scenicID > 0 else { throw APIError.networkFailed("请先选择景区") }
let response: DroneDockPlaneStatusResponse = try await client.send(APIRequest(
method: .get,
path: "/api/app/airport/plane-status",
queryItems: [URLQueryItem(name: "scenic_id", value: String(scenicID)),
URLQueryItem(name: "live_battery", value: "1")]
))
guard response.scenicID == scenicID else {
throw APIError.decodeFailed("无人机状态与当前景区不一致,请刷新重试")
}
return response
}
}
@@ -0,0 +1,44 @@
import Foundation
/// 对已创建的订单飞行任务请求召唤,复用该任务及服务端锁定的飞机。
protocol DroneDockShootServing: Sendable {
/// 只提交已有任务 ID;调用方负责防止重复提交及核对不确定结果。
@MainActor
func shoot(taskID: Int) async throws -> DroneDockShootResponse
}
/// 朱工 shoot 接口适配,业务成功仅表示接口受理结果,不推断飞机已经到达。
@MainActor
final class DroneDockShootAPI: DroneDockShootServing {
private let client: APIClient
/// 注入统一网络客户端,沿用登录凭证、HTTP 与业务码处理。
init(client: APIClient) { self.client = client }
/// 仅发送一次召唤 POST;不创建任务、不重试、不修改任务已选航线。
func shoot(taskID: Int) async throws -> DroneDockShootResponse {
try Task.checkCancellation()
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请先创建任务") }
do {
return try await client.send(APIRequest(
method: .post,
path: "/api/app/airport/shoot",
body: ShootBody(taskID: taskID)
))
} catch APIError.emptyData {
// 统一客户端仅在 HTTP 和业务码均成功后抛 emptyData;此接口尚未约定成功 data 结构。
return DroneDockShootResponse(dataJSON: nil)
}
}
/// 本轮联调仅发送任务身份和非重启标记,完全省略 plane_id 与航线覆盖字段。
private struct ShootBody: Encodable {
let taskID: Int
let restart = false
/// 朱工已建任务召唤参数映射。
private enum CodingKeys: String, CodingKey {
case taskID = "id", restart
}
}
}
@@ -0,0 +1,29 @@
import Foundation
/// 朱工拍摄任务信息只读服务,读取张工已创建的任务,不发送飞行控制。
protocol DroneDockShootingServing: Sendable {
/// 按已有任务 ID 获取拍摄页信息;读取失败后可对同一 ID 再次读取。
@MainActor
func shooting(taskID: Int, liveBattery: Bool) async throws -> DroneDockShootingResponse
}
/// shooting GET 接口适配,鉴权及业务码由统一客户端处理。
@MainActor
final class DroneDockShootingAPI: DroneDockShootingServing {
private let client: APIClient
/// 注入共享网络客户端,便于验证请求只包含已创建任务的查询参数。
init(client: APIClient) { self.client = client }
/// 仅发送一次无请求体的 GET,不创建任务、不召唤、不调用 start-shoot。
func shooting(taskID: Int, liveBattery: Bool = true) async throws -> DroneDockShootingResponse {
try Task.checkCancellation()
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请先创建任务") }
return try await client.send(APIRequest(
method: .get,
path: "/api/app/airport/shooting",
queryItems: [URLQueryItem(name: "id", value: String(taskID)),
URLQueryItem(name: "live_battery", value: liveBattery ? "1" : "0")]
))
}
}
@@ -0,0 +1,50 @@
import Foundation
/// 创建张工订单待飞任务,不派机、不调用朱工召唤或开始拍摄接口。
protocol DroneDockTaskCreating: Sendable {
/// 提交当前订单购买范围内的点位与航线,返回任务身份及订单摘要。
@MainActor
func createTask(scenicID: Int, orderNumber: String, spotID: Int, airLineID: Int) async throws -> DroneDockCreatedTask
}
/// 张工 tasks/create 接口,登录凭证和业务码由统一客户端处理。
@MainActor
final class DroneDockTaskCreationAPI: DroneDockTaskCreating {
private let client: APIClient
/// 注入共享网络客户端,测试可替换传输层。
init(client: APIClient) { self.client = client }
/// 单次调用仅发一次创建请求;响应身份异常交由页面核对,不自动重试写入。
func createTask(scenicID: Int, orderNumber: String, spotID: Int, airLineID: Int) async throws -> DroneDockCreatedTask {
try Task.checkCancellation()
guard scenicID > 0, spotID > 0, airLineID > 0, !orderNumber.isEmpty,
orderNumber.count <= 128,
orderNumber == orderNumber.trimmingCharacters(in: .whitespacesAndNewlines),
orderNumber.rangeOfCharacter(from: .controlCharacters) == nil else {
throw APIError.networkFailed("缺少有效景区、订单、拍摄点或航线,请刷新准备信息")
}
let response: DroneDockCreatedTask = try await client.send(APIRequest(
method: .post, path: "/api/yf-handset-app/photog/multi-plane/tasks/create",
body: CreateTaskBody(scenicID: scenicID, orderNumber: orderNumber, spotID: spotID, airLineID: airLineID)
))
guard response.order.orderNumber == orderNumber else {
throw APIError.decodeFailed("创建任务返回的订单与当前订单不一致,请先核对任务结果")
}
return response
}
/// 创建仅提交四项身份,不发送选机、位置或任何起飞参数。
private struct CreateTaskBody: Encodable {
let scenicID: Int
let orderNumber: String
let spotID: Int
let airLineID: Int
/// 张工创建待飞任务参数名。
private enum CodingKeys: String, CodingKey {
case scenicID = "scenic_id", orderNumber = "order_number"
case spotID = "scenic_spot_id", airLineID = "air_line_id"
}
}
}
@@ -0,0 +1,104 @@
import Foundation
/// 朱工提供的景区无人机状态快照,推荐设备由服务端选择。
struct DroneDockPlaneStatusResponse: Decodable, Equatable, Sendable {
/// 本次状态所属景区,必须与请求一致。
let scenicID: Int
/// 当前景区的设备状态;空数组表示没有设备。
let planes: [DroneDockPlaneStatus]
/// 服务端推荐设备,缺失时不在客户端另选一台。
let recommend: DroneDockPlaneStatus?
/// 服务端是否存在空闲设备,未知时不当作 false。
let hasIdle: Bool?
/// 服务端是否存在拍摄中的设备。
let hasShooting: Bool?
/// 景区连接状态,缺失时仍为未知。
let connected: Bool?
/// 服务端建议的轮询间隔;实际定时由页面生命周期控制。
let pollHintMS: Int?
/// 保留 plane-status 原始字段映射,不复用首页的不同状态枚举。
private enum CodingKeys: String, CodingKey {
case scenicID = "scenic_id", planes, recommend
case hasIdle = "has_idle", hasShooting = "has_shooting", connected, pollHintMS = "poll_hint_ms"
}
/// 校验景区和设备身份,不把缺失或错误列表当作正常空态。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
scenicID = try container.decode(DroneDockPlaneStatusInteger.self, forKey: .scenicID).value
guard scenicID > 0 else {
throw DecodingError.dataCorruptedError(forKey: .scenicID, in: container, debugDescription: "景区 ID 必须为正整数")
}
planes = try container.decode([DroneDockPlaneStatus].self, forKey: .planes)
guard Set(planes.map(\.id)).count == planes.count else {
throw DecodingError.dataCorruptedError(forKey: .planes, in: container, debugDescription: "无人机 ID 重复")
}
recommend = try container.decodeIfPresent(DroneDockPlaneStatus.self, forKey: .recommend)
hasIdle = try container.decodeIfPresent(Bool.self, forKey: .hasIdle)
hasShooting = try container.decodeIfPresent(Bool.self, forKey: .hasShooting)
connected = try container.decodeIfPresent(Bool.self, forKey: .connected)
pollHintMS = try container.decodeIfPresent(DroneDockPlaneStatusInteger.self, forKey: .pollHintMS)?.value
}
}
/// 单台无人机的工作状态和电量,仅供准备页展示,不代表召唤许可。
struct DroneDockPlaneStatus: Decodable, Equatable, Sendable {
/// 后端设备稳定身份。
let id: Int
/// 设备序列号,不作为飞行任务 ID 使用。
let snNumber: String?
/// 后端设备名称。
let name: String?
/// 0 离线、1 空闲、2 拍摄中;其他整数原样保留。
let workStatus: Int?
/// 后端工作状态名称。
let workStatusLabel: String?
/// 原始电量百分比,0 与缺失分开表示。
let batteryPercent: Int?
/// 后端格式化电量文案。
let batteryLabel: String?
/// 后端设备可飞标记,不据此启用当前订单的召唤按钮。
let canFly: Bool?
/// 准备页底栏优先展示的完整状态文案。
let statusText: String?
/// 后端字段映射。
private enum CodingKeys: String, CodingKey {
case id, snNumber = "sn_number", name, workStatus = "work_status", workStatusLabel = "work_status_label"
case batteryPercent = "battery_percent", batteryLabel = "battery_label", canFly = "can_fly", statusText = "status_text"
}
/// 状态允许未知,设备身份必须明确;不从电量或工作状态推导 can_fly。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(DroneDockPlaneStatusInteger.self, forKey: .id).value
guard id > 0 else {
throw DecodingError.dataCorruptedError(forKey: .id, in: container, debugDescription: "无人机 ID 必须为正整数")
}
snNumber = try container.decodeIfPresent(String.self, forKey: .snNumber)
name = try container.decodeIfPresent(String.self, forKey: .name)
workStatus = try container.decodeIfPresent(DroneDockPlaneStatusInteger.self, forKey: .workStatus)?.value
workStatusLabel = try container.decodeIfPresent(String.self, forKey: .workStatusLabel)
batteryPercent = try container.decodeIfPresent(DroneDockPlaneStatusInteger.self, forKey: .batteryPercent)?.value
batteryLabel = try container.decodeIfPresent(String.self, forKey: .batteryLabel)
canFly = try container.decodeIfPresent(Bool.self, forKey: .canFly)
statusText = try container.decodeIfPresent(String.self, forKey: .statusText)
}
}
/// 兼容整数与整数字符串,拒绝布尔值、浮点截断及非法数字。
private struct DroneDockPlaneStatusInteger: Decodable {
let value: Int
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let number = try? container.decode(Int.self) {
value = number
} else if let text = try? container.decode(String.self), let number = Int(text) {
value = number
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "需要整数或整数字符串")
}
}
}
@@ -0,0 +1,36 @@
import Foundation
/// shoot 业务成功后的原始 data 回执,不假设或构造飞机、任务及飞行阶段字段。
struct DroneDockShootResponse: Decodable, Equatable, Sendable {
/// 完整 data JSON;nil 表示统一客户端未提供 data,不补造 null 或空对象。
let dataJSON: String?
/// 保留已格式化回执;业务成功但 data 缺失或为 null 时使用 nil。
init(dataJSON: String?) { self.dataJSON = dataJSON }
/// 支持任意真实 JSON 值,保留未知结构、空数组、布尔值及原始字段类型。
init(from decoder: Decoder) throws {
let raw = try DroneDockHomeJSONValue(from: decoder)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
dataJSON = String(decoding: try encoder.encode(DroneDockShootJSONSnapshot(value: raw)), as: UTF8.self)
}
}
/// 将现有 JSON 值解码结果格式化,完整保留 shoot 尚未约定的成功数据结构。
private struct DroneDockShootJSONSnapshot: Encodable {
let value: DroneDockHomeJSONValue
/// 按真实 JSON 类型编码,不推导任务身份或追加外层业务字段。
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch value {
case .object(let object): try container.encode(object.mapValues { DroneDockShootJSONSnapshot(value: $0) })
case .array(let array): try container.encode(array.map { DroneDockShootJSONSnapshot(value: $0) })
case .string(let text): try container.encode(text)
case .number(let number): try container.encode(number)
case .bool(let flag): try container.encode(flag)
case .null: try container.encodeNil()
}
}
}
@@ -0,0 +1,202 @@
import Foundation
/// 朱工 shooting 的只读快照;完整 data 用于展示,不表示已召唤或已开始拍摄。
struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
/// 后端若明确提供订单号则保留,不由请求上下文伪造响应身份。
let orderNumber: String?
/// 实测返回的订单飞行任务身份;存在时必须与请求上下文核对。
let orderFlightTask: DroneDockShootingTaskIdentity?
/// 实测返回的任务摘要,不以其状态推导控制动作。
let task: DroneDockShootingTaskIdentity?
/// 拍摄任务关联的景区信息。
let scenic: DroneDockShootingPlace?
/// 拍摄任务关联的点位信息。
let scenicSpot: DroneDockShootingPlace?
/// 拍摄任务关联的航线信息。
let airLine: DroneDockShootingAirLine?
/// 服务端给出的页面标题、游客及套餐文案。
let header: DroneDockShootingHeader?
/// 服务端给出的当前设备,不由准备页推荐设备替代。
let currentPlane: DroneDockShootingPlane?
/// 六项读数使用后端格式化文案,保留未知值与真实零值。
let metrics: [DroneDockHomeMetric]
/// 景区设备连接与轮询建议,不在客户端改选推荐飞机。
let planeStatus: DroneDockShootingPlaneStatus?
/// 服务端执行门禁只用于展示,本次接入不执行其动作。
let executeGate: DroneDockShootingExecuteGate?
/// 服务端拍摄阶段和页面提示。
let ui: DroneDockShootingUI?
/// 完整 data 的格式化 JSON,保留未知字段、空值及原 JSON 类型。
let dataJSON: String
/// 只映射已知展示字段,不假设响应中的任务 ID 位置。
private enum CodingKeys: String, CodingKey {
case orderNumber = "order_number", orderFlightTask = "order_flight_task", task
case scenic, scenicSpot = "scenic_spot", airLine = "air_line"
case header, currentPlane = "current_plane", executeGate = "execute_gate", ui
case metrics, planeStatus = "plane_status"
}
/// 可选字段缺失或为 null 时保持未知;不把缺失执行门禁推断为允许。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderNumber = try container.decodeIfPresent(String.self, forKey: .orderNumber)
orderFlightTask = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .orderFlightTask)
task = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .task)
scenic = try container.decodeIfPresent(DroneDockShootingPlace.self, forKey: .scenic)
scenicSpot = try container.decodeIfPresent(DroneDockShootingPlace.self, forKey: .scenicSpot)
airLine = try container.decodeIfPresent(DroneDockShootingAirLine.self, forKey: .airLine)
header = try container.decodeIfPresent(DroneDockShootingHeader.self, forKey: .header)
currentPlane = try container.decodeIfPresent(DroneDockShootingPlane.self, forKey: .currentPlane)
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
planeStatus = try container.decodeIfPresent(DroneDockShootingPlaneStatus.self, forKey: .planeStatus)
executeGate = try container.decodeIfPresent(DroneDockShootingExecuteGate.self, forKey: .executeGate)
ui = try container.decodeIfPresent(DroneDockShootingUI.self, forKey: .ui)
let raw = try DroneDockHomeJSONValue(from: decoder)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
dataJSON = String(decoding: try encoder.encode(DroneDockShootingJSONSnapshot(value: raw)), as: UTF8.self)
}
}
/// shooting 实测返回的已有任务身份和状态摘要,各身份仅在实际提供时参与核对。
struct DroneDockShootingTaskIdentity: Decodable, Equatable, Sendable {
/// 订单飞行任务 ID。
let id: Int?
/// 任务所属订单号。
let orderNumber: String?
/// 任务所属景区。
let scenicID: Int?
/// 后端原始任务状态,不与订单状态混用。
let status: Int?
/// 服务端任务状态文案。
let statusLabel: String?
/// 实测航线任务状态,与订单飞行任务状态分别保留。
let waylineStatus: Int?
/// 服务端航线状态文案;执行失败优先于笼统的订单任务执行中。
let waylineStatusLabel: String?
/// 已确认嵌套任务字段映射。
private enum CodingKeys: String, CodingKey {
case id, orderNumber = "order_number", scenicID = "scenic_id", status, statusLabel = "status_label"
case waylineStatus = "wayline_status", waylineStatusLabel = "wayline_status_label"
}
}
/// shooting 的设备轮询提示与连接结果;缺失布尔保持未知。
struct DroneDockShootingPlaneStatus: Decodable, Equatable, Sendable {
/// 后端实际提供的设备列表所属景区。
let scenicID: Int?
/// 后端景区连接状态。
let connected: Bool?
/// 保留后端建议间隔;当前任务页不据此安排定时请求。
let pollHintMS: Int?
/// 设备快照字段映射,其余字段仍保留在完整 dataJSON 中。
private enum CodingKeys: String, CodingKey {
case scenicID = "scenic_id", connected, pollHintMS = "poll_hint_ms"
}
}
/// shooting 返回的景区或点位信息,缺失身份不由客户端补齐。
struct DroneDockShootingPlace: Decodable, Equatable, Sendable {
/// 服务端场景身份,未知时为 nil。
let id: Int?
/// 服务端显示名称。
let name: String?
}
/// shooting 返回的航线及其所属点位。
struct DroneDockShootingAirLine: Decodable, Equatable, Sendable {
/// 服务端航线身份。
let id: Int?
/// 服务端航线名称。
let name: String?
/// 航线所属点位,不用于推导当前任务 ID。
let scenicSpotID: Int?
/// 航线字段映射。
private enum CodingKeys: String, CodingKey { case id, name, scenicSpotID = "scenic_spot_id" }
}
/// shooting 拍摄页的服务端摘要文案。
struct DroneDockShootingHeader: Decodable, Equatable, Sendable {
/// 实测摘要返回的订单身份,不能忽略其与请求订单的一致性。
let orderNumber: String?
/// 页面主标题。
let title: String?
/// 服务端提供的游客显示文案。
let touristLabel: String?
/// 订单套餐显示文案。
let packageName: String?
/// 页面摘要字段映射。
private enum CodingKeys: String, CodingKey {
case orderNumber = "order_number", title, touristLabel = "tourist_label", packageName = "package_name"
}
}
/// shooting 当前设备的展示信息,不代表调用方已发送飞行指令。
struct DroneDockShootingPlane: Decodable, Equatable, Sendable {
/// 当前设备身份。
let id: Int?
/// 当前设备序列号。
let snNumber: String?
/// 服务端工作状态文案。
let workStatusLabel: String?
/// 服务端完整状态文案。
let statusText: String?
/// 当前设备字段映射。
private enum CodingKeys: String, CodingKey {
case id, snNumber = "sn_number", workStatusLabel = "work_status_label", statusText = "status_text"
}
}
/// shooting 执行门禁的原始结果;false 与未知分别保留。
struct DroneDockShootingExecuteGate: Decodable, Equatable, Sendable {
/// 服务端明确的执行许可,不从文案或 action 推导。
let canExecute: Bool?
/// 服务端门禁原因码。
let code: String?
/// 服务端门禁说明。
let message: String?
/// 服务端建议动作,本阶段仅展示。
let primaryAction: String?
/// 服务端建议动作名称。
let primaryActionLabel: String?
/// 门禁字段映射。
private enum CodingKeys: String, CodingKey {
case canExecute = "can_execute", code, message
case primaryAction = "primary_action", primaryActionLabel = "primary_action_label"
}
}
/// shooting 返回的拍摄阶段显示信息。
struct DroneDockShootingUI: Decodable, Equatable, Sendable {
/// 原始阶段标识,未知值原样保留。
let phase: String?
/// 服务端页面提示。
let title: String?
/// 服务端阶段说明,不由 GET 请求成功拼造飞行进度。
let message: String?
}
/// 将现有 JSON 值解码结果重新格式化,完整保留 shooting 的未建模字段。
private struct DroneDockShootingJSONSnapshot: Encodable {
let value: DroneDockHomeJSONValue
/// 保留字符串、数字、布尔、null 及嵌套结构,不添加外层业务包裹。
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch value {
case .object(let object): try container.encode(object.mapValues { DroneDockShootingJSONSnapshot(value: $0) })
case .array(let array): try container.encode(array.map { DroneDockShootingJSONSnapshot(value: $0) })
case .string(let text): try container.encode(text)
case .number(let number): try container.encode(number)
case .bool(let flag): try container.encode(flag)
case .null: try container.encodeNil()
}
}
}
@@ -0,0 +1,54 @@
import Foundation
/// 张工创建待飞任务的回执,保留最新订单摘要和完整 data 字段供联调展示。
struct DroneDockCreatedTask: Decodable, Equatable, Sendable {
/// 后端创建的订单飞行任务 ID,后续召唤应复用该任务。
let taskID: Int
/// 创建后的权威订单摘要,待飞任务不由客户端扣减次数。
let order: DroneDockHomeOrder
/// 格式化后的完整 data JSON;不添加或伪造外层 code、msg、time。
let dataJSON: String
/// 创建任务回执的必需身份字段。
private enum CodingKeys: String, CodingKey { case taskID = "task_id" }
/// 任务身份允许整数字符串,但必须为正整数;额外字段保留原 JSON 类型。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let value = try? container.decode(Int.self, forKey: .taskID) {
taskID = value
} else if let text = try? container.decode(String.self, forKey: .taskID), let value = Int(text) {
taskID = value
} else {
throw DecodingError.dataCorruptedError(forKey: .taskID, in: container, debugDescription: "创建任务未返回有效任务 ID")
}
guard taskID > 0 else {
throw DecodingError.dataCorruptedError(forKey: .taskID, in: container, debugDescription: "创建任务返回的任务 ID 必须为正整数")
}
order = try DroneDockHomeOrder(from: decoder)
let rawData = try DroneDockHomeJSONValue(from: decoder)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
dataJSON = String(decoding: try encoder.encode(DroneDockTaskJSONSnapshot(value: rawData)), as: UTF8.self)
}
}
/// 复用现有 JSON 值解码器,将回执 data 格式化,保留未建模字段和空值。
private struct DroneDockTaskJSONSnapshot: Encodable {
let value: DroneDockHomeJSONValue
/// JSON 类型保持不变,数字使用 Decimal 避免先转换为 Double 丢失精度。
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch value {
case .object(let object):
try container.encode(object.mapValues { DroneDockTaskJSONSnapshot(value: $0) })
case .array(let array):
try container.encode(array.map { DroneDockTaskJSONSnapshot(value: $0) })
case .string(let text): try container.encode(text)
case .number(let number): try container.encode(number)
case .bool(let flag): try container.encode(flag)
case .null: try container.encodeNil()
}
}
}
@@ -0,0 +1,59 @@
import Foundation
/// 真实任务页的显示阶段;未确认或冲突数据保持未知,不代表客户端已发送控制指令。
enum DroneDockTaskDisplayPhase: String, Equatable, Sendable {
/// 正在读取任务。
case loading
/// 服务端明确正在前往拍摄点。
case navigating
/// 服务端明确已到达且允许开始。
case ready
/// 服务端明确正在拍摄。
case shooting
/// 服务端明确已暂停。
case paused
/// 服务端明确正在返航。
case returning
/// 服务端明确任务已完成。
case completed
/// 已确认的任务或航线执行失败。
case failed
/// 服务端阻止执行或任务已取消。
case blocked
/// 尚无足够信息确定阶段。
case unknown
/// 当前读取失败,不能沿用旧阶段。
case readError
}
/// 任务状态区可呈现的动作;开始与恢复在本轮仅禁用展示,不发送飞控。
enum DroneDockTaskDisplayAction: Equatable, Sendable {
/// 重新读取同一任务。
case refresh
/// 开始拍摄占位动作,本轮禁用。
case start
/// 恢复拍摄占位动作,本轮禁用。
case resume
/// 查看已明确完成任务的订单素材。
case materials
/// 当前无主动作。
case none
}
/// 状态区的纯展示数据,供固定区域布局使用,不依赖 UIKit 或虚构进度。
struct DroneDockTaskPresentation: Equatable, Sendable {
/// 当前可信显示阶段。
let phase: DroneDockTaskDisplayPhase
/// 阶段标题。
let title: String
/// 服务端说明或读取错误,完整文字可由界面展开。
let message: String
/// 当前任务设备的状态文案。
let deviceStatus: String
/// 本轮允许展示的主动作。
let action: DroneDockTaskDisplayAction
/// 主动作名称,无动作时为 nil。
let actionTitle: String?
/// 是否可触发动作;未对接的开始和恢复始终为 false。
let isActionEnabled: Bool
}
@@ -1,6 +1,6 @@
import Foundation
/// 拍摄准备状态:只读取张工的已购配置,不创建飞行任务。
/// 拍摄准备状态:明确点击创建待飞任务,再用同一任务 ID 召唤,保留回执并防止重复提交。
final class DroneDockPreparationViewModel {
/// 页面进入时固定的账号、景区及门店范围。
let context: DroneDockHomeContext
@@ -16,21 +16,291 @@ final class DroneDockPreparationViewModel {
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 let service: any DroneDockPreparationServing
private let planeStatusService: any DroneDockPlaneStatusServing
private let taskCreationService: any DroneDockTaskCreating
private let shootService: any DroneDockShootServing
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 hasSubmittedSummon = false
private var primaryActionGeneration = 0
private var isPerformingPrimaryAction = false
/// 注入只读接口及最新会话,不绑定默认 MainActor。
/// 注入购买、设备、任务创建与召唤服务及最新会话,不绑定默认 MainActor。
init(context: DroneDockHomeContext, order: DroneDockHomeOrder,
service: any DroneDockPreparationServing,
planeStatusService: any DroneDockPlaneStatusServing,
taskCreationService: any DroneDockTaskCreating,
shootService: any DroneDockShootServing,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.order = order
self.service = service
self.planeStatusService = planeStatusService
self.taskCreationService = taskCreationService
self.shootService = shootService
self.currentContext = currentContext
}
/// 当前阶段只创建待飞任务,不以设备电量或位置作为创建任务条件。
var canCreateTask: Bool {
guard 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 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
&& (createdTask?.taskID ?? 0) > 0
}
/// 首次允许创建再召唤;明确业务拒绝后可对同任务重试,成功和未知结果锁定。
var isPrimaryActionEnabled: Bool {
guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
!isSummoning, !isPerformingPrimaryAction, !taskCreationOutcomeUnknown,
!hasSubmittedSummon, !summonOutcomeUnknown else { return false }
if let createdTask { return createdTask.taskID > 0 }
return canCreateTask
}
/// 主按钮串接创建与召唤;已有任务跳过创建,成功后的导航由页面处理。
@MainActor
func prepareAndSummon(onStateChange: @escaping @MainActor () -> Void = {}) async {
guard 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 !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown,
!hasSubmittedSummon, !summonOutcomeUnknown,
let taskID = createdTask?.taskID, taskID > 0 else { return }
summonGeneration &+= 1
let requestGeneration = summonGeneration
isSummoning = true
didSendSummon = false
shootErrorMessage = 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
hasSubmittedSummon = true
summonOutcomeUnknown = false
} catch {
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
if case APIError.serverCode = error {
shootErrorMessage = error.localizedDescription
} 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
}
}
/// 点击后先校验最新购买配置,再发送一次创建请求;成功留在准备页供核对。
@MainActor
func createTask(onStateChange: @escaping @MainActor () -> Void = {}) async {
guard 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
hasCreatedTask = true
taskCreationOutcomeUnknown = false
} catch {
guard acceptsTaskCreation(requestGeneration) else { return }
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 ?? [] }
/// 当前有效点位。
@@ -41,6 +311,7 @@ final class DroneDockPreparationViewModel {
var selectedRoute: DroneDockPurchasedAirLine? { routes.first { $0.id == selectedRouteID } }
/// 进入页面后直接请求购买快照,不等待定位或设备接口。
func refresh() async {
guard !isCreatingTask else { return }
generation &+= 1
let requestGeneration = generation
isLoading = true
@@ -76,62 +347,109 @@ final class DroneDockPreparationViewModel {
/// 不可用或可用性未知的点位不能选中,切点后选择首条明确可用的已购航线。
func selectSpot(id: Int) {
guard !isLoading, spots.contains(where: { $0.id == id && $0.available == true }), selectedSpotID != id else { return }
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, selectedSpot?.available == true,
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()
}
/// 当前接口没有机巢连接信息,不能由购买权限推导设备状态。
var connectionTitle: String { "机巢连接待确认" }
/// 设备连接未知时使用中性色。
var connectionTone: DroneDockStatusTone { .gray }
/// 连接状态仅使用 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 { "状态待确认" }
/// 准备阶段尚未派机。
var deviceTone: DroneDockStatusTone { .gray }
/// 文案反映购买权限,不开放实际召唤操作。
/// 优先展示服务端推荐无人机的完整文案,不自行重选列表中的另一架。
var deviceStatusText: String {
guard let planeStatus else { return "状态待确认" }
guard let recommendation = planeStatus.recommend else {
return planeStatus.planes.isEmpty ? "暂无无人机" : "状态待确认"
}
if let text = DroneDockHomeMetric.usableText(recommendation.statusText) { return text }
let state = DroneDockHomeMetric.usableText(recommendation.workStatusLabel) ?? "状态待确认"
let battery = DroneDockHomeMetric.usableText(recommendation.batteryLabel)
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 { 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 let createdTask {
if hasSubmittedSummon { return "任务 \(createdTask.taskID) 的召唤请求已提交,请等待任务状态更新" }
if let shootErrorMessage { return shootErrorMessage }
if summonOutcomeUnknown { return "召唤结果待核对,请勿重复提交" }
return "任务 \(createdTask.taskID) 已创建,等待召唤"
}
if let taskCreationErrorMessage { return taskCreationErrorMessage }
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, info.order.shotTotal != nil else { 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 "召唤功能暂未开放"
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
@@ -143,6 +461,8 @@ final class DroneDockPreparationViewModel {
private func clearProject() {
projectInfo = nil
// 已提交的任务仍归属原点位航线,暂时清空购买快照不能替它重新选项。
guard creationContextInvalidated || !isTaskSelectionLocked else { return }
selectedSpotID = nil
selectedRouteID = nil
}
@@ -152,6 +472,42 @@ final class DroneDockPreparationViewModel {
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
@@ -159,6 +515,36 @@ final class DroneDockPreparationViewModel {
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) {
summonOutcomeUnknown = true
shootErrorMessage = (reason.map { "\($0)。" } ?? "") + "召唤结果待核对,请先核对任务状态,勿重复提交"
}
private func markTaskCreationUnknown(reason: String? = nil) {
taskCreationOutcomeUnknown = true
taskCreationErrorMessage = (reason.map { "\($0)。" } ?? "") + "创建结果待核对,请先查看订单任务,勿重复提交"
}
private static func message(for error: Error) -> String? {
error is CancellationError ? nil : error.localizedDescription
}
@@ -0,0 +1,270 @@
import Foundation
/// 真实拍摄任务页只读状态,只按准备页传入的既有任务 ID 读取 shooting。
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 let service: any DroneDockShootingServing
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
private var identityInvalidated = false
/// 只注入读取服务,不依赖创建、召唤、开始拍摄或控制服务。
init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder,
service: any DroneDockShootingServing,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.taskID = taskID
self.order = order
self.service = service
self.currentContext = currentContext
}
/// 页面可见时读取同一任务;失败、取消或身份失效不沿用之前的执行门禁与读数。
@MainActor
func refresh() async {
guard !isLoading, !identityInvalidated else { return }
generation &+= 1
let requestGeneration = generation
isLoading = true
errorMessage = nil
response = nil
defer {
if generation == requestGeneration {
isLoading = false
if Task.isCancelled { response = nil }
}
}
guard accepts(requestGeneration) else { return }
guard context.canLoad, taskID > 0,
DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
errorMessage = "缺少有效任务、订单或景区信息,请返回工作台重新进入"
return
}
do {
let value = try await service.shooting(taskID: taskID, liveBattery: true)
guard accepts(requestGeneration) else { return }
guard matchesIdentity(value) else {
throw APIError.decodeFailed("拍摄任务返回的任务、订单或景区与当前页面不一致,请重新读取")
}
response = value
} catch {
guard accepts(requestGeneration) else { return }
response = nil
errorMessage = error is CancellationError ? nil : error.localizedDescription
}
}
/// 离开或进入后台时使旧请求失效;再次进入仍读取同一任务,不创建或召唤。
@MainActor
func invalidate() {
generation &+= 1
isLoading = false
response = nil
if !identityInvalidated { errorMessage = nil }
}
/// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。
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 errorMessage != nil { return "任务状态读取失败" }
if isLoading { return "正在获取任务状态" }
return usable(response?.ui?.title) ?? usable(response?.task?.statusLabel)
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
}
/// 保留服务端阶段说明与执行门禁原因;本模块不执行门禁给出的动作。
var statusMessage: String {
if let errorMessage { return errorMessage }
if isLoading { return "正在读取当前拍摄任务" }
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
}
/// 组合可信阶段与本轮可用动作,不从请求成功、执行中或指令列表推断飞行进度。
var presentation: DroneDockTaskPresentation {
if isLoading {
return DroneDockTaskPresentation(phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: deviceStatusText, action: .none, actionTitle: nil, isActionEnabled: false)
}
if 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:
action = .start
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄"
enabled = false
case .paused where response?.executeGate?.canExecute == true:
action = .resume
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "继续拍摄"
enabled = false
case .completed:
action = .materials
actionTitle = "查看素材"
enabled = true
default:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle, isActionEnabled: enabled)
}
/// 后端六项展示读数,不解析文案反推设备状态或数值单位。
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"))
}
/// 无有效快照时不展示旧读数;连接 false 自身不被转换为飞行阶段。
var isTelemetryStale: Bool { response == nil }
/// 完整服务端 data,供页面展示和联调查看。
var dataJSON: String? { response?.dataJSON }
@MainActor
private func accepts(_ requestGeneration: Int) -> Bool {
guard generation == requestGeneration, !Task.isCancelled else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
identityInvalidated = true
invalidate()
errorMessage = "账号或景区已变化,请返回工作台重新进入"
return false
}
return true
}
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, let failed = tasks.first(where: { $0.waylineStatus == 91 }) {
return usable(failed.waylineStatusLabel) ?? "任务执行失败"
}
if phase == .failed, let failed = tasks.first(where: { $0.status == 40 }) {
return usable(failed.statusLabel) ?? "任务执行失败"
}
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) }
}
/// 任务页六项读数的后端展示文本,保持服务端单位与零值。
struct DroneDockShootingTelemetry: Equatable, Sendable {
/// 电量读数。
let batteryText: String
/// 环境温度读数。
let temperatureText: String
/// 风速读数。
let windText: String
/// 雨量读数。
let rainText: String
/// 信号状态。
let signalText: String
/// 搜星状态。
let satelliteText: String
}
@@ -306,6 +306,9 @@ final class DroneDockHomeViewController: BaseViewController {
DroneDockRemotePreparationViewController(viewModel: DroneDockPreparationViewModel(
context: context, order: order,
service: DroneDockPreparationAPI(client: NetworkServices.shared.apiClient),
planeStatusService: DroneDockPlaneStatusAPI(client: NetworkServices.shared.apiClient),
taskCreationService: DroneDockTaskCreationAPI(client: NetworkServices.shared.apiClient),
shootService: DroneDockShootAPI(client: NetworkServices.shared.apiClient),
currentContext: { Self.currentContext() }
))
}
@@ -6,6 +6,22 @@ import UIKit
enum DroneDockPreview {
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
static func navigationController(arguments: [String]) -> UINavigationController? {
// 仅打开已存在任务进行只读联调;不经过创建或召唤流程。
if let taskArgument = arguments.first(where: { $0.hasPrefix("--dock-task-live=") }),
let taskID = Int(taskArgument.dropFirst("--dock-task-live=".count)), taskID > 0,
let orderArgument = arguments.first(where: { $0.hasPrefix("--dock-task-order=") }),
AppStore.shared.session.isLoggedIn {
let number = String(orderArgument.dropFirst("--dock-task-order=".count)).trimmingCharacters(in: .whitespacesAndNewlines)
if !number.isEmpty,
let data = try? JSONEncoder().encode(["order_number": number]),
let order = try? JSONDecoder().decode(DroneDockHomeOrder.self, from: data) {
let task = DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order,
context: DroneDockHomeViewController.currentContext())
let navigation = UINavigationController()
navigation.setViewControllers([DroneDockHomeViewController(), task], animated: false)
return navigation
}
}
if let argument = arguments.first(where: { $0.hasPrefix("--dock-delivery-live=") }), AppStore.shared.session.isLoggedIn {
let number = String(argument.dropFirst("--dock-delivery-live=".count))
if let data = try? JSONEncoder().encode(["order_number": number]),
@@ -29,6 +45,18 @@ enum DroneDockPreview {
return navigation
}
if arguments.contains("--dock-home-live"), AppStore.shared.session.isLoggedIn {
// 显式联调既有任务,只读取 shooting,避免为检查响应额外创建订单任务。
if let argument = arguments.first(where: { $0.hasPrefix("--dock-shooting-probe=") }),
let taskID = Int(argument.dropFirst("--dock-shooting-probe=".count)), taskID > 0 {
Task { @MainActor in
do {
_ = try await DroneDockShootingAPI(client: NetworkServices.shared.apiClient)
.shooting(taskID: taskID, liveBattery: true)
} catch {
print("[DroneDockShooting] Existing task read failed: \(error.localizedDescription)")
}
}
}
return UINavigationController(rootViewController: DroneDockHomeViewController())
}
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview", "--dock-ui-materials-preview", "--dock-ui-delivery-preview", "--dock-ui-delivery-review-preview"]
@@ -1,27 +1,41 @@
import SnapKit
import UIKit
/// 进入页面后通过 project-info 读取已购套餐、点位和航线。
/// 展示准备信息并提交召唤;业务成功后携同一任务 ID 进入真实拍摄任务页。
@MainActor
final class DroneDockRemotePreparationViewController: BaseViewController {
/// 当前订单与准备页的真实读取状态。
/// 当前订单、准备信息及任务创建状态。
let viewModel: DroneDockPreparationViewModel
/// 点位与航线沿用原准备页顺序,状态区单独承载加载和错误说明。
private enum Section: Int, CaseIterable { case order, points, routes, status }
private enum Section: Int, CaseIterable { case order, points, routes, status, creationResult, shootResult }
/// 点位与航线使用后端稳定 ID,刷新时保留有效选择。
private enum Item: Hashable { case order, point(Int), route(Int), emptyPoints, emptyRoutes, status }
private enum Item: Hashable { case order, point(Int), route(Int), emptyPoints, emptyRoutes, status, creationResult, shootResult }
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private let footerView = DronePreparationFooterView()
private let refreshControl = UIRefreshControl()
private var refreshTask: Task<Void, Never>?
private var planeStatusTask: Task<Void, Never>?
private var creationTask: Task<Void, Never>?
private var isStartingCreation = false
private let planeStatusPollDelay: @Sendable (UInt64) async throws -> Void
private var isRefreshing = false
private var isPageVisible = false
private var isApplicationActive = false
private var automaticallyOpenedTaskID: Int?
private let taskControllerFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
/// 注入只读状态源,不初始化本地演示订单或任务。
init(viewModel: DroneDockPreparationViewModel) {
/// 注入准备页业务状态和轮询等待,便于验证任务创建及页面生命周期。
init(viewModel: DroneDockPreparationViewModel,
taskControllerFactory: (@MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
planeStatusPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.viewModel = viewModel
self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in
DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context)
}
self.planeStatusPollDelay = planeStatusPollDelay
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@@ -29,7 +43,12 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit { refreshTask?.cancel() }
deinit {
refreshTask?.cancel()
planeStatusTask?.cancel()
creationTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
override func setupNavigationBar() {
title = "拍摄准备"
@@ -47,6 +66,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
collectionView.register(DronePreparationPointCell.self, forCellWithReuseIdentifier: "point")
collectionView.register(DronePreparationRouteCell.self, forCellWithReuseIdentifier: "route")
collectionView.register(DronePreparationEmptyCell.self, forCellWithReuseIdentifier: "message")
collectionView.register(DroneDockTaskCreationResultCell.self, forCellWithReuseIdentifier: "creationResult")
collectionView.register(DronePreparationHeadingView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "heading")
@@ -70,22 +90,35 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
override func bindActions() {
refreshControl.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
footerView.onRefreshTap = { [weak self] in self?.refreshPreparation() }
footerView.onPrimaryTap = { [weak self] in self?.createSelectedTask() }
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isPageVisible = true
isApplicationActive = UIApplication.shared.applicationState == .active
refreshPreparation()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
stopPlaneStatusPolling()
refreshTask?.cancel()
creationTask?.cancel()
isStartingCreation = false
isRefreshing = false
refreshControl.endRefreshing()
viewModel.invalidate()
}
private func refreshPreparation() {
guard !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning else { refreshControl.endRefreshing(); return }
startPlaneStatusPolling()
guard !isRefreshing else { return }
isRefreshing = true
refreshTask = Task { @MainActor [weak self] in
@@ -109,13 +142,93 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
}
}
/// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。
private func createSelectedTask() {
guard !isRefreshing, !isStartingCreation else { return }
if viewModel.canOpenShootingTask {
_ = openShootingTask(automatically: false)
return
}
guard viewModel.isPrimaryActionEnabled else { return }
isStartingCreation = true
applySnapshot(animated: false)
creationTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.prepareAndSummon { [weak self] in self?.applySnapshot(animated: false) }
guard !Task.isCancelled else { return }
self.isStartingCreation = false
if self.openShootingTask(automatically: true) { return }
self.applySnapshot(animated: true) { [weak self] in
guard let self,
let path = self.dataSource.indexPath(for: .shootResult) ?? self.dataSource.indexPath(for: .creationResult) else { return }
self.collectionView.scrollToItem(at: path, at: .top, animated: true)
}
}
}
/// 只在准备页可见且召唤已成功时导航一次;返回后允许主动查看同一任务。
@discardableResult
private func openShootingTask(automatically: Bool) -> Bool {
guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask,
let taskID = viewModel.createdTask?.taskID,
let navigationController, navigationController.topViewController === self,
!automatically || automaticallyOpenedTaskID != taskID else { return false }
automaticallyOpenedTaskID = taskID
let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context)
navigationController.pushViewController(controller, animated: true)
return true
}
/// 设备请求与购买快照各自更新,轮询不重载列表或改变点位、航线选择。
private func startPlaneStatusPolling() {
guard isPageVisible, isApplicationActive else { return }
stopPlaneStatusPolling()
let delay = planeStatusPollDelay
planeStatusTask = Task { @MainActor [weak self] in
while !Task.isCancelled {
guard let interval = await self?.refreshPlaneStatusIfVisible() else { return }
do { try await delay(interval) }
catch { return }
}
}
}
private func refreshPlaneStatusIfVisible() async -> UInt64? {
guard isPageVisible, isApplicationActive, !Task.isCancelled else { return nil }
await viewModel.refreshPlaneStatus()
guard isPageVisible, isApplicationActive, !Task.isCancelled else { return nil }
if viewModel.errorMessage != nil {
applySnapshot(animated: false)
} else {
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
}
return viewModel.pollIntervalNanoseconds
}
private func stopPlaneStatusPolling() {
planeStatusTask?.cancel()
planeStatusTask = nil
viewModel.invalidatePlaneStatus()
}
@objc private func applicationWillResignActive() {
isApplicationActive = false
stopPlaneStatusPolling()
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
}
@objc private func applicationDidBecomeActive() {
isApplicationActive = true
startPlaneStatusPolling()
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
guard let self else { return nil }
switch item {
case .order:
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DronePreparationOrderCell
cell.apply(homeOrder: self.viewModel.order, summary: self.viewModel.projectInfo?.order,
cell.apply(homeOrder: self.viewModel.order, summary: self.viewModel.latestOrderSummary,
usesHomeSnapshot: self.viewModel.projectInfo == nil && self.viewModel.errorMessage == nil)
return cell
case .point(let id):
@@ -130,6 +243,20 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
cell.apply(route: route, selected: self.viewModel.selectedRouteID == id)
}
return cell
case .creationResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.apply(task: self.viewModel.createdTask, errorMessage: self.viewModel.taskCreationErrorMessage,
outcomeUnknown: self.viewModel.taskCreationOutcomeUnknown)
return cell
case .shootResult:
let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell
cell.applyShoot(taskID: self.viewModel.createdTask?.taskID,
dataJSON: self.viewModel.shootDataJSON,
errorMessage: self.viewModel.shootErrorMessage,
isLoading: self.viewModel.isSummoning,
hasSucceeded: self.viewModel.shootResponse != nil,
outcomeUnknown: self.viewModel.summonOutcomeUnknown)
return cell
case .emptyPoints, .emptyRoutes, .status:
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell
if item == .status {
@@ -177,8 +304,15 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
} else {
snapshot.appendItems([.status], toSection: .status)
}
if viewModel.createdTask != nil || (viewModel.errorMessage == nil && viewModel.projectInfo != nil && viewModel.taskCreationErrorMessage != nil) {
snapshot.appendItems([.creationResult], toSection: .creationResult)
}
if viewModel.createdTask != nil,
viewModel.isSummoning || viewModel.shootResponse != nil || viewModel.shootErrorMessage != nil {
snapshot.appendItems([.shootResult], toSection: .shootResult)
}
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing)
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
let previousPointCount = previous.sectionIdentifiers.contains(.points) ? previous.numberOfItems(inSection: .points) : 0
let previousRouteCount = previous.sectionIdentifiers.contains(.routes) ? previous.numberOfItems(inSection: .routes) : 0
let layoutChanged = previousPointCount != snapshot.numberOfItems(inSection: .points)
@@ -212,11 +346,13 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
height = self.viewModel.routes.isEmpty ? .absolute(160) : .estimated(64)
width = .fractionalWidth(1)
case .status: height = .absolute(160); width = .fractionalWidth(1)
case .creationResult: height = .absolute(380); width = .fractionalWidth(1)
case .shootResult: height = .absolute(420); width = .fractionalWidth(1)
}
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
let layout = NSCollectionLayoutSection(group: group)
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: section == .status ? 12 : 0, trailing: 16)
layout.contentInsets = NSDirectionalEdgeInsets(top: section == .shootResult ? 12 : 0, leading: 16, bottom: section == .status ? 12 : 0, trailing: 16)
if section == .points, !self.viewModel.spots.isEmpty {
layout.orthogonalScrollingBehavior = .continuous
layout.interGroupSpacing = 8
@@ -265,7 +401,9 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
extension DroneDockRemotePreparationViewController: UICollectionViewDelegate {
/// 点位和航线只在当前成功快照中选择,刷新期间不切换旧配置。
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
guard !isRefreshing, viewModel.projectInfo != nil, viewModel.errorMessage == nil,
guard !isRefreshing, !isStartingCreation, !viewModel.isCreatingTask,
viewModel.createdTask == nil, !viewModel.taskCreationOutcomeUnknown,
viewModel.projectInfo != nil, viewModel.errorMessage == nil,
let item = dataSource.itemIdentifier(for: indexPath) else { return false }
switch item {
case .point(let id): return viewModel.spots.first { $0.id == id }?.available == true
@@ -276,7 +414,9 @@ extension DroneDockRemotePreparationViewController: UICollectionViewDelegate {
/// 更新本地点位、航线及底部摘要,不创建拍摄任务。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard !isRefreshing, let item = dataSource.itemIdentifier(for: indexPath) else { return }
guard !isRefreshing, !isStartingCreation, !viewModel.isCreatingTask,
viewModel.createdTask == nil, !viewModel.taskCreationOutcomeUnknown,
let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .point(let id): viewModel.selectSpot(id: id)
case .route(let id): viewModel.selectRoute(id: id)
@@ -0,0 +1,15 @@
import UIKit
/// 组装真实拍摄任务页;构造时不发请求,页面出现后才读取同一任务。
@MainActor
enum DroneDockShootingTaskEntry {
/// 使用当前共享网络服务读取已创建、已召唤任务,不创建或控制无人机。
static func makeController(taskID: Int, order: DroneDockHomeOrder,
context: DroneDockHomeContext) -> UIViewController {
DroneDockShootingTaskViewController(viewModel: DroneDockShootingTaskViewModel(
context: context, taskID: taskID, order: order,
service: DroneDockShootingAPI(client: NetworkServices.shared.apiClient),
currentContext: { DroneDockHomeViewController.currentContext() }
))
}
}
@@ -0,0 +1,344 @@
import SnapKit
import UIKit
/// 真实拍摄任务页:进入后仅查询同一任务,展示状态与遥测,不发送飞行控制。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
let viewModel: DroneDockShootingTaskViewModel
private let topView = UIView()
private let summaryView = UIView()
private let taskTitleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
private let subtitleLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let feedPlaceholder = DroneDockTaskFeedPlaceholderView()
private let telemetryView = DroneShootingTaskTelemetryView()
private let statusView = DroneDockTaskStatusView()
private let safetyView = DroneDockTaskSafetyView()
private var summaryHeight: Constraint?
private var safetyHeight: Constraint?
private var compactLayout: Bool?
private var bottomInset: CGFloat = -1
private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private var refreshTask: Task<Void, Never>?
private var requestGeneration = 0
private var isPageVisible = false
private var isApplicationActive = false
private var isRequesting = false
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
self.viewModel = viewModel
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
service: DroneDockMaterialsAPI(client: NetworkServices.shared.apiClient),
currentContext: { DroneDockHomeViewController.currentContext() }))
}
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit {
refreshTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
/// 使用常规导航返回准备页,不劫持返回手势或自动创建任务。
override func setupNavigationBar() {
title = "拍摄任务"
navigationItem.backButtonDisplayMode = .minimal
let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain,
target: self, action: #selector(refreshTriggered))
refresh.accessibilityLabel = "刷新任务状态"
refresh.accessibilityIdentifier = "drone.task.remote.navigationRefresh"
navigationItem.rightBarButtonItem = refresh
}
/// 顶部、中间状态和安全控制分开布局,状态切换不影响外部区域大小。
override func setupUI() {
view.backgroundColor = .white
topView.accessibilityIdentifier = "drone.task.remote.top"
summaryView.accessibilityIdentifier = "drone.task.remote.summary"
statusView.accessibilityIdentifier = "drone.task.remote.stateContainer"
safetyView.accessibilityIdentifier = "drone.task.remote.safety"
view.addSubview(topView)
view.addSubview(statusView)
view.addSubview(safetyView)
topView.addSubview(summaryView)
summaryView.addSubview(taskTitleLabel)
summaryView.addSubview(subtitleLabel)
taskTitleLabel.numberOfLines = 1
taskTitleLabel.lineBreakMode = .byTruncatingTail
taskTitleLabel.accessibilityIdentifier = "drone.task.remote.title"
subtitleLabel.numberOfLines = 1
subtitleLabel.lineBreakMode = .byTruncatingTail
subtitleLabel.accessibilityIdentifier = "drone.task.remote.subtitle"
topView.addSubview(feedPlaceholder)
topView.addSubview(telemetryView)
telemetryView.accessibilityIdentifier = "drone.task.remote.telemetry"
telemetryView.configureFixedLayout(compact: false)
applySnapshot()
}
/// 图传保持 16:9,底部贴安全区,中间占满剩余空间且没有滚动容器。
override func setupConstraints() {
topView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.equalToSuperview()
}
summaryView.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
summaryHeight = make.height.equalTo(60).constraint
}
taskTitleLabel.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.bottom.equalTo(summaryView.snp.centerY).offset(-1)
}
subtitleLabel.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.top.equalTo(summaryView.snp.centerY).offset(2)
}
feedPlaceholder.snp.makeConstraints { make in
make.top.equalTo(summaryView.snp.bottom)
make.leading.trailing.equalToSuperview()
make.height.equalTo(feedPlaceholder.snp.width).multipliedBy(9.0 / 16.0)
}
telemetryView.snp.makeConstraints { make in
make.top.equalTo(feedPlaceholder.snp.bottom)
make.leading.trailing.bottom.equalToSuperview()
}
safetyView.snp.makeConstraints { make in
make.leading.trailing.bottom.equalToSuperview()
safetyHeight = make.height.equalTo(104).constraint
}
statusView.snp.makeConstraints { make in
make.top.equalTo(topView.snp.bottom)
make.bottom.equalTo(safetyView.snp.top)
make.leading.trailing.equalToSuperview()
}
}
/// 只按设备可用尺寸调整固定区域,数据、错误和加载状态不会改变它们的高度。
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let availableHeight = view.bounds.height - view.safeAreaInsets.top - view.safeAreaInsets.bottom
let compact = availableHeight < 680
let inset = view.safeAreaInsets.bottom
guard compactLayout != compact || bottomInset != inset else { return }
compactLayout = compact
bottomInset = inset
summaryHeight?.update(offset: compact ? 44 : 60)
safetyHeight?.update(offset: (compact ? 90 : 104) + inset)
telemetryView.configureFixedLayout(compact: compact)
safetyView.configure(compact: compact)
taskTitleLabel.font = .systemFont(ofSize: compact ? 16 : 17, weight: .semibold)
}
/// 仅绑定读取、详情和已有素材入口;本轮不发送飞控指令。
override func bindActions() {
statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() }
statusView.onDetails = { [weak self] in self?.showStatusDetails() }
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification, object: nil)
}
/// 每次完整进入任务页只查询一次,不定时重读同一任务。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
isApplicationActive = UIApplication.shared.applicationState == .active
refreshTaskIfVisible()
}
/// 离页立即取消未完成的读取,使迟到响应失效。
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
cancelRefresh()
}
private func applySnapshot() {
guard isViewLoaded else { return }
let loading = isRequesting || viewModel.isLoading
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle
let telemetry = viewModel.telemetry
telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText],
isStale: loading || viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric")
let value = loading ? DroneDockTaskPresentation(
phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务",
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
statusView.apply(value)
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItem?.isEnabled = isPageVisible && isApplicationActive && !loading
}
private func primaryActionTriggered() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
let state = viewModel.presentation
guard state.isActionEnabled else { return }
switch state.action {
case .refresh:
refreshTaskIfVisible()
case .materials:
guard let navigationController, navigationController.topViewController === self else { return }
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
case .start, .resume, .none:
break
}
}
private func showStatusDetails() {
guard isPageVisible, isApplicationActive, presentedViewController == nil else { return }
let state = viewModel.presentation
let texts = [state.title, state.message, state.deviceStatus].filter { !$0.isEmpty && $0 != "—" }
var distinct: [String] = []
for text in texts where !distinct.contains(text) { distinct.append(text) }
let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "关闭", style: .cancel))
present(alert, animated: true)
}
/// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。
private func refreshTaskIfVisible() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
requestGeneration &+= 1
let generation = requestGeneration
isRequesting = true
applySnapshot()
refreshTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.refresh()
guard self.isPageVisible, self.isApplicationActive,
self.requestGeneration == generation, !Task.isCancelled else { return }
self.refreshTask = nil
self.isRequesting = false
self.applySnapshot()
}
}
private func cancelRefresh() {
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
isRequesting = false
viewModel.invalidate()
applySnapshot()
}
@objc private func refreshTriggered() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else {
return
}
refreshTaskIfVisible()
}
@objc private func applicationWillResignActive() {
isApplicationActive = false
cancelRefresh()
}
@objc private func applicationDidBecomeActive() {
guard !isApplicationActive else { return }
isApplicationActive = true
refreshTaskIfVisible()
}
}
/// 固定底部的安全控制占位,尚未接入控制接口时不提供可执行的飞控动作。
@MainActor
private final class DroneDockTaskSafetyView: UIView {
private let header = DroneDockStyle.label("安全控制", size: 11, color: DroneDockStyle.secondary)
private let pauseButton = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: UIColor(hex: 0xEC982A), filled: true)
private let returnButton = DroneShootingTaskSafetyButton(symbol: "arrow.uturn.backward", color: UIColor(hex: 0xD85762), filled: false)
private let buttons = UIStackView()
private var headerTop: Constraint?
private var headerHeight: Constraint?
private var buttonGap: Constraint?
private var buttonHeight: Constraint?
/// 复用安全按钮样式,按钮始终保留占位与明确的不可用状态。
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
let divider = UIView()
divider.backgroundColor = DroneDockStyle.border
addSubview(divider)
divider.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
make.height.equalTo(0.5)
}
header.textAlignment = .center
addSubview(header)
buttons.axis = .horizontal
buttons.spacing = 8
buttons.distribution = .fillEqually
buttons.addArrangedSubview(pauseButton)
buttons.addArrangedSubview(returnButton)
addSubview(buttons)
pauseButton.accessibilityIdentifier = "drone.task.remote.pause"
returnButton.accessibilityIdentifier = "drone.task.remote.return"
pauseButton.apply(title: "紧急暂停", subtitle: "暂不可用", enabled: false)
returnButton.apply(title: "立即返航", subtitle: "暂不可用", enabled: false)
header.snp.makeConstraints { make in
headerTop = make.top.equalToSuperview().offset(10).constraint
make.leading.trailing.equalToSuperview().inset(16)
headerHeight = make.height.equalTo(14).constraint
}
buttons.snp.makeConstraints { make in
buttonGap = make.top.equalTo(header.snp.bottom).offset(8).constraint
make.leading.trailing.equalToSuperview().inset(16)
buttonHeight = make.height.equalTo(62).constraint
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 高度仅依设备空间切换,不随任务状态、按钮文案或网络响应变化。
func configure(compact: Bool) {
headerTop?.update(offset: compact ? 8 : 10)
headerHeight?.update(offset: compact ? 12 : 14)
buttonGap?.update(offset: compact ? 6 : 8)
buttonHeight?.update(offset: compact ? 56 : 62)
}
}
/// 真实图传尚未接入时的中性占位,不使用演示图片、播放进度或虚假连接状态。
@MainActor
private final class DroneDockTaskFeedPlaceholderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(hex: 0x172033)
accessibilityIdentifier = "drone.task.remote.feedPlaceholder"
let icon = UIImageView(image: UIImage(systemName: "video.slash"))
icon.contentMode = .scaleAspectFit
icon.tintColor = UIColor.white.withAlphaComponent(0.6)
let title = DroneDockStyle.label("图传暂未接入", size: 15, weight: .medium, color: .white)
let detail = DroneDockStyle.label("任务状态将在下方更新", size: 12, color: .white.withAlphaComponent(0.65))
let stack = UIStackView(arrangedSubviews: [icon, title, detail])
stack.axis = .vertical
stack.spacing = 9
stack.alignment = .center
addSubview(stack)
icon.snp.makeConstraints { make in make.size.equalTo(31) }
stack.snp.makeConstraints { make in
make.center.equalToSuperview()
make.leading.greaterThanOrEqualToSuperview().offset(20)
make.trailing.lessThanOrEqualToSuperview().offset(-20)
}
isAccessibilityElement = true
accessibilityLabel = "图传暂未接入,任务状态将在下方更新"
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
@@ -0,0 +1,80 @@
import SnapKit
import UIKit
/// 在准备页展示任务创建或召唤请求的回执,保留 data 原文结构并支持滚动与选择文本。
@MainActor
final class DroneDockTaskCreationResultCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let responseView = UITextView()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = DroneDockStyle.background
contentView.layer.cornerRadius = 10
titleLabel.numberOfLines = 0
detailLabel.numberOfLines = 0
responseView.backgroundColor = .clear
responseView.isEditable = false
responseView.isSelectable = true
responseView.alwaysBounceVertical = true
responseView.textContainerInset = .zero
responseView.textContainer.lineFragmentPadding = 0
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
[titleLabel, detailLabel, responseView].forEach(contentView.addSubview)
titleLabel.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview().inset(12)
}
detailLabel.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(6)
make.leading.trailing.equalTo(titleLabel)
}
responseView.snp.makeConstraints { make in
make.top.equalTo(detailLabel.snp.bottom).offset(12)
make.leading.trailing.equalTo(titleLabel)
make.bottom.equalToSuperview().inset(12)
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 成功保留完整 data,失败显示真实错误,不构造任务 ID 或成功响应。
func apply(task: DroneDockCreatedTask?, errorMessage: String?, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.creationResponse"
if let task {
titleLabel.text = "任务已创建 · ID \(task.taskID)"
titleLabel.textColor = DroneDockStyle.success
detailLabel.text = "tasks/create 返回的 data"
responseView.font = .monospacedSystemFont(ofSize: 12, weight: .regular)
if responseView.text != task.dataJSON { responseView.text = task.dataJSON }
} else {
titleLabel.text = outcomeUnknown ? "任务创建结果待确认" : "任务创建未成功"
titleLabel.textColor = DroneDockStyle.warning
detailLabel.text = outcomeUnknown ? "请先核对订单任务,避免重复创建" : "接口返回的错误信息"
responseView.font = .systemFont(ofSize: 14)
responseView.text = errorMessage
}
responseView.textColor = DroneDockStyle.text
}
/// 展示 shoot 回执;提交成功不代表无人机已到达,结果未知不能引导直接重发。
func applyShoot(taskID: Int?, dataJSON: String?, errorMessage: String?, isLoading: Bool,
hasSucceeded: Bool, outcomeUnknown: Bool) {
responseView.accessibilityIdentifier = "drone.preparation.shootResponse"
let suffix = taskID.map { " · ID \($0)" } ?? ""
let title: String
if isLoading { title = "正在召唤无人机" }
else if hasSucceeded { title = "召唤请求已提交" }
else { title = outcomeUnknown ? "召唤结果待核对" : "召唤请求未成功" }
titleLabel.text = title + suffix
titleLabel.textColor = hasSucceeded ? DroneDockStyle.success : errorMessage == nil ? DroneDockStyle.text : DroneDockStyle.warning
if isLoading { detailLabel.text = "正在为已创建的任务提交召唤请求" }
else if hasSucceeded { detailLabel.text = "shoot 返回信息;飞行进度以任务状态为准" }
else { detailLabel.text = outcomeUnknown ? "请先核对任务状态,避免重复发送召唤" : "任务已保留,可重试召唤" }
responseView.font = dataJSON == nil ? .systemFont(ofSize: 14) : .monospacedSystemFont(ofSize: 12, weight: .regular)
let text = dataJSON ?? errorMessage ?? (hasSucceeded ? "接口已返回业务成功,未提供可展示的 data。" : "")
if responseView.text != text { responseView.text = text }
responseView.textColor = DroneDockStyle.text
}
}
@@ -0,0 +1,243 @@
import SnapKit
import UIKit
/// 固定区域内组合任务状态与主操作,根据可用高度收紧内容,不滚动或改变外部尺寸。
@MainActor
final class DroneDockTaskStatusView: UIView {
/// 当前状态的主操作,由页面协调执行,不在组件中调用接口。
var onPrimaryAction: (() -> Void)?
/// 展开完整状态说明,由页面提供详情展示。
var onDetails: (() -> Void)?
/// 当前内容采用的字号和间距参考比例,始终介于 0.8 与 1。
private(set) var effectiveScale: CGFloat = 1
/// 中间区域不足以显示常规内容时采用紧凑布局。
private(set) var usesCompactLayout = false
private let contentStack = UIStackView()
private let titleRow = UIView()
private let iconView = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 22, weight: .semibold)
private let messageLabel = DroneDockStyle.label(size: 14, color: DroneDockStyle.secondary)
private let deviceLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let actionRow = UIView()
private let primaryButton = UIButton(type: .system)
private let detailsButton = UIButton(type: .system)
private var presentation: DroneDockTaskPresentation?
private var contentTop: Constraint?
private var contentLeading: Constraint?
private var contentTrailing: Constraint?
private var iconSize: Constraint?
private var titleLeading: Constraint?
private var titleRowHeight: Constraint?
private var messageHeight: Constraint?
private var deviceHeight: Constraint?
/// 创建稳定的标题、说明、设备摘要与操作槽,所有状态复用同一组视图。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 外部容器决定高度;状态内容不会通过固有尺寸推高底部安全区。
override var intrinsicContentSize: CGSize {
CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
/// 更新真实状态文案与动作许可,不补造百分比或自行推导飞行阶段。
func apply(_ presentation: DroneDockTaskPresentation) {
self.presentation = presentation
titleLabel.text = presentation.title
messageLabel.text = presentation.message
deviceLabel.text = presentation.deviceStatus
let style = Self.style(for: presentation.phase)
iconView.image = UIImage(systemName: style.symbol)
iconView.tintColor = style.color
let actionTitle = DroneDockHomeMetric.usableText(presentation.actionTitle)
primaryButton.isHidden = presentation.action == .none || actionTitle == nil
primaryButton.setTitle(actionTitle, for: .normal)
primaryButton.isEnabled = presentation.isActionEnabled && !primaryButton.isHidden
primaryButton.backgroundColor = primaryButton.isEnabled
? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.35)
primaryButton.accessibilityIdentifier = presentation.action == .refresh
? "drone.task.remote.refresh" : "drone.task.remote.primary"
setNeedsLayout()
}
/// 尺寸改变时仅重排内部内容,保留至少 44 点操作区域,不使用 transform 缩放。
override func layoutSubviews() {
updateContentLayout()
super.layoutSubviews()
}
private func setupUI() {
backgroundColor = .white
contentStack.axis = .vertical
contentStack.alignment = .fill
contentStack.spacing = 10
addSubview(contentStack)
contentStack.addArrangedSubview(titleRow)
contentStack.addArrangedSubview(messageLabel)
contentStack.addArrangedSubview(deviceLabel)
contentStack.addArrangedSubview(actionRow)
titleRow.addSubview(iconView)
titleRow.addSubview(titleLabel)
iconView.contentMode = .scaleAspectFit
titleLabel.numberOfLines = 2
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.accessibilityTraits = .header
titleLabel.accessibilityIdentifier = "drone.task.remote.statusTitle"
messageLabel.numberOfLines = 3
messageLabel.lineBreakMode = .byTruncatingTail
messageLabel.accessibilityIdentifier = "drone.task.remote.statusMessage"
deviceLabel.numberOfLines = 1
deviceLabel.lineBreakMode = .byTruncatingTail
deviceLabel.accessibilityIdentifier = "drone.task.remote.deviceStatus"
actionRow.addSubview(primaryButton)
actionRow.addSubview(detailsButton)
primaryButton.layer.cornerRadius = 9
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.lineBreakMode = .byTruncatingTail
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(.white.withAlphaComponent(0.9), for: .disabled)
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
detailsButton.setTitle("详情", for: .normal)
detailsButton.setTitleColor(DroneDockStyle.primary, for: .normal)
detailsButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
detailsButton.backgroundColor = DroneDockStyle.background
detailsButton.layer.cornerRadius = 9
detailsButton.accessibilityIdentifier = "drone.task.remote.details"
detailsButton.accessibilityLabel = "查看完整任务状态"
detailsButton.addTarget(self, action: #selector(detailsTapped), for: .touchUpInside)
}
private func setupConstraints() {
contentStack.snp.makeConstraints { make in
contentTop = make.top.equalToSuperview().offset(12).constraint
contentLeading = make.leading.equalToSuperview().offset(16).constraint
contentTrailing = make.trailing.equalToSuperview().inset(16).constraint
}
titleRow.snp.makeConstraints { make in titleRowHeight = make.height.equalTo(36).priority(999).constraint }
iconView.snp.makeConstraints { make in
make.leading.centerY.equalToSuperview()
iconSize = make.size.equalTo(36).constraint
}
titleLabel.snp.makeConstraints { make in
titleLeading = make.leading.equalTo(iconView.snp.trailing).offset(10).constraint
make.trailing.centerY.equalToSuperview()
}
messageLabel.snp.makeConstraints { make in messageHeight = make.height.equalTo(34).priority(999).constraint }
deviceLabel.snp.makeConstraints { make in deviceHeight = make.height.equalTo(16).priority(999).constraint }
actionRow.snp.makeConstraints { make in make.height.equalTo(44) }
detailsButton.snp.makeConstraints { make in
make.top.trailing.bottom.equalToSuperview()
make.width.equalTo(64)
}
primaryButton.snp.makeConstraints { make in
make.top.leading.bottom.equalToSuperview()
make.trailing.equalTo(detailsButton.snp.leading).offset(-8)
}
}
private func updateContentLayout() {
guard let presentation, bounds.width > 0, bounds.height > 0 else { return }
let isExtreme = bounds.height < 120
let horizontalInset: CGFloat = isExtreme ? 12 : 16
let verticalInset: CGFloat = isExtreme ? 6 : 12
let width = max(1, bounds.width - horizontalInset * 2)
let availableHeight = max(1, bounds.height - verticalInset * 2)
let message = DroneDockHomeMetric.usableText(presentation.message)
let hasMessage = message != nil && message != DroneDockHomeMetric.usableText(presentation.title)
let device = DroneDockHomeMetric.usableText(presentation.deviceStatus)
let hasDevice = device != nil && device != "—"
let naturalTitle = max(36, Self.textHeight(presentation.title, font: .systemFont(ofSize: 22, weight: .semibold),
width: width - 46, lines: 2))
let naturalMessage = hasMessage ? Self.textHeight(message, font: .systemFont(ofSize: 14), width: width, lines: 3) : 0
let naturalDevice = hasDevice ? UIFont.systemFont(ofSize: 12).lineHeight : 0
let naturalGaps = CGFloat(1 + (hasMessage ? 1 : 0) + (hasDevice ? 1 : 0)) * 10
let naturalHeight = naturalTitle + naturalMessage + naturalDevice + 44 + naturalGaps
effectiveScale = min(1, max(0.8, availableHeight / max(1, naturalHeight)))
usesCompactLayout = bounds.height < 190 || naturalHeight * effectiveScale > availableHeight
// 先收紧图标和间距;只有不足九成空间时才缩小文字。
let fontScale: CGFloat = effectiveScale >= 0.9 ? 1 : effectiveScale / 0.9
titleLabel.font = .systemFont(ofSize: max(17, 22 * fontScale), weight: .semibold)
messageLabel.font = .systemFont(ofSize: max(12, 14 * fontScale))
deviceLabel.font = .systemFont(ofSize: 12)
let icon: CGFloat = isExtreme ? 20 : usesCompactLayout ? 24 : 36 * effectiveScale
let gap: CGFloat = isExtreme ? 4 : max(4, 10 * effectiveScale)
let titleGap: CGFloat = usesCompactLayout ? 8 : 10 * effectiveScale
titleLabel.numberOfLines = usesCompactLayout ? 1 : 2
messageLabel.numberOfLines = usesCompactLayout ? 2 : 3
messageLabel.isHidden = !hasMessage || isExtreme
deviceLabel.isHidden = !hasDevice || usesCompactLayout
let titleWidth = max(1, width - icon - titleGap)
var titleHeight = max(icon, Self.textHeight(presentation.title, font: titleLabel.font,
width: titleWidth, lines: titleLabel.numberOfLines))
var messageLineCount = messageLabel.numberOfLines
var bodyHeight = messageLabel.isHidden ? 0 : Self.textHeight(message, font: messageLabel.font,
width: width, lines: messageLineCount)
let deviceTextHeight = deviceLabel.isHidden ? 0 : ceil(deviceLabel.font.lineHeight)
var contentHeight: CGFloat {
titleHeight + bodyHeight + deviceTextHeight + 44
+ CGFloat(1 + (messageLabel.isHidden ? 0 : 1) + (deviceLabel.isHidden ? 0 : 1)) * gap
}
while contentHeight > availableHeight && messageLineCount > 1 && !messageLabel.isHidden {
messageLineCount -= 1
bodyHeight = Self.textHeight(message, font: messageLabel.font, width: width, lines: messageLineCount)
}
if contentHeight > availableHeight && titleLabel.numberOfLines > 1 {
titleLabel.numberOfLines = 1
titleHeight = max(icon, ceil(titleLabel.font.lineHeight))
}
if contentHeight > availableHeight && !messageLabel.isHidden {
messageLabel.isHidden = true
bodyHeight = 0
}
messageLabel.numberOfLines = messageLineCount
let top = verticalInset + max(0, (availableHeight - contentHeight) / 2)
contentTop?.update(offset: top)
contentLeading?.update(offset: horizontalInset)
contentTrailing?.update(inset: horizontalInset)
iconSize?.update(offset: icon)
titleLeading?.update(offset: titleGap)
titleRowHeight?.update(offset: titleHeight)
messageHeight?.update(offset: max(1, bodyHeight))
deviceHeight?.update(offset: max(1, deviceTextHeight))
contentStack.spacing = gap
}
private static func textHeight(_ text: String?, font: UIFont, width: CGFloat, lines: Int) -> CGFloat {
guard let text, !text.isEmpty else { return ceil(font.lineHeight) }
let height = (text as NSString).boundingRect(with: CGSize(width: max(1, width), height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
attributes: [.font: font], context: nil).height
return ceil(min(height, font.lineHeight * CGFloat(lines)))
}
private static func style(for phase: DroneDockTaskDisplayPhase) -> (symbol: String, color: UIColor) {
switch phase {
case .loading: ("clock.arrow.circlepath", DroneDockStyle.primary)
case .navigating: ("paperplane.fill", DroneDockStyle.primary)
case .ready: ("checkmark.circle.fill", DroneDockStyle.success)
case .shooting: ("video.fill", DroneDockStyle.primary)
case .paused: ("pause.circle.fill", DroneDockStyle.warning)
case .returning: ("arrow.uturn.backward.circle.fill", DroneDockStyle.warning)
case .completed: ("checkmark.circle.fill", DroneDockStyle.success)
case .failed: ("xmark.circle.fill", UIColor(hex: 0xD46B62))
case .blocked, .readError: ("exclamationmark.circle.fill", DroneDockStyle.warning)
case .unknown: ("questionmark.circle.fill", DroneDockStyle.secondary)
}
}
@objc private func primaryTapped() {
guard primaryButton.isEnabled, !primaryButton.isHidden else { return }
onPrimaryAction?()
}
@objc private func detailsTapped() { onDetails?() }
}
@@ -416,6 +416,9 @@ final class DronePreparationFooterView: UIView {
let divider = UIView()
divider.backgroundColor = DroneDockStyle.border
let deviceRow = UIStackView(arrangedSubviews: [deviceCaption, deviceLabel, UIView()])
deviceLabel.accessibilityIdentifier = "drone.preparation.planeStatus"
deviceLabel.numberOfLines = 2
deviceLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
deviceRow.axis = .horizontal
deviceRow.alignment = .center
deviceRow.spacing = 3
@@ -497,20 +500,25 @@ final class DronePreparationFooterView: UIView {
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
}
/// 展示真实准备状态;本阶段保留召唤按钮文案,但尚不提供飞行执行入口。
/// 按购买权限启用待飞任务创建;本阶段不提供无人机召唤或起飞入口。
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false) {
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
selectionLabel.text = viewModel.selectionSummary
selectionLabel.numberOfLines = 2
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceTone)
primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal)
primaryButton.isEnabled = false
primaryButton.backgroundColor = UIColor(hex: 0xE1E7F0)
primaryButton.isEnabled = (viewModel.isPrimaryActionEnabled || viewModel.canOpenShootingTask) && !isRefreshing
primaryButton.backgroundColor = primaryButton.isEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE1E7F0)
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(UIColor(hex: 0x8792A5), for: .disabled)
messageLabel.text = viewModel.admissionMessage
if viewModel.isTaskSelectionLocked || viewModel.taskCreationErrorMessage != nil {
messageLabel.text = viewModel.admissionMessage
} else {
messageLabel.text = viewModel.planeStatusErrorMessage.map { "无人机状态获取失败:\($0)" } ?? viewModel.admissionMessage
}
messageLabel.textColor = DroneDockStyle.secondary
refreshButton.isHidden = false
refreshButton.isEnabled = !viewModel.isLoading && !isRefreshing
refreshButton.isEnabled = !viewModel.isLoading && !viewModel.isCreatingTask && !viewModel.isSummoning && !isRefreshing
}
@objc private func primaryTapped() { onPrimaryTap?() }
@@ -158,6 +158,9 @@ final class DroneShootingTaskTelemetryView: UIView {
private let stackView = UIStackView()
private let staleLabel = DroneDockStyle.label("ⓘ 状态暂未更新", size: 11, color: DroneDockStyle.secondary)
private var cells: [DroneShootingTaskTelemetryCell] = []
private var rowHeights: [Constraint] = []
private var contentEdges: Constraint?
private var usesFixedLayout = false
/// 以两行三列固定展示电量、温度、风速、雨量、信号与搜星。
override init(frame: CGRect) {
@@ -184,22 +187,38 @@ final class DroneShootingTaskTelemetryView: UIView {
row.addArrangedSubview(cell)
}
stackView.addArrangedSubview(row)
row.snp.makeConstraints { make in make.height.equalTo(55) }
row.snp.makeConstraints { make in rowHeights.append(make.height.equalTo(55).constraint) }
}
stackView.snp.makeConstraints { make in make.edges.equalToSuperview().inset(10) }
stackView.snp.makeConstraints { make in contentEdges = make.edges.equalToSuperview().inset(10).constraint }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 固定任务页不增减状态提示行;小屏仅压缩格子间距与留白,六项参数位置保持稳定。
func configureFixedLayout(compact: Bool) {
usesFixedLayout = true
staleLabel.isHidden = true
rowHeights.forEach { $0.update(offset: compact ? 46 : 55) }
stackView.spacing = compact ? 4 : 6
contentEdges?.update(inset: compact ? 8 : 10)
}
/// 新快照覆盖全部读数;不保留断网前的值冒充有效数据。
func apply(telemetry: DroneDockTelemetry, isStale: Bool) {
staleLabel.isHidden = !isStale
let values = isStale
? Array(repeating: "—", count: 6)
: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText, telemetry.rainText, telemetry.signalText, telemetry.satelliteText]
apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText,
telemetry.rainText, telemetry.signalText, telemetry.satelliteText], isStale: isStale)
}
/// 展示后端已格式化的六项读数,保留单位;缺项与过期读数显示破折号。
func apply(values: [String], isStale: Bool, accessibilityPrefix: String? = nil) {
staleLabel.isHidden = usesFixedLayout || !isStale
let keys = ["battery", "temperature", "wind", "rain", "signal", "satellite"]
for (index, cell) in cells.enumerated() {
cell.apply(value: values[index], isStale: isStale)
let value = !isStale && values.indices.contains(index)
? DroneDockHomeMetric.usableText(values[index]) ?? "—" : "—"
cell.apply(value: value, isStale: isStale)
if let accessibilityPrefix { cell.accessibilityIdentifier = "\(accessibilityPrefix).\(keys[index])" }
}
}
}