feat(drone-dock): 接入首页真实数据并完善设备卡片

通过 airport/home 读取当前景区和门店的设备与统计,隔离失效会话回包,未知遥测显示破折号。完善状态圆点、分割线和卫星图标;订单详情等待后端测试数据。

验证:iPhone 11 上 49 项相关测试、样式调整后 9 项界面回归,以及测试样例匿名化后 20 项测试均通过。真实联调响应、日志和截图仅保留在本地。
This commit is contained in:
2026-10-27 15:05:51 +08:00
parent 7862d208ce
commit 40060cd883
15 changed files with 1739 additions and 14 deletions
@@ -0,0 +1,16 @@
{
"images" : [
{
"filename" : "drone_telemetry_satellite.svg",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
},
"properties" : {
"preserves-vector-representation" : true,
"template-rendering-intent" : "template"
}
}
@@ -0,0 +1,11 @@
<!-- Tabler Icons satellite, as used by https://voicestudio.suixinkan.cn/.
Copyright (c) 2020-2026 Paweł Kuna, MIT License.
Full notice: Resources/DroneDock/TablerIcons-LICENSE.txt -->
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000000" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round">
<path d="M3.707 6.293l2.586 -2.586a1 1 0 0 1 1.414 0l5.586 5.586a1 1 0 0 1 0 1.414l-2.586 2.586a1 1 0 0 1 -1.414 0l-5.586 -5.586a1 1 0 0 1 0 -1.414"/>
<path d="M6 10l-3 3l3 3l3 -3"/>
<path d="M10 6l3 -3l3 3l-3 3"/>
<path d="M12 12l1.5 1.5"/>
<path d="M14.5 17a2.5 2.5 0 0 0 2.5 -2.5"/>
<path d="M15 21a6 6 0 0 0 6 -6"/>
</svg>

After

Width:  |  Height:  |  Size: 715 B

@@ -0,0 +1,29 @@
import Foundation
/// 机巢首页只读数据源;通过主 Actor 的统一客户端读取,不提供飞行控制能力。
protocol DroneDockHomeServing: Sendable {
/// 获取指定景区、门店的首页快照。
@MainActor
func home(scenicID: Int, storeID: Int) async throws -> DroneDockHomeResponse
}
/// 朱工提供的机巢首页接口;身份由统一网络客户端注入。
@MainActor
final class DroneDockAPI: DroneDockHomeServing {
private let client: APIClient
/// 注入统一网络客户端,供正式页面及网络测试使用。
init(client: APIClient) { self.client = client }
/// 获取当前景区、门店的工作台首页,不创建订单或飞行任务。
func home(scenicID: Int, storeID: Int) async throws -> DroneDockHomeResponse {
guard scenicID > 0, storeID > 0 else {
throw APIError.networkFailed("请先选择景区和门店")
}
return try await client.send(APIRequest(
method: .get, path: "/api/app/airport/home",
queryItems: [URLQueryItem(name: "scenic_id", value: String(scenicID)),
URLQueryItem(name: "store_id", value: String(storeID))]
))
}
}
@@ -0,0 +1,231 @@
import Foundation
/// 朱工首页接口的已验证结构;数组缺失或类型异常视为解析错误,不伪装成空列表。
struct DroneDockHomeResponse: Decodable, Equatable, Sendable {
/// 服务端返回的数据所属景区。
let scenicID: Int
/// 当前景区的机巢设备,按真实非空响应的字段读取。
let airports: [DroneDockHomeAirport]
/// 订单原始记录;不将未知字段猜测成演示订单。
let orders: [DroneDockHomeRecord]
/// 今日数据缺失时保留未知,不生成零值统计。
let today: DroneDockHomeToday?
/// 已验证的首页顶层字段名。
private enum CodingKeys: String, CodingKey {
case scenicID = "scenic_id"
case airports, orders, today
}
/// 严格读取首页骨架,兼容服务端使用整数或整数字符串表示景区 ID。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
scenicID = try container.decode(DroneDockHomeInteger.self, forKey: .scenicID).value
guard scenicID > 0 else {
throw DecodingError.dataCorruptedError(forKey: .scenicID, in: container, debugDescription: "景区 ID 必须为正整数")
}
airports = try container.decode([DroneDockHomeAirport].self, forKey: .airports)
guard Set(airports.map(\.id)).count == airports.count else {
throw DecodingError.dataCorruptedError(forKey: .airports, in: container, debugDescription: "设备 ID 重复,无法确定设备身份")
}
orders = try container.decode([DroneDockHomeRecord].self, forKey: .orders)
today = try container.decodeIfPresent(DroneDockHomeToday.self, forKey: .today)
}
}
/// 首页设备卡的数据,只表达后端展示信息,不推导起飞或拍摄许可。
struct DroneDockHomeAirport: Decodable, Equatable, Sendable {
/// 后端设备稳定 ID,用于 Diffable 项身份。
let id: Int
/// 后端设备名称。
let name: String
/// 后端设备序列号,不将它与尚未确认的飞控参数混用。
let snNumber: String?
/// 后端设备所属景区 ID。
let scenicAreaID: Int?
/// 原始在线状态;尚未取得完整枚举约定。
let onlineStatus: Int?
/// 原始工作状态;不据此决定设备可否执行任务。
let workStatus: Int?
/// 后端工作状态展示文案。
let workStatusLabel: String?
/// 原始接单配置;不等同于本次起飞许可。
let isReceiveOrder: Int?
/// 任务类型原始值;当前样本为 null,暂不假定其枚举或值类型。
let taskType: DroneDockHomeJSONValue?
/// 后端读数列表,展示时按稳定 key 匹配,不依赖返回顺序。
let metrics: [DroneDockHomeMetric]
/// 已实测的设备字段名。
private enum CodingKeys: String, CodingKey {
case id, name, metrics
case snNumber = "sn_number"
case scenicAreaID = "scenic_area_id"
case onlineStatus = "online_status"
case workStatus = "work_status"
case workStatusLabel = "work_status_label"
case isReceiveOrder = "is_receive_order"
case taskType = "task_type"
}
/// 读取实际设备结构;身份缺失时报错,缺失遥测保持未知。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(DroneDockHomeInteger.self, forKey: .id).value
guard id > 0 else {
throw DecodingError.dataCorruptedError(forKey: .id, in: container, debugDescription: "设备 ID 必须为正整数")
}
name = try container.decode(String.self, forKey: .name)
snNumber = try container.decodeIfPresent(String.self, forKey: .snNumber)
scenicAreaID = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .scenicAreaID)?.value
onlineStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .onlineStatus)?.value
workStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .workStatus)?.value
workStatusLabel = try container.decodeIfPresent(String.self, forKey: .workStatusLabel)
isReceiveOrder = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .isReceiveOrder)?.value
taskType = try container.decodeIfPresent(DroneDockHomeJSONValue.self, forKey: .taskType)
metrics = try container.decodeIfPresent([DroneDockHomeMetric].self, forKey: .metrics) ?? []
}
/// 状态标签使用后端文案;缺失、空白或占位文案不显示成空闲。
var statusTitle: String { DroneDockHomeMetric.usableText(workStatusLabel) ?? "状态待确认" }
/// 只映射已验证的空闲状态样本,其余保持中性色,不新增业务状态推断。
var statusTone: DroneDockStatusTone { workStatus == 1 && statusTitle == "空闲" ? .green : .gray }
/// 返回指定读数的后端展示值,保留单位;未知值不从 raw 猜测生成。
func metricText(for key: String) -> String {
metrics.first { $0.key == key }?.displayText ?? "—"
}
/// 仅在电量原始值为 0~100 的真实数字时绘制环形进度,零电量与未知分开。
var batteryProgress: Double? {
guard let metric = metrics.first(where: { $0.key == "battery" }),
case let .number(value)? = metric.raw, value >= 0, value <= 100 else { return nil }
return NSDecimalNumber(decimal: value).doubleValue / 100
}
}
/// 首页单项设备读数,区分可展示的后端文案和未经解释的原始值。
struct DroneDockHomeMetric: Decodable, Equatable, Sendable {
/// 后端读数稳定键,如 battery、env_temp。
let key: String
/// 后端读数名称。
let label: String?
/// 后端原始读数;除合法数值电量环外不据此推测单位或设备许可。
let raw: DroneDockHomeJSONValue?
/// 后端格式化展示值。
let value: String?
/// 统一未知占位,但保留有效零值及服务端单位。
var displayText: String { Self.usableText(value) ?? "—" }
/// 将空白和仅由破折号组成的占位文案判为未知。
static func usableText(_ value: String?) -> String? {
guard let value else { return nil }
let text = value.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty, !text.allSatisfy({ "-–—−― ".contains($0) }) else { return nil }
return text
}
}
/// 首页今日统计;保留服务端字段语义,未知项不显示为零。
struct DroneDockHomeToday: Decodable, Equatable, Sendable {
/// 服务端的今日订单数量。
let orderCount: Int?
/// 服务端的今日订单金额,使用十进制金额避免二进制浮点误差。
let orderAmount: Decimal?
/// 服务端 finished_shoot 数值,其业务统计口径仍需与后端核对。
let finishedShoot: Int?
/// 已验证的统计字段名。
private enum CodingKeys: String, CodingKey {
case orderCount = "order_count"
case orderAmount = "order_amount"
case finishedShoot = "finished_shoot"
}
/// 兼容数字和数字字符串;缺失或 null 保持 nil,非法文本拒绝解析。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderCount = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .orderCount)?.value
orderAmount = try container.decodeIfPresent(DroneDockHomeDecimal.self, forKey: .orderAmount)?.value
finishedShoot = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .finishedShoot)?.value
}
}
/// 尚未取得真实样本的订单行,保留对象字段供后续精确接入和诊断。
struct DroneDockHomeRecord: Decodable, Equatable, Sendable {
/// 原始对象键值,不猜测订单状态或拍摄次数的字段别名。
let fields: [String: DroneDockHomeJSONValue]
/// 只接受 JSON 对象作为列表记录,拒绝 null、标量和嵌套数组。
init(from decoder: Decoder) throws {
fields = try decoder.singleValueContainer().decode([String: DroneDockHomeJSONValue].self)
}
}
/// 保留未知记录的 JSON 结构;数字采用 Decimal,不参与未确认业务计算。
indirect enum DroneDockHomeJSONValue: Decodable, Equatable, Sendable {
/// JSON 对象。
case object([String: DroneDockHomeJSONValue])
/// JSON 数组。
case array([DroneDockHomeJSONValue])
/// JSON 字符串。
case string(String)
/// JSON 数字。
case number(Decimal)
/// JSON 布尔值。
case bool(Bool)
/// JSON 空值。
case null
/// 按 JSON 实际类型解码,不把字符串自动转换为其他类型。
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() { self = .null }
else if let value = try? container.decode(Bool.self) { self = .bool(value) }
else if let value = try? container.decode(String.self) { self = .string(value) }
else if let value = try? container.decode(Decimal.self) { self = .number(value) }
else if let value = try? container.decode([String: DroneDockHomeJSONValue].self) { self = .object(value) }
else { self = .array(try container.decode([DroneDockHomeJSONValue].self)) }
}
}
/// 已知整数统计字段的严格兼容解码器。
private struct DroneDockHomeInteger: 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: "需要整数或整数字符串")
}
}
}
/// 已知金额字段的十进制兼容解码器,拒绝只含部分合法数字的字符串。
private struct DroneDockHomeDecimal: Decodable {
let value: Decimal
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let text = try? container.decode(String.self) {
let normalized = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard normalized.range(of: #"^-?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$"#, options: .regularExpression) != nil,
let number = Decimal(string: normalized, locale: Locale(identifier: "en_US_POSIX")),
!number.isNaN else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "金额必须为有效十进制数")
}
value = number
} else {
value = try container.decode(Decimal.self)
guard !value.isNaN else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "金额必须为有效十进制数")
}
}
}
}
@@ -0,0 +1,120 @@
import Foundation
/// 一次真实首页请求的账号、景区和门店范围;凭证只参与隔离,不对外提供展示。
struct DroneDockHomeContext: Equatable, Sendable {
/// 当前登录工作人员的稳定 ID。
let userID: String
/// 当前账号类型,用于区分相同 ID 的不同账号域。
let accountType: String
/// 当前景区 ID。
let scenicID: Int
/// 当前景区名称。
let scenicName: String
/// 当前景区下的门店 ID。
let storeID: Int
/// 当前工作人员展示名称。
let photographerName: String
private let token: String
/// 冻结请求范围及登录凭证,仅用于与最新会话比较。
init(userID: String, accountType: String, scenicID: Int, scenicName: String,
storeID: Int, photographerName: String, token: String) {
self.userID = userID
self.accountType = accountType
self.scenicID = scenicID
self.scenicName = scenicName
self.storeID = storeID
self.photographerName = photographerName
self.token = token.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// 是否具备查询当前首页所需的登录及景区、门店上下文。
var canLoad: Bool { !userID.isEmpty && !token.isEmpty && scenicID > 0 && storeID > 0 }
/// 判断响应是否仍属于当前会话,包含登录 Token 更新但忽略展示名称变化。
func hasSameIdentity(as other: DroneDockHomeContext) -> Bool {
userID == other.userID && accountType == other.accountType && scenicID == other.scenicID
&& storeID == other.storeID && token == other.token
}
}
/// 真实机巢首页的独立读取状态;不使用演示订单、演示设备或本地拍摄任务。
final class DroneDockHomeViewModel {
/// 当前页面所属的真实账号、景区和门店。
private(set) var context: DroneDockHomeContext
/// 最近一次成功读取的当前范围首页;加载失败或身份变更时清除。
private(set) var response: DroneDockHomeResponse?
/// 当前最新一次请求是否尚未结束。
private(set) var isLoading = false
/// 当前请求的可展示错误;与成功空列表分开表达。
private(set) var errorMessage: String?
private let service: any DroneDockHomeServing
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
/// 注入读取服务与最新会话提供器,调用方在刷新完成后主动更新界面。
init(context: DroneDockHomeContext, service: any DroneDockHomeServing,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.service = service
self.currentContext = currentContext
}
/// 刷新真实首页;拒绝旧请求、旧登录凭证、旧景区及旧门店的迟到结果。
func refresh() async {
generation &+= 1
let requestGeneration = generation
isLoading = true
errorMessage = nil
defer { if generation == requestGeneration { isLoading = false } }
let requestedContext = await currentContext()
guard generation == requestGeneration, !Task.isCancelled else { return }
if !context.hasSameIdentity(as: requestedContext) { response = nil }
context = requestedContext
guard requestedContext.canLoad else {
response = nil
isLoading = false
errorMessage = "请先登录并选择景区和门店"
return
}
do {
let result = try await service.home(scenicID: requestedContext.scenicID, storeID: requestedContext.storeID)
guard await accepts(requestGeneration, context: requestedContext) else { return }
guard result.scenicID == requestedContext.scenicID else {
response = nil
errorMessage = "接口返回的景区与当前景区不一致,请刷新重试"
return
}
response = result
} catch {
guard await accepts(requestGeneration, context: requestedContext) else { return }
response = nil
if error is CancellationError { return }
errorMessage = error.localizedDescription
}
}
/// 离开或取消当前读取时使所有在途结果失效;再次刷新仍可重新加载。
func invalidate() {
generation &+= 1
response = nil
errorMessage = nil
isLoading = false
}
private func accepts(_ requestGeneration: Int, context requested: DroneDockHomeContext) async -> Bool {
guard generation == requestGeneration, !Task.isCancelled else { return false }
let latest = await currentContext()
guard generation == requestGeneration, !Task.isCancelled else { return false }
guard requested.hasSameIdentity(as: latest) else {
generation &+= 1
context = latest
response = nil
isLoading = false
errorMessage = "账号或景区已变化,请刷新工作台"
return false
}
return true
}
}
@@ -69,7 +69,7 @@ enum HomeRouteHandler {
case "/scenic-queue":
viewController.navigationController?.pushViewController(ScenicQueueViewController(), animated: true)
case "drone_dock":
viewController.navigationController?.pushViewController(DroneDockWorkbenchViewController(), animated: true)
viewController.navigationController?.pushViewController(DroneDockHomeViewController(), animated: true)
case "task_management", "task_management_editor":
viewController.navigationController?.pushViewController(TaskAddViewController(), animated: true)
case "travel_album":
@@ -0,0 +1,25 @@
Tabler Icons — satellite
Source: https://github.com/tabler/tabler-icons
Used by the device card to match https://voicestudio.suixinkan.cn/.
MIT License
Copyright (c) 2020-2026 Paweł Kuna
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -4,7 +4,7 @@ import UIKit
/// 设备遥测卡:只展示设备状态,横向浏览不会选择执行拍摄的无人机。
final class DroneDockDeviceCardView: UIView {
private let nameLabel = DroneDockStyle.label(size: 15, weight: .semibold)
private let statusLabel = DroneDockStatusLabel()
private let statusLabel = DroneDockDeviceStatusView()
private let batteryView = DroneDockBatteryView()
private let signalValue = DroneDockStyle.label(size: 19, weight: .semibold)
private let satelliteValue = DroneDockStyle.label(size: 19, weight: .semibold)
@@ -40,7 +40,26 @@ final class DroneDockDeviceCardView: UIView {
accessibilityLabel = "\(device.name),\(device.state.title)"
}
/// 展示 home 返回的机巢名称、工作状态及格式化读数,不根据展示状态推断起飞许可。
func apply(airport: DroneDockHomeAirport) {
nameLabel.text = airport.name
statusLabel.apply(title: airport.statusTitle, tone: airport.statusTone)
batteryView.apply(text: airport.metricText(for: "battery"), progress: airport.batteryProgress)
temperatureValue.text = airport.metricText(for: "env_temp")
windValue.text = airport.metricText(for: "wind_speed")
rainValue.text = airport.metricText(for: "rainfall")
signalValue.text = airport.metricText(for: "signal")
satelliteValue.text = airport.metricText(for: "satellite")
accessibilityIdentifier = "drone.device.\(airport.id)"
accessibilityLabel = "\(airport.name),\(airport.statusTitle)"
}
private func setupUI() {
temperatureValue.accessibilityIdentifier = "drone.metric.env_temp"
windValue.accessibilityIdentifier = "drone.metric.wind_speed"
rainValue.accessibilityIdentifier = "drone.metric.rainfall"
signalValue.accessibilityIdentifier = "drone.metric.signal"
satelliteValue.accessibilityIdentifier = "drone.metric.satellite"
[nameLabel, statusLabel, batteryView].forEach(addSubview)
nameLabel.snp.makeConstraints { make in
make.top.leading.equalToSuperview().inset(16)
@@ -57,7 +76,7 @@ final class DroneDockDeviceCardView: UIView {
}
let signal = telemetryRow(symbol: "antenna.radiowaves.left.and.right", title: "信号状态", value: signalValue)
let satellites = telemetryRow(symbol: "sparkles", title: "搜星状态", value: satelliteValue)
let satellites = telemetryRow(image: UIImage(named: "drone_telemetry_satellite"), title: "搜星状态", value: satelliteValue)
let radioStack = UIStackView(arrangedSubviews: [signal, satellites])
radioStack.axis = .vertical
radioStack.distribution = .fillEqually
@@ -77,11 +96,12 @@ final class DroneDockDeviceCardView: UIView {
make.leading.trailing.equalToSuperview().inset(16)
make.height.equalTo(0.5)
}
let metrics = UIStackView(arrangedSubviews: [
let metricColumns = [
metric(value: temperatureValue, symbol: "thermometer.medium", title: "环境温度"),
metric(value: windValue, symbol: "wind", title: "风速"),
metric(value: rainValue, symbol: "cloud", title: "雨量")
])
metric(value: rainValue, symbol: "cloud.rain", title: "雨量")
]
let metrics = UIStackView(arrangedSubviews: metricColumns)
metrics.axis = .horizontal
metrics.distribution = .fillEqually
addSubview(metrics)
@@ -90,10 +110,24 @@ final class DroneDockDeviceCardView: UIView {
make.leading.trailing.equalToSuperview().inset(12)
make.bottom.equalToSuperview().inset(14)
}
for column in metricColumns.dropFirst() {
let separator = UIView()
separator.backgroundColor = DroneDockStyle.border
metrics.addSubview(separator)
separator.snp.makeConstraints { make in
make.leading.equalTo(column.snp.leading)
make.top.bottom.equalToSuperview()
make.width.equalTo(0.5)
}
}
}
private func telemetryRow(symbol: String, title: String, value: UILabel) -> UIView {
let icon = UIImageView(image: UIImage(systemName: symbol))
telemetryRow(image: UIImage(systemName: symbol), title: title, value: value)
}
private func telemetryRow(image: UIImage?, title: String, value: UILabel) -> UIView {
let icon = UIImageView(image: image?.withRenderingMode(.alwaysTemplate))
icon.tintColor = DroneDockStyle.secondary
icon.contentMode = .scaleAspectFit
let label = DroneDockStyle.label(title, size: 11, color: DroneDockStyle.secondary)
@@ -128,6 +162,39 @@ final class DroneDockDeviceCardView: UIView {
}
}
/// 设备专用状态标签,圆点与文字共用语义颜色,不改变其他业务标签。
private final class DroneDockDeviceStatusView: UIView {
private let dot = UIView()
private let titleLabel = DroneDockStyle.label(size: 11, weight: .medium)
override init(frame: CGRect) {
super.init(frame: frame)
layer.cornerRadius = 6
dot.layer.cornerRadius = 3
dot.snp.makeConstraints { $0.size.equalTo(6) }
let content = UIStackView(arrangedSubviews: [dot, titleLabel])
content.axis = .horizontal
content.alignment = .center
content.spacing = 5
addSubview(content)
content.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 4, left: 7, bottom: 4, right: 7)) }
titleLabel.setContentHuggingPriority(.required, for: .horizontal)
titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 圆点、文字及浅色背景同步更新,复用时不残留上一设备的状态色。
func apply(title: String, tone: DroneDockStatusTone) {
let color = DroneDockStyle.color(for: tone)
titleLabel.text = title
titleLabel.textColor = color
dot.backgroundColor = color
backgroundColor = color.withAlphaComponent(0.09)
}
}
/// 环形电量组件,未知电量只显示轨道和占位读数。
private final class DroneDockBatteryView: UIView {
private let track = CAShapeLayer()
@@ -136,6 +203,7 @@ private final class DroneDockBatteryView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
valueLabel.accessibilityIdentifier = "drone.metric.battery"
for layer in [track, progress] {
layer.fillColor = UIColor.clear.cgColor
layer.lineWidth = 7
@@ -165,9 +233,14 @@ private final class DroneDockBatteryView: UIView {
}
func apply(telemetry: DroneDockTelemetry) {
valueLabel.text = telemetry.batteryText
progress.strokeEnd = telemetry.batteryProgress ?? 0
accessibilityLabel = "电池电量 \(telemetry.batteryText)"
apply(text: telemetry.batteryText, progress: telemetry.batteryProgress)
}
/// 有效电量才绘制进度;未知值只保留环形轨道与破折号。
func apply(text: String, progress value: Double?) {
valueLabel.text = text
progress.strokeEnd = value.map { CGFloat(min(1, max(0, $0))) } ?? 0
accessibilityLabel = "电池电量 \(text)"
isAccessibilityElement = true
}
}
@@ -0,0 +1,375 @@
import SnapKit
import UIKit
/// 正式机巢首页,仅展示 airport/home 的真实快照,不进入本地演示业务。
final class DroneDockHomeViewController: BaseViewController {
/// 与演示数据源隔离的首页状态。
let viewModel: DroneDockHomeViewModel
private var refreshTask: Task<Void, Never>?
private var isRefreshing = false
private var devicePage = 0
private let pageControl = UIPageControl()
/// 首页固定分区;设备与订单的数据结构以实际联调结果为准。
private enum Section: Int, CaseIterable { case context, devices, orders, statistics }
/// 稳定身份确保刷新使用 Diffable 更新。
private enum Item: Hashable { case context, devices, device(Int), orders, statistics }
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
/// 使用当前登录身份及选择的景区、门店构造正式首页。
convenience init() {
self.init(viewModel: DroneDockHomeViewModel(
context: Self.currentContext(),
service: DroneDockAPI(client: NetworkServices.shared.apiClient),
currentContext: { Self.currentContext() }
))
}
/// 注入可测试的数据源,不加载演示数据。
init(viewModel: DroneDockHomeViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit { refreshTask?.cancel() }
override func setupNavigationBar() {
title = "机巢工作台"
let button = UIBarButtonItem(title: "收款码", image: UIImage(systemName: "qrcode"),
target: self, action: #selector(receiptTapped))
button.accessibilityIdentifier = "drone.home.receipt"
navigationItem.rightBarButtonItem = button
navigationItem.backButtonDisplayMode = .minimal
}
override func setupUI() {
view.backgroundColor = DroneDockStyle.background
collectionView.backgroundColor = .clear
collectionView.alwaysBounceVertical = true
collectionView.accessibilityIdentifier = "drone.home.remote.list"
collectionView.register(DroneDockHomeContentCell.self, forCellWithReuseIdentifier: "content")
collectionView.register(DroneDockDeviceCell.self, forCellWithReuseIdentifier: "device")
collectionView.register(DroneDockHomeHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "header")
collectionView.register(DroneDockHomePageFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
withReuseIdentifier: "pages")
pageControl.currentPageIndicatorTintColor = DroneDockStyle.primary
pageControl.pageIndicatorTintColor = DroneDockStyle.border
pageControl.isUserInteractionEnabled = false
pageControl.accessibilityIdentifier = "drone.home.devicePages"
let refresh = UIRefreshControl()
refresh.tintColor = DroneDockStyle.primary
refresh.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
collectionView.refreshControl = refresh
view.addSubview(collectionView)
configureDataSource()
applySnapshot(animated: false)
}
override func setupConstraints() {
collectionView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.bottom.equalToSuperview()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshHome()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
refreshTask?.cancel()
isRefreshing = false
viewModel.invalidate()
}
private func refreshHome() {
refreshTask?.cancel()
isRefreshing = true
refreshTask = Task { @MainActor [weak self] in
guard let self else { return }
self.applySnapshot(animated: false)
await self.viewModel.refresh()
guard !Task.isCancelled else { return }
self.isRefreshing = false
self.collectionView.refreshControl?.endRefreshing()
self.applySnapshot(animated: true) { [weak self] in
#if DEBUG
Task { @MainActor [weak self] in await self?.captureHomeIfRequested() }
#endif
}
}
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] collection, path, item in
guard let self else { return nil }
if case .device(let id) = item {
let cell = collection.dequeueReusableCell(withReuseIdentifier: "device", for: path) as! DroneDockDeviceCell
if let airport = self.viewModel.response?.airports.first(where: { $0.id == id }) {
cell.cardView.apply(airport: airport)
}
return cell
}
let cell = collection.dequeueReusableCell(withReuseIdentifier: "content", for: path) as! DroneDockHomeContentCell
switch item {
case .context:
let context = self.viewModel.context
let title = [context.scenicName, context.photographerName].filter { !$0.isEmpty }.joined(separator: " · ")
cell.applyContext(title.isEmpty ? "机巢工作台" : title)
case .statistics:
cell.applyStatistics(self.viewModel.response?.today)
case .devices, .orders:
self.applyDataState(to: cell, isDevice: item == .devices)
case .device: break
}
return cell
}
dataSource.supplementaryViewProvider = { [weak self] collection, kind, path in
guard let self else { return nil }
if kind == UICollectionView.elementKindSectionFooter {
let footer = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "pages", for: path) as! DroneDockHomePageFooter
footer.install(self.pageControl)
return footer
}
let header = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: path) as! DroneDockHomeHeader
let isOrders = Section(rawValue: path.section) == .orders
header.apply(title: isOrders ? "我的拍摄订单" : "今日统计", showsAction: isOrders)
header.onViewAll = { [weak self] in self?.showUnavailable("拍摄订单") }
return header
}
}
private func applyDataState(to cell: DroneDockHomeContentCell, isDevice: Bool) {
if isRefreshing, viewModel.response == nil {
cell.applyMessage(symbol: "arrow.triangle.2.circlepath", title: "正在加载", detail: "正在获取最新数据")
return
}
if let error = viewModel.errorMessage {
cell.applyMessage(symbol: "wifi.exclamationmark", title: "首页加载失败", detail: error + ",请下拉重试")
return
}
guard let response = viewModel.response else {
cell.applyMessage(symbol: "arrow.triangle.2.circlepath", title: "正在加载", detail: "正在获取最新数据")
return
}
let recordCount = isDevice ? response.airports.count : response.orders.count
if recordCount == 0 {
cell.applyMessage(symbol: isDevice ? "airplane" : "doc.text",
title: isDevice ? "暂无无人机" : "暂无待拍摄订单",
detail: isDevice ? "当前景区暂无设备数据" : "当前景区暂无拍摄订单数据")
} else {
// 订单仍等待真实非空样例,不影响已接入的设备卡片。
cell.applyMessage(symbol: "exclamationmark.circle", title: "订单信息暂不可用",
detail: "已获取 \(recordCount) 条数据,暂时无法展示详情")
}
}
private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) {
guard dataSource != nil else { return }
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections(Section.allCases)
snapshot.appendItems([.context], toSection: .context)
let airports = viewModel.response?.airports ?? []
snapshot.appendItems(airports.isEmpty ? [.devices] : airports.map { .device($0.id) }, toSection: .devices)
snapshot.appendItems([.orders], toSection: .orders)
snapshot.appendItems([.statistics], toSection: .statistics)
let old = Set(dataSource.snapshot().itemIdentifiers)
let previousDeviceCount = old.filter { if case .device = $0 { return true }; return false }.count
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { old.contains($0) })
devicePage = min(devicePage, max(0, airports.count - 1))
pageControl.numberOfPages = airports.count
pageControl.currentPage = devicePage
if previousDeviceCount != airports.count {
collectionView.setCollectionViewLayout(makeLayout(), animated: false)
}
dataSource.apply(snapshot, animatingDifferences: animated, completion: completion)
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, environment in
guard let section = Section(rawValue: index) else { return nil }
let deviceCount = self?.viewModel.response?.airports.count ?? 0
let hasDevices = section == .devices && deviceCount > 0
let multipleDevices = section == .devices && deviceCount > 1
let height: NSCollectionLayoutDimension = hasDevices ? .absolute(248) : section == .context ? .estimated(40) : .estimated(132)
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
let width: NSCollectionLayoutDimension = multipleDevices ? .absolute(environment.container.effectiveContentSize.width - 48) : .fractionalWidth(1)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
let layout = NSCollectionLayoutSection(group: group)
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: section == .statistics ? 24 : 0, trailing: 16)
if multipleDevices {
layout.interGroupSpacing = 12
layout.orthogonalScrollingBehavior = .groupPaging
layout.visibleItemsInvalidationHandler = { [weak self] _, offset, _ in
guard let self else { return }
let step = max(1, environment.container.effectiveContentSize.width - 36)
let page = min(deviceCount - 1, max(0, Int((offset.x / step).rounded())))
self.devicePage = page
self.pageControl.currentPage = page
}
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(24)),
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom)]
}
if section == .orders || section == .statistics {
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(54)),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
}
return layout
}
}
private func showUnavailable(_ feature: String) {
showAlert(title: feature, message: "该功能暂未开放")
}
@objc private func receiptTapped() { showUnavailable("套餐收款") }
@objc private func refreshTriggered() { refreshHome() }
#if DEBUG
/// 显式联调参数下只保存本应用窗口,不截取用户切换后的其他 App。
private func captureHomeIfRequested() async {
guard ProcessInfo.processInfo.arguments.contains("--dock-home-capture") else { return }
// Diffable 完成回调仍可能处于旧卡片的移除事务内,等下一轮屏幕提交后再取图。
try? await Task.sleep(nanoseconds: 400_000_000)
guard !Task.isCancelled, !isRefreshing, let window = view.window else { return }
window.layoutIfNeeded()
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
}
do {
let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
.appendingPathComponent("AirportHomeDiagnostics", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
try image.pngData()?.write(to: directory.appendingPathComponent("airport-home-real.png"), options: .atomic)
print("[AirportHome] App window screenshot saved")
} catch { print("[AirportHome] Screenshot failed: \(error.localizedDescription)") }
}
#endif
/// 只从现有会话读取身份,不修改登录状态或当前选择。
private static func currentContext() -> DroneDockHomeContext {
let session = AppStore.shared.session
return DroneDockHomeContext(userID: session.userId, accountType: session.accountType.rawValue,
scenicID: session.currentScenicId, scenicName: session.currentScenicName,
storeID: session.currentStoreId, photographerName: session.userName, token: session.token)
}
}
/// 多设备横向轮播的页码容器。
private final class DroneDockHomePageFooter: UICollectionReusableView {
/// 安装首页维护的页码控件,避免复用时重复添加。
func install(_ control: UIPageControl) {
guard control.superview !== self else { return }
control.removeFromSuperview()
addSubview(control)
control.snp.makeConstraints { make in
make.center.equalToSuperview()
make.height.equalTo(24)
}
}
}
/// 真实首页的空态、加载状态及统计展示。
private final class DroneDockHomeContentCell: UICollectionViewCell {
private var embeddedView: UIView?
/// 展示当前身份与景区。
func applyContext(_ text: String) {
let label = DroneDockStyle.label(text, size: 12, color: DroneDockStyle.secondary)
label.numberOfLines = 2
install(label, insets: UIEdgeInsets(top: 6, left: 0, bottom: 12, right: 0), card: false)
}
/// 展示明确空态或错误,避免将接口失败解释为没有订单。
func applyMessage(symbol: String, title: String, detail: String) {
let image = UIImageView(image: UIImage(systemName: symbol))
image.tintColor = DroneDockStyle.secondary.withAlphaComponent(0.6)
image.contentMode = .scaleAspectFit
image.snp.makeConstraints { $0.size.equalTo(28) }
let titleLabel = DroneDockStyle.label(title, size: 14, weight: .medium)
let detailLabel = DroneDockStyle.label(detail, size: 12, color: DroneDockStyle.secondary)
detailLabel.numberOfLines = 0
detailLabel.textAlignment = .center
let stack = UIStackView(arrangedSubviews: [image, titleLabel, detailLabel])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 9
install(stack, insets: UIEdgeInsets(top: 22, left: 16, bottom: 22, right: 16), card: true)
}
/// 使用服务端 today 字段;缺失数据保持未知,不显示为零。
func applyStatistics(_ today: DroneDockHomeToday?) {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "zh_CN")
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let amount = today?.orderAmount.flatMap { formatter.string(from: NSDecimalNumber(decimal: $0)) }.map { "¥" + $0 } ?? "—"
let values = [(today?.orderCount.map(String.init) ?? "—", "成交订单"),
(amount, "成交金额"), (today?.finishedShoot.map(String.init) ?? "—", "完成拍摄")]
let columns = values.map { value, title in
let label = DroneDockStyle.label(value, size: 23, weight: .semibold)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.6
let stack = UIStackView(arrangedSubviews: [label, DroneDockStyle.label(title, size: 12, color: DroneDockStyle.secondary)])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 9
return stack
}
let stack = UIStackView(arrangedSubviews: columns)
stack.distribution = .fillEqually
install(stack, insets: UIEdgeInsets(top: 23, left: 10, bottom: 23, right: 10), card: true)
}
private func install(_ view: UIView, insets: UIEdgeInsets, card: Bool) {
embeddedView?.removeFromSuperview()
embeddedView = view
if card { DroneDockStyle.applyCard(to: contentView) } else { contentView.backgroundColor = .clear }
contentView.addSubview(view)
view.snp.makeConstraints { $0.edges.equalToSuperview().inset(insets) }
}
}
/// 首页分区标题与后续订单列表入口。
private final class DroneDockHomeHeader: UICollectionReusableView {
/// 用户请求查看完整订单列表。
var onViewAll: (() -> Void)?
private let label = DroneDockStyle.label(size: 17, weight: .semibold)
private let button = UIButton(type: .system)
override init(frame: CGRect) {
super.init(frame: frame)
button.setTitle("查看全部 ›", for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 13)
button.tintColor = DroneDockStyle.primary
button.accessibilityIdentifier = "drone.home.allOrders"
button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
button.snp.makeConstraints { $0.height.equalTo(44) }
let stack = UIStackView(arrangedSubviews: [label, UIView(), button])
stack.alignment = .center
addSubview(stack)
stack.snp.makeConstraints { $0.leading.trailing.centerY.equalToSuperview() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 刷新区块标题和入口可见性。
func apply(title: String, showsAction: Bool) {
label.text = title
button.isHidden = !showsAction
}
@objc private func tapped() { onViewAll?() }
}
@@ -1,11 +1,14 @@
import UIKit
#if DEBUG
/// 独立的本地预览入口,不伪造登录、权限或真实业务数据。
/// Debug 页面入口:本地演示与使用当前登录身份的真实首页联调分别进入。
@MainActor
enum DroneDockPreview {
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
static func navigationController(arguments: [String]) -> UINavigationController? {
if arguments.contains("--dock-home-live"), AppStore.shared.session.isLoggedIn {
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"]
guard arguments.contains(where: { entryFlags.contains($0) }) else { return nil }
let store = DroneDockDemoStore()