feat(drone-dock): 拆分首页设备订单与统计接口
This commit is contained in:
@@ -1,29 +1,68 @@
|
||||
import Foundation
|
||||
|
||||
/// 机巢首页只读数据源;通过主 Actor 的统一客户端读取,不提供飞行控制能力。
|
||||
/// 首页三个独立只读数据源;设备由朱工提供,订单与统计由张工提供。
|
||||
protocol DroneDockHomeServing: Sendable {
|
||||
/// 获取指定景区、门店的首页快照。
|
||||
/// 读取当前景区的机巢摘要;门店用于验证本地身份,不作为查询参数。
|
||||
@MainActor
|
||||
func home(scenicID: Int, storeID: Int) async throws -> DroneDockHomeResponse
|
||||
/// 分页读取本人当前景区的全部类型 25 拍摄订单。
|
||||
@MainActor
|
||||
func orders(scenicID: Int, page: Int, pageSize: Int) async throws -> DroneDockOrdersResponse
|
||||
/// 读取本人当前景区当天的成交和确认完成统计。
|
||||
@MainActor
|
||||
func todayStats(scenicID: Int) async throws -> DroneDockHomeToday
|
||||
}
|
||||
|
||||
/// 朱工提供的机巢首页接口;身份由统一网络客户端注入。
|
||||
/// 机巢首页三接口适配,复用统一凭证及业务错误处理,不创建订单或飞行任务。
|
||||
@MainActor
|
||||
final class DroneDockAPI: DroneDockHomeServing {
|
||||
private let client: APIClient
|
||||
private let orderPrefix = "/api/yf-handset-app/photog/multi-plane"
|
||||
|
||||
/// 注入统一网络客户端,供正式页面及网络测试使用。
|
||||
init(client: APIClient) { self.client = client }
|
||||
|
||||
/// 获取当前景区、门店的工作台首页,不创建订单或飞行任务。
|
||||
/// 朱工 home 只传 scenic_id,响应仅用于设备区域。
|
||||
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))]
|
||||
queryItems: [URLQueryItem(name: "scenic_id", value: String(scenicID))]
|
||||
))
|
||||
}
|
||||
|
||||
/// 张工 orders 由当前登录身份限定归属,不传其他摄影师或门店 ID。
|
||||
func orders(scenicID: Int, page: Int, pageSize: Int) async throws -> DroneDockOrdersResponse {
|
||||
try validateScenic(scenicID)
|
||||
guard page > 0, (1...100).contains(pageSize) else {
|
||||
throw APIError.networkFailed("订单分页参数无效")
|
||||
}
|
||||
let response: DroneDockOrdersResponse = try await client.send(APIRequest(
|
||||
method: .get, path: orderPrefix + "/orders",
|
||||
queryItems: [URLQueryItem(name: "scenic_id", value: String(scenicID)),
|
||||
URLQueryItem(name: "status", value: "all"),
|
||||
URLQueryItem(name: "page", value: String(page)),
|
||||
URLQueryItem(name: "page_size", value: String(pageSize))]
|
||||
))
|
||||
guard response.page == page else {
|
||||
throw APIError.decodeFailed("订单页码与请求不一致")
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
/// 张工 today-stats 负责统计口径与上海时区日界限,客户端不传本地日期。
|
||||
func todayStats(scenicID: Int) async throws -> DroneDockHomeToday {
|
||||
try validateScenic(scenicID)
|
||||
return try await client.send(APIRequest(
|
||||
method: .get, path: orderPrefix + "/today-stats",
|
||||
queryItems: [URLQueryItem(name: "scenic_id", value: String(scenicID))]
|
||||
))
|
||||
}
|
||||
|
||||
/// 没有选择景区时阻止范围不明的请求。
|
||||
private func validateScenic(_ scenicID: Int) throws {
|
||||
guard scenicID > 0 else { throw APIError.networkFailed("请先选择景区") }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,19 @@
|
||||
import Foundation
|
||||
|
||||
/// 朱工首页接口的已验证结构;数组缺失或类型异常视为解析错误,不伪装成空列表。
|
||||
/// 朱工首页接口仅提供设备摘要;订单和统计由张工的独立接口读取。
|
||||
struct DroneDockHomeResponse: Decodable, Equatable, Sendable {
|
||||
/// 服务端返回的数据所属景区。
|
||||
let scenicID: Int
|
||||
/// 当前景区的机巢设备,按真实非空响应的字段读取。
|
||||
/// 当前景区的机巢设备。
|
||||
let airports: [DroneDockHomeAirport]
|
||||
/// 按真实响应字段读取的拍摄订单,保持后端返回顺序。
|
||||
let orders: [DroneDockHomeOrder]
|
||||
/// 今日数据缺失时保留未知,不生成零值统计。
|
||||
let today: DroneDockHomeToday?
|
||||
|
||||
/// 已验证的首页顶层字段名。
|
||||
/// 仅读取设备字段,忽略旧版本响应中的订单及统计。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case scenicID = "scenic_id"
|
||||
case airports, orders, today
|
||||
case airports
|
||||
}
|
||||
|
||||
/// 严格读取首页骨架,兼容服务端使用整数或整数字符串表示景区 ID。
|
||||
/// 严格读取设备数组,拒绝身份缺失或重复的快照。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
scenicID = try container.decode(DroneDockHomeInteger.self, forKey: .scenicID).value
|
||||
@@ -28,11 +24,39 @@ struct DroneDockHomeResponse: Decodable, Equatable, Sendable {
|
||||
guard Set(airports.map(\.id)).count == airports.count else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .airports, in: container, debugDescription: "设备 ID 重复,无法确定设备身份")
|
||||
}
|
||||
orders = try container.decode([DroneDockHomeOrder].self, forKey: .orders)
|
||||
guard Set(orders.map(\.orderID)).count == orders.count else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .orders, in: container, debugDescription: "订单 ID 重复,无法确定订单身份")
|
||||
}
|
||||
}
|
||||
|
||||
/// 张工拍摄订单列表的一页结果;总数不由当前页条数推算。
|
||||
struct DroneDockOrdersResponse: Decodable, Equatable, Sendable {
|
||||
/// 当前页订单,保持后端排序。
|
||||
let list: [DroneDockHomeOrder]
|
||||
/// 当前筛选条件下的订单总数。
|
||||
let total: Int
|
||||
/// 当前响应页码,从 1 开始。
|
||||
let page: Int
|
||||
/// 服务端本次采用的每页数量。
|
||||
let pageSize: Int
|
||||
|
||||
/// 分页响应字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case list, total, page
|
||||
case pageSize = "page_size"
|
||||
}
|
||||
|
||||
/// 校验分页骨架和订单号,避免把失败数据当成空列表。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
list = try container.decode([DroneDockHomeOrder].self, forKey: .list)
|
||||
total = try container.decode(DroneDockHomeInteger.self, forKey: .total).value
|
||||
page = try container.decode(DroneDockHomeInteger.self, forKey: .page).value
|
||||
pageSize = try container.decode(DroneDockHomeInteger.self, forKey: .pageSize).value
|
||||
guard total >= 0, page > 0, (1...100).contains(pageSize), list.count <= pageSize, list.count <= total else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .page, in: container, debugDescription: "订单分页数据无效")
|
||||
}
|
||||
guard Set(list.map(\.orderID)).count == list.count else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .list, in: container, debugDescription: "订单号重复,无法确定订单身份")
|
||||
}
|
||||
today = try container.decodeIfPresent(DroneDockHomeToday.self, forKey: .today)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,148 +155,181 @@ struct DroneDockHomeMetric: Decodable, Equatable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// 首页今日统计;保留服务端字段语义,未知项不显示为零。
|
||||
/// 张工的今日统计;仅覆盖本人当前景区类型 25 订单,按上海时区划分当天。
|
||||
struct DroneDockHomeToday: Decodable, Equatable, Sendable {
|
||||
/// 服务端的今日订单数量。
|
||||
/// 今天付款且当前仍为已付款或已完成的成交订单数。
|
||||
let orderCount: Int?
|
||||
/// 服务端的今日订单金额,使用十进制金额避免二进制浮点误差。
|
||||
/// 成交订单现金实收减成功退款,使用十进制金额。
|
||||
let orderAmount: Decimal?
|
||||
/// 服务端 finished_shoot 数值,其业务统计口径仍需与后端核对。
|
||||
/// 今天经游客确认完成、当前状态为已完成的订单数。
|
||||
let finishedShoot: Int?
|
||||
|
||||
/// 已验证的统计字段名。
|
||||
/// today-stats 的字段,不兼容旧 home 的统计口径。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case orderCount = "order_count"
|
||||
case orderAmount = "order_amount"
|
||||
case finishedShoot = "finished_shoot"
|
||||
case orderCount = "deal_count"
|
||||
case orderAmount = "deal_amount"
|
||||
case finishedShoot = "completed_count"
|
||||
}
|
||||
|
||||
/// 兼容数字和数字字符串;缺失或 null 保持 nil,非法文本拒绝解析。
|
||||
/// 未知项保留 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
|
||||
for (key, value) in [(CodingKeys.orderCount, orderCount), (.finishedShoot, finishedShoot)] {
|
||||
if let value, value < 0 {
|
||||
throw DecodingError.dataCorruptedError(forKey: key, in: container, debugDescription: "统计数量不能为负数")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 首页拍摄订单的展示数据;状态及动作仅用于呈现,不代表飞行执行许可。
|
||||
/// 张工类型 25 订单摘要;操作入口取后端 can_* 权限,进入准备页仍需校验设备条件。
|
||||
struct DroneDockHomeOrder: Decodable, Equatable, Sendable {
|
||||
/// 后端订单稳定 ID,用于 Diffable 项身份。
|
||||
let orderID: Int
|
||||
/// 后端订单编号,保留字符串形式与前导零。
|
||||
/// 订单号同时作为 Diffable 稳定身份,不虚构接口未提供的整数 ID。
|
||||
let orderID: String
|
||||
/// 原始订单号,保留前导零;解码时要求非空。
|
||||
let orderNumber: String?
|
||||
/// 后端游客展示名称。
|
||||
let touristLabel: String?
|
||||
/// 后端已脱敏的游客手机号。
|
||||
/// 已购买项目 ID,传递给后续准备页读取购买快照。
|
||||
let projectID: Int?
|
||||
/// 订单创建时间的服务端字符串。
|
||||
let createdAt: String?
|
||||
/// 后端已经脱敏的游客手机号。
|
||||
let touristPhoneMask: String?
|
||||
/// 后端套餐名称,不据此推断套餐类型或项目 ID。
|
||||
/// 购买时的项目名称。
|
||||
let packageName: String?
|
||||
/// 后端订单状态展示文案。
|
||||
let statusLabel: String?
|
||||
/// 后端拍摄总次数,未知时不默认成零。
|
||||
/// 购买快照中的整单共享总次数。
|
||||
let shotTotal: Int?
|
||||
/// 后端已拍摄次数,不在客户端根据任务状态重新计算。
|
||||
/// 有效且成功的飞行任务数量。
|
||||
let shotUsed: Int?
|
||||
/// 后端剩余拍摄次数,不用总次数减已拍摄次数推断。
|
||||
/// 服务端权威剩余次数,不在客户端重新计算。
|
||||
let shotRemain: Int?
|
||||
/// 后端格式化的拍摄进度文案。
|
||||
let progressText: String?
|
||||
/// 后端素材状态原始值,保留尚未验证的值。
|
||||
let mediaStatus: String?
|
||||
/// 后端素材状态展示文案;空文案不生成新的业务状态。
|
||||
let mediaStatusLabel: String?
|
||||
/// 后端主动作标识,仅用于展示入口,不作为执行权限。
|
||||
let primaryAction: String?
|
||||
/// 后端主动作按钮文案。
|
||||
let primaryActionLabel: String?
|
||||
/// 后端游客用户 ID。
|
||||
let userID: Int?
|
||||
/// 拍摄列表状态 pending、processing、completed;未知值保留。
|
||||
let shootStatus: String?
|
||||
/// 订单支付和交付状态,与飞行任务状态分开。
|
||||
let orderStatus: Int?
|
||||
/// 整单原素材汇总状态。
|
||||
let materialStatus: Int?
|
||||
/// 已有成片的有效任务数。
|
||||
let filmCount: Int?
|
||||
/// 后端是否允许新增待飞任务。
|
||||
let canCreateTask: Bool?
|
||||
/// 后端是否允许上传成片。
|
||||
let canUploadFilm: Bool?
|
||||
/// 后端是否允许邀请游客确认完成。
|
||||
let canConfirm: Bool?
|
||||
/// 交付确认状态。
|
||||
let confirmStatus: Int?
|
||||
/// 游客确认完成时间,未完成时为空。
|
||||
let confirmedAt: String?
|
||||
|
||||
/// 已实测的首页订单字段名。
|
||||
/// 张工 orders 与订单摘要的字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case orderID = "order_id"
|
||||
case orderNumber = "order_number"
|
||||
case touristLabel = "tourist_label"
|
||||
case touristPhoneMask = "tourist_phone_mask"
|
||||
case packageName = "package_name"
|
||||
case statusLabel = "status_label"
|
||||
case shotTotal = "shot_total"
|
||||
case shotUsed = "shot_used"
|
||||
case shotRemain = "shot_remain"
|
||||
case progressText = "progress_text"
|
||||
case mediaStatus = "media_status"
|
||||
case mediaStatusLabel = "media_status_label"
|
||||
case primaryAction = "primary_action"
|
||||
case primaryActionLabel = "primary_action_label"
|
||||
case userID = "user_id"
|
||||
case orderNumber = "order_number", projectID = "project_id", createdAt = "created_at"
|
||||
case touristPhoneMask = "user_phone", packageName = "project_name"
|
||||
case shotTotal = "shoot_count", shotUsed = "shot_count", shotRemain = "remaining_count"
|
||||
case shootStatus = "shoot_status", orderStatus = "order_status", materialStatus = "material_status"
|
||||
case filmCount = "film_count", canCreateTask = "can_create_task", canUploadFilm = "can_upload_film"
|
||||
case canConfirm = "can_confirm", confirmStatus = "confirm_status", confirmedAt = "confirmed_at"
|
||||
}
|
||||
|
||||
/// 严格校验列表身份和计数;缺失展示字段保留未知。
|
||||
/// 保留未知展示值,但拒绝无身份、负次数和错误类型。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
orderID = try container.decode(DroneDockHomeInteger.self, forKey: .orderID).value
|
||||
guard orderID > 0 else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .orderID, in: container, debugDescription: "订单 ID 必须为正整数")
|
||||
let number = try container.decode(String.self, forKey: .orderNumber)
|
||||
guard !number.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
number == number.trimmingCharacters(in: .whitespacesAndNewlines) else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .orderNumber, in: container, debugDescription: "订单号必须为有效非空字符串")
|
||||
}
|
||||
orderNumber = try container.decodeIfPresent(String.self, forKey: .orderNumber)
|
||||
touristLabel = try container.decodeIfPresent(String.self, forKey: .touristLabel)
|
||||
orderID = number
|
||||
orderNumber = number
|
||||
projectID = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .projectID)?.value
|
||||
if let projectID, projectID <= 0 {
|
||||
throw DecodingError.dataCorruptedError(forKey: .projectID, in: container, debugDescription: "项目 ID 必须为正整数")
|
||||
}
|
||||
createdAt = try container.decodeIfPresent(String.self, forKey: .createdAt)
|
||||
touristPhoneMask = try container.decodeIfPresent(String.self, forKey: .touristPhoneMask)
|
||||
packageName = try container.decodeIfPresent(String.self, forKey: .packageName)
|
||||
statusLabel = try container.decodeIfPresent(String.self, forKey: .statusLabel)
|
||||
shotTotal = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .shotTotal)?.value
|
||||
shotUsed = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .shotUsed)?.value
|
||||
shotRemain = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .shotRemain)?.value
|
||||
for (key, value) in [(CodingKeys.shotTotal, shotTotal), (.shotUsed, shotUsed), (.shotRemain, shotRemain)] {
|
||||
filmCount = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .filmCount)?.value
|
||||
for (key, value) in [(CodingKeys.shotTotal, shotTotal), (.shotUsed, shotUsed), (.shotRemain, shotRemain), (.filmCount, filmCount)] {
|
||||
if let value, value < 0 {
|
||||
throw DecodingError.dataCorruptedError(forKey: key, in: container, debugDescription: "拍摄次数不能为负数")
|
||||
throw DecodingError.dataCorruptedError(forKey: key, in: container, debugDescription: "次数不能为负数")
|
||||
}
|
||||
}
|
||||
progressText = try container.decodeIfPresent(String.self, forKey: .progressText)
|
||||
mediaStatus = try container.decodeIfPresent(String.self, forKey: .mediaStatus)
|
||||
mediaStatusLabel = try container.decodeIfPresent(String.self, forKey: .mediaStatusLabel)
|
||||
primaryAction = try container.decodeIfPresent(String.self, forKey: .primaryAction)
|
||||
primaryActionLabel = try container.decodeIfPresent(String.self, forKey: .primaryActionLabel)
|
||||
userID = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .userID)?.value
|
||||
shootStatus = try container.decodeIfPresent(String.self, forKey: .shootStatus)
|
||||
orderStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .orderStatus)?.value
|
||||
materialStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .materialStatus)?.value
|
||||
canCreateTask = try container.decodeIfPresent(Bool.self, forKey: .canCreateTask)
|
||||
canUploadFilm = try container.decodeIfPresent(Bool.self, forKey: .canUploadFilm)
|
||||
canConfirm = try container.decodeIfPresent(Bool.self, forKey: .canConfirm)
|
||||
confirmStatus = try container.decodeIfPresent(DroneDockHomeInteger.self, forKey: .confirmStatus)?.value
|
||||
confirmedAt = try container.decodeIfPresent(String.self, forKey: .confirmedAt)
|
||||
}
|
||||
|
||||
/// 页面稳定身份,与后端订单 ID 一致。
|
||||
var id: Int { orderID }
|
||||
/// 页面稳定身份。
|
||||
var id: String { orderID }
|
||||
|
||||
/// 展示后端订单编号;缺失时不以内部 ID 冒充订单编号。
|
||||
var orderNumberText: String { DroneDockHomeMetric.usableText(orderNumber) ?? "—" }
|
||||
/// 原样展示后端订单号。
|
||||
var orderNumberText: String { orderID }
|
||||
|
||||
/// 优先展示服务端游客文案,其次使用已脱敏手机号。
|
||||
/// 仅使用后端提供的脱敏手机号。
|
||||
var touristTitle: String {
|
||||
if let label = DroneDockHomeMetric.usableText(touristLabel) { return label }
|
||||
if let phone = DroneDockHomeMetric.usableText(touristPhoneMask) { return "游客 \(phone)" }
|
||||
return "游客信息待确认"
|
||||
}
|
||||
|
||||
/// 展示后端套餐名称,缺失时不生成套餐或次数。
|
||||
/// 缺失项目名称时保留未知。
|
||||
var packageTitle: String { DroneDockHomeMetric.usableText(packageName) ?? "套餐信息待确认" }
|
||||
|
||||
/// 展示后端状态,缺失时不默认成待拍摄。
|
||||
var statusTitle: String { DroneDockHomeMetric.usableText(statusLabel) ?? "状态待确认" }
|
||||
/// 仅映射文档定义的拍摄列表状态,不根据次数推导完成。
|
||||
var statusTitle: String {
|
||||
switch shootStatus {
|
||||
case "pending": return "待拍摄"
|
||||
case "processing": return "进行中"
|
||||
case "completed": return "已完成"
|
||||
default: return "状态待确认"
|
||||
}
|
||||
}
|
||||
|
||||
/// 优先展示后端进度文案;没有文案时逐项展示真实计数与未知占位。
|
||||
/// 逐项展示真实计数和未知占位,不把任务数当作已使用次数。
|
||||
var progressTitle: String {
|
||||
if let text = DroneDockHomeMetric.usableText(progressText) { return text }
|
||||
let used = shotUsed.map(String.init) ?? "—"
|
||||
let total = shotTotal.map(String.init) ?? "—"
|
||||
let remain = shotRemain.map(String.init) ?? "—"
|
||||
return "已拍摄 \(used)/\(total) 次,剩余 \(remain) 次"
|
||||
}
|
||||
|
||||
/// 只有后端同时提供动作标识和文案时才显示按钮,不猜测缺失动作。
|
||||
var actionTitle: String? {
|
||||
guard DroneDockHomeMetric.usableText(primaryAction) != nil else { return nil }
|
||||
return DroneDockHomeMetric.usableText(primaryActionLabel)
|
||||
/// 依据后端权限提供入口标识;不从剩余次数猜测是否可拍。
|
||||
var primaryAction: String? {
|
||||
if canCreateTask == true { return "start_shoot" }
|
||||
if canConfirm == true { return "confirm_delivery" }
|
||||
if canUploadFilm == true { return "view_materials" }
|
||||
return nil
|
||||
}
|
||||
|
||||
/// 仅展示有效的后端素材状态文案,不将空值转成未上传等新状态。
|
||||
/// 与后端权限对应的按钮文案。
|
||||
var actionTitle: String? {
|
||||
switch primaryAction {
|
||||
case "start_shoot": return "开始拍摄"
|
||||
case "confirm_delivery": return "邀请确认"
|
||||
case "view_materials": return "查看素材"
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// 映射原素材汇总状态;未知值不显示成成功或失败。
|
||||
var mediaStatusTitle: String? {
|
||||
DroneDockHomeMetric.usableText(mediaStatusLabel)
|
||||
switch materialStatus {
|
||||
case 0: return "未开始上传"
|
||||
case 1: return "上传完成"
|
||||
case 2: return "上传中"
|
||||
case 3: return "上传失败"
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,22 +38,49 @@ struct DroneDockHomeContext: Equatable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// 真实机巢首页的独立读取状态;不使用演示订单、演示设备或本地拍摄任务。
|
||||
/// 分别读取朱工设备与张工订单、统计的首页状态,保留各区域独立的失败结果。
|
||||
final class DroneDockHomeViewModel {
|
||||
/// 当前页面所属的真实账号、景区和门店。
|
||||
private(set) var context: DroneDockHomeContext
|
||||
/// 最近一次成功读取的当前范围首页;加载失败或身份变更时清除。
|
||||
/// 朱工 home 返回的设备快照。
|
||||
private(set) var response: DroneDockHomeResponse?
|
||||
/// 当前最新一次请求是否尚未结束。
|
||||
/// 最近一页订单及服务端总数;累计订单通过 orders 读取。
|
||||
private(set) var ordersResponse: DroneDockOrdersResponse?
|
||||
/// 张工 today-stats 返回的今日数据。
|
||||
private(set) var today: DroneDockHomeToday?
|
||||
/// 三个首屏读取是否尚未全部结束。
|
||||
private(set) var isLoading = false
|
||||
/// 当前请求的可展示错误;与成功空列表分开表达。
|
||||
/// 是否正在加载下一页订单。
|
||||
private(set) var isLoadingMore = false
|
||||
/// 登录、景区或门店范围发生问题时的整页提示。
|
||||
private(set) var errorMessage: String?
|
||||
/// 设备接口错误,不影响订单和统计。
|
||||
private(set) var deviceErrorMessage: String?
|
||||
/// 订单首屏错误,不影响设备和统计。
|
||||
private(set) var ordersErrorMessage: String?
|
||||
/// 统计接口错误,不影响设备和订单。
|
||||
private(set) var statisticsErrorMessage: String?
|
||||
/// 下一页错误,保留已显示订单并允许重试同一页。
|
||||
private(set) var ordersLoadMoreErrorMessage: String?
|
||||
/// 当前累计订单,按服务端顺序显示并以订单号去重。
|
||||
var orders: [DroneDockHomeOrder] { loadedOrders }
|
||||
/// 服务端整单列表总数,不以当前页数量代替。
|
||||
var orderTotal: Int? { ordersResponse?.total }
|
||||
/// 分页依据服务端页码和总数,空页会停止继续加载。
|
||||
var hasMoreOrders: Bool {
|
||||
guard let page = ordersResponse, !reachedEmptyPage else { return false }
|
||||
return page.page < Int(ceil(Double(page.total) / Double(page.pageSize)))
|
||||
}
|
||||
|
||||
private let service: any DroneDockHomeServing
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
private let pageSize = 20
|
||||
private var loadedOrders: [DroneDockHomeOrder] = []
|
||||
private var reachedEmptyPage = false
|
||||
private var generation = 0
|
||||
private var paginationGeneration = 0
|
||||
|
||||
/// 注入读取服务与最新会话提供器,调用方在刷新完成后主动更新界面。
|
||||
/// 注入只读服务及最新会话,界面在刷新或翻页完成后主动更新。
|
||||
init(context: DroneDockHomeContext, service: any DroneDockHomeServing,
|
||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||
self.context = context
|
||||
@@ -61,46 +88,117 @@ final class DroneDockHomeViewModel {
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 刷新真实首页;拒绝旧请求、旧登录凭证、旧景区及旧门店的迟到结果。
|
||||
/// 并行刷新三个来源;单接口失败不丢弃其他区域的成功数据。
|
||||
func refresh() async {
|
||||
generation &+= 1
|
||||
paginationGeneration &+= 1
|
||||
let requestGeneration = generation
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
isLoadingMore = false
|
||||
clearErrors()
|
||||
defer { if generation == requestGeneration { isLoading = false } }
|
||||
let requestedContext = await currentContext()
|
||||
guard generation == requestGeneration, !Task.isCancelled else { return }
|
||||
if !context.hasSameIdentity(as: requestedContext) { response = nil }
|
||||
if !context.hasSameIdentity(as: requestedContext) { clearData() }
|
||||
context = requestedContext
|
||||
guard requestedContext.canLoad else {
|
||||
response = nil
|
||||
isLoading = false
|
||||
clearData()
|
||||
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 }
|
||||
let service = self.service
|
||||
let pageSize = self.pageSize
|
||||
async let devices = Self.capture {
|
||||
try await service.home(scenicID: requestedContext.scenicID, storeID: requestedContext.storeID)
|
||||
}
|
||||
async let firstPage = Self.capture {
|
||||
try await service.orders(scenicID: requestedContext.scenicID, page: 1, pageSize: pageSize)
|
||||
}
|
||||
async let statistics = Self.capture {
|
||||
try await service.todayStats(scenicID: requestedContext.scenicID)
|
||||
}
|
||||
let results = await (devices, firstPage, statistics)
|
||||
guard await accepts(requestGeneration, context: requestedContext) else { return }
|
||||
switch results.0 {
|
||||
case .success(let value) where value.scenicID == requestedContext.scenicID:
|
||||
response = value
|
||||
case .success:
|
||||
response = nil
|
||||
if error is CancellationError { return }
|
||||
errorMessage = error.localizedDescription
|
||||
deviceErrorMessage = "接口返回的景区与当前景区不一致,请刷新重试"
|
||||
case .failure(let error):
|
||||
response = nil
|
||||
deviceErrorMessage = Self.message(for: error)
|
||||
}
|
||||
switch results.1 {
|
||||
case .success(let value) where value.page == 1:
|
||||
ordersResponse = value
|
||||
loadedOrders = value.list
|
||||
reachedEmptyPage = value.list.isEmpty
|
||||
case .success:
|
||||
clearOrders()
|
||||
ordersErrorMessage = "订单分页返回异常,请刷新重试"
|
||||
case .failure(let error):
|
||||
clearOrders()
|
||||
ordersErrorMessage = Self.message(for: error)
|
||||
}
|
||||
switch results.2 {
|
||||
case .success(let value): today = value
|
||||
case .failure(let error):
|
||||
today = nil
|
||||
statisticsErrorMessage = Self.message(for: error)
|
||||
}
|
||||
}
|
||||
|
||||
/// 离开或取消当前读取时使所有在途结果失效;再次刷新仍可重新加载。
|
||||
/// 加载下一页;失败不清除已加载订单,刷新或切换会话后拒绝旧分页响应。
|
||||
func loadMoreOrders() async {
|
||||
guard !isLoading, !isLoadingMore, hasMoreOrders, let previousPage = ordersResponse else { return }
|
||||
let requestGeneration = generation
|
||||
paginationGeneration &+= 1
|
||||
let pageGeneration = paginationGeneration
|
||||
let requestedContext = context
|
||||
let nextPage = previousPage.page + 1
|
||||
isLoadingMore = true
|
||||
ordersLoadMoreErrorMessage = nil
|
||||
defer {
|
||||
if generation == requestGeneration, paginationGeneration == pageGeneration { isLoadingMore = false }
|
||||
}
|
||||
guard await accepts(requestGeneration, context: requestedContext),
|
||||
paginationGeneration == pageGeneration else { return }
|
||||
do {
|
||||
let value = try await service.orders(scenicID: requestedContext.scenicID,
|
||||
page: nextPage, pageSize: previousPage.pageSize)
|
||||
guard await accepts(requestGeneration, context: requestedContext),
|
||||
paginationGeneration == pageGeneration else { return }
|
||||
guard value.page == nextPage, value.pageSize == previousPage.pageSize else {
|
||||
ordersLoadMoreErrorMessage = "订单分页返回异常,请重试"
|
||||
return
|
||||
}
|
||||
var indices = Dictionary(uniqueKeysWithValues: loadedOrders.enumerated().map { ($0.element.orderID, $0.offset) })
|
||||
for order in value.list {
|
||||
if let index = indices[order.orderID] {
|
||||
loadedOrders[index] = order
|
||||
} else {
|
||||
indices[order.orderID] = loadedOrders.count
|
||||
loadedOrders.append(order)
|
||||
}
|
||||
}
|
||||
ordersResponse = value
|
||||
reachedEmptyPage = value.list.isEmpty
|
||||
} catch {
|
||||
guard await accepts(requestGeneration, context: requestedContext),
|
||||
paginationGeneration == pageGeneration else { return }
|
||||
ordersLoadMoreErrorMessage = Self.message(for: error)
|
||||
}
|
||||
}
|
||||
|
||||
/// 离开或取消时清空三处数据,并使全部在途请求和分页响应失效。
|
||||
func invalidate() {
|
||||
generation &+= 1
|
||||
response = nil
|
||||
errorMessage = nil
|
||||
paginationGeneration &+= 1
|
||||
clearData()
|
||||
clearErrors()
|
||||
isLoading = false
|
||||
isLoadingMore = false
|
||||
}
|
||||
|
||||
private func accepts(_ requestGeneration: Int, context requested: DroneDockHomeContext) async -> Bool {
|
||||
@@ -108,13 +206,40 @@ final class DroneDockHomeViewModel {
|
||||
let latest = await currentContext()
|
||||
guard generation == requestGeneration, !Task.isCancelled else { return false }
|
||||
guard requested.hasSameIdentity(as: latest) else {
|
||||
generation &+= 1
|
||||
invalidate()
|
||||
context = latest
|
||||
response = nil
|
||||
isLoading = false
|
||||
errorMessage = "账号或景区已变化,请刷新工作台"
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private func clearData() {
|
||||
response = nil
|
||||
today = nil
|
||||
clearOrders()
|
||||
}
|
||||
|
||||
private func clearOrders() {
|
||||
ordersResponse = nil
|
||||
loadedOrders = []
|
||||
reachedEmptyPage = false
|
||||
}
|
||||
|
||||
private func clearErrors() {
|
||||
errorMessage = nil
|
||||
deviceErrorMessage = nil
|
||||
ordersErrorMessage = nil
|
||||
statisticsErrorMessage = nil
|
||||
ordersLoadMoreErrorMessage = nil
|
||||
}
|
||||
|
||||
private static func message(for error: Error) -> String? {
|
||||
error is CancellationError ? nil : error.localizedDescription
|
||||
}
|
||||
|
||||
private static func capture<Value: Sendable>(_ operation: @Sendable () async throws -> Value) async -> Result<Value, Error> {
|
||||
do { return .success(try await operation()) }
|
||||
catch { return .failure(error) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ final class DroneDockCompactOrderCell: UICollectionViewCell {
|
||||
accessibilityIdentifier = "drone.home.\(order.id)"
|
||||
}
|
||||
|
||||
/// 展示 home 的真实订单快照,缺失字段保持未知,按钮只向页面报告点击。
|
||||
/// 展示张工 orders 的真实摘要,权限决定按钮入口,点击交给页面处理。
|
||||
func apply(homeOrder order: DroneDockHomeOrder) {
|
||||
customerLabel.text = order.touristTitle
|
||||
orderNumberLabel.isHidden = false
|
||||
@@ -65,9 +65,14 @@ final class DroneDockCompactOrderCell: UICollectionViewCell {
|
||||
actionButton.backgroundColor = actionButton.isEnabled ? DroneDockStyle.primary : DroneDockStyle.secondary
|
||||
actionButton.accessibilityIdentifier = "drone.home.order.\(order.orderID).primary"
|
||||
let materialTitle = order.mediaStatusTitle ?? ""
|
||||
let materialStatus = order.mediaStatus?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
footer.isHidden = materialStatus.isEmpty || materialStatus == "none" || materialTitle.isEmpty
|
||||
applyMaterial(title: materialTitle, symbol: "photo.on.rectangle.angled", tone: .gray)
|
||||
footer.isHidden = materialTitle.isEmpty
|
||||
let materialTone: DroneDockStatusTone = switch order.materialStatus {
|
||||
case 1: .green
|
||||
case 2: .blue
|
||||
case 3: .red
|
||||
default: .gray
|
||||
}
|
||||
applyMaterial(title: materialTitle, symbol: "photo.on.rectangle.angled", tone: materialTone)
|
||||
accessibilityIdentifier = "drone.home.order.\(order.orderID)"
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 正式机巢首页,仅展示 airport/home 的真实快照,不进入本地演示业务。
|
||||
/// 正式机巢首页:朱工提供设备,张工提供订单与今日统计。
|
||||
final class DroneDockHomeViewController: BaseViewController {
|
||||
/// 与演示数据源隔离的首页状态。
|
||||
let viewModel: DroneDockHomeViewModel
|
||||
private let paymentControllerFactory: (() -> UIViewController)?
|
||||
private let preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)?
|
||||
private var refreshTask: Task<Void, Never>?
|
||||
private var loadMoreTask: Task<Void, Never>?
|
||||
private var isRefreshing = false
|
||||
private var isLoadingOrdersPage = 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, order(Int), statistics }
|
||||
private enum Item: Hashable { case context, devices, device(Int), orders, order(String), moreOrders, statistics }
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||||
|
||||
@@ -41,7 +43,10 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
deinit { refreshTask?.cancel() }
|
||||
deinit {
|
||||
refreshTask?.cancel()
|
||||
loadMoreTask?.cancel()
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "机巢工作台"
|
||||
@@ -92,16 +97,20 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
refreshTask?.cancel()
|
||||
loadMoreTask?.cancel()
|
||||
isRefreshing = false
|
||||
isLoadingOrdersPage = false
|
||||
viewModel.invalidate()
|
||||
}
|
||||
|
||||
private func refreshHome() {
|
||||
refreshTask?.cancel()
|
||||
loadMoreTask?.cancel()
|
||||
isLoadingOrdersPage = false
|
||||
isRefreshing = true
|
||||
refreshTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
let isInitialLoad = self.viewModel.response == nil
|
||||
let isInitialLoad = self.viewModel.response == nil && self.viewModel.ordersResponse == nil
|
||||
self.applySnapshot(animated: false)
|
||||
await self.viewModel.refresh()
|
||||
guard !Task.isCancelled else { return }
|
||||
@@ -131,7 +140,7 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
}
|
||||
if case .order(let id) = item {
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DroneDockCompactOrderCell
|
||||
if let order = self.viewModel.response?.orders.first(where: { $0.orderID == id }) {
|
||||
if let order = self.viewModel.orders.first(where: { $0.orderID == id }) {
|
||||
cell.apply(homeOrder: order)
|
||||
cell.onShootingTap = { [weak self] in
|
||||
self?.openPreparation(orderID: id)
|
||||
@@ -147,7 +156,12 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
let title = [context.scenicName, context.photographerName].filter { !$0.isEmpty }.joined(separator: " · ")
|
||||
cell.applyContext(title.isEmpty ? "机巢工作台" : title)
|
||||
case .statistics:
|
||||
cell.applyStatistics(self.viewModel.response?.today)
|
||||
cell.applyStatistics(self.viewModel.today,
|
||||
error: self.viewModel.statisticsErrorMessage ?? self.viewModel.errorMessage)
|
||||
case .moreOrders:
|
||||
cell.applyLoadMore(isLoading: self.isLoadingOrdersPage,
|
||||
error: self.viewModel.ordersLoadMoreErrorMessage,
|
||||
enabled: !self.isRefreshing) { [weak self] in self?.loadMoreOrders() }
|
||||
case .devices, .orders:
|
||||
self.applyDataState(to: cell, isDevice: item == .devices)
|
||||
case .device, .order: break
|
||||
@@ -163,27 +177,30 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
}
|
||||
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("拍摄订单") }
|
||||
let orderTitle = self.viewModel.orderTotal.map { "我的拍摄订单(\($0))" } ?? "我的拍摄订单"
|
||||
header.apply(title: isOrders ? orderTitle : "今日统计", isOrders: isOrders)
|
||||
return header
|
||||
}
|
||||
}
|
||||
|
||||
private func applyDataState(to cell: DroneDockHomeContentCell, isDevice: Bool) {
|
||||
if isRefreshing, viewModel.response == nil {
|
||||
let hasResponse = isDevice ? viewModel.response != nil : viewModel.ordersResponse != nil
|
||||
let error = (isDevice ? viewModel.deviceErrorMessage : viewModel.ordersErrorMessage) ?? viewModel.errorMessage
|
||||
if isRefreshing, !hasResponse {
|
||||
cell.applyMessage(symbol: "arrow.triangle.2.circlepath", title: "正在加载", detail: "正在获取最新数据")
|
||||
return
|
||||
}
|
||||
if let error = viewModel.errorMessage {
|
||||
cell.applyMessage(symbol: "wifi.exclamationmark", title: "首页加载失败", detail: error + ",请下拉重试")
|
||||
if let error {
|
||||
cell.applyMessage(symbol: "wifi.exclamationmark", title: isDevice ? "设备加载失败" : "订单加载失败",
|
||||
detail: error + ",请下拉重试")
|
||||
return
|
||||
}
|
||||
guard viewModel.response != nil else {
|
||||
guard hasResponse else {
|
||||
cell.applyMessage(symbol: "arrow.triangle.2.circlepath", title: "正在加载", detail: "正在获取最新数据")
|
||||
return
|
||||
}
|
||||
cell.applyMessage(symbol: isDevice ? "airplane" : "doc.text",
|
||||
title: isDevice ? "暂无无人机" : "暂无待拍摄订单",
|
||||
title: isDevice ? "暂无无人机" : "暂无拍摄订单",
|
||||
detail: isDevice ? "当前景区暂无设备数据" : "当前景区暂无拍摄订单数据")
|
||||
}
|
||||
|
||||
@@ -194,8 +211,11 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
snapshot.appendItems([.context], toSection: .context)
|
||||
let airports = viewModel.response?.airports ?? []
|
||||
snapshot.appendItems(airports.isEmpty ? [.devices] : airports.map { .device($0.id) }, toSection: .devices)
|
||||
let orders = viewModel.response?.orders ?? []
|
||||
let orders = viewModel.orders
|
||||
snapshot.appendItems(orders.isEmpty ? [.orders] : orders.map { .order($0.orderID) }, toSection: .orders)
|
||||
if viewModel.hasMoreOrders || viewModel.isLoadingMore || viewModel.ordersLoadMoreErrorMessage != nil {
|
||||
snapshot.appendItems([.moreOrders], 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
|
||||
@@ -206,7 +226,18 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
if previousDeviceCount != airports.count {
|
||||
collectionView.setCollectionViewLayout(makeLayout(), animated: false)
|
||||
}
|
||||
dataSource.apply(snapshot, animatingDifferences: animated, completion: completion)
|
||||
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
|
||||
if let self {
|
||||
for path in self.collectionView.indexPathsForVisibleSupplementaryElements(ofKind: UICollectionView.elementKindSectionHeader) {
|
||||
guard let header = self.collectionView.supplementaryView(
|
||||
forElementKind: UICollectionView.elementKindSectionHeader, at: path) as? DroneDockHomeHeader else { continue }
|
||||
let isOrders = Section(rawValue: path.section) == .orders
|
||||
let title = self.viewModel.orderTotal.map { "我的拍摄订单(\($0))" } ?? "我的拍摄订单"
|
||||
header.apply(title: isOrders ? title : "今日统计", isOrders: isOrders)
|
||||
}
|
||||
}
|
||||
completion?()
|
||||
}
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
@@ -249,8 +280,8 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
showAlert(title: feature, message: "该功能暂未开放")
|
||||
}
|
||||
|
||||
private func openPreparation(orderID: Int) {
|
||||
guard !isRefreshing, let order = viewModel.response?.orders.first(where: { $0.orderID == orderID }) else { return }
|
||||
private func openPreparation(orderID: String) {
|
||||
guard !isRefreshing, let order = viewModel.orders.first(where: { $0.orderID == orderID }) else { return }
|
||||
guard order.primaryAction == "start_shoot" else {
|
||||
showUnavailable(order.actionTitle ?? "拍摄订单")
|
||||
return
|
||||
@@ -276,6 +307,21 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
}
|
||||
@objc private func refreshTriggered() { refreshHome() }
|
||||
|
||||
/// 按后端分页继续读取订单,失败保留已有列表并允许重试。
|
||||
private func loadMoreOrders() {
|
||||
guard !isRefreshing, !isLoadingOrdersPage, !viewModel.isLoadingMore else { return }
|
||||
loadMoreTask?.cancel()
|
||||
isLoadingOrdersPage = true
|
||||
applySnapshot(animated: false)
|
||||
loadMoreTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.loadMoreOrders()
|
||||
guard !Task.isCancelled else { return }
|
||||
self.isLoadingOrdersPage = false
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// 显式联调参数下只保存本应用窗口,不截取用户切换后的其他 App。
|
||||
private func captureHomeIfRequested() async {
|
||||
@@ -348,8 +394,8 @@ private final class DroneDockHomeContentCell: UICollectionViewCell {
|
||||
install(stack, insets: UIEdgeInsets(top: 22, left: 16, bottom: 22, right: 16), card: true)
|
||||
}
|
||||
|
||||
/// 使用服务端 today 字段;缺失数据保持未知,不显示为零。
|
||||
func applyStatistics(_ today: DroneDockHomeToday?) {
|
||||
/// 展示张工 today-stats 的成交与确认完成统计,失败保持未知并提示重试。
|
||||
func applyStatistics(_ today: DroneDockHomeToday?, error: String?) {
|
||||
let formatter = NumberFormatter()
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.numberStyle = .decimal
|
||||
@@ -368,11 +414,40 @@ private final class DroneDockHomeContentCell: UICollectionViewCell {
|
||||
stack.spacing = 9
|
||||
return stack
|
||||
}
|
||||
let stack = UIStackView(arrangedSubviews: columns)
|
||||
stack.distribution = .fillEqually
|
||||
let row = UIStackView(arrangedSubviews: columns)
|
||||
row.distribution = .fillEqually
|
||||
let stack = UIStackView(arrangedSubviews: [row])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 12
|
||||
if let error {
|
||||
let message = DroneDockStyle.label("统计加载失败,请下拉重试\n\(error)", size: 12, color: DroneDockStyle.secondary)
|
||||
message.numberOfLines = 0
|
||||
message.textAlignment = .center
|
||||
stack.addArrangedSubview(message)
|
||||
}
|
||||
install(stack, insets: UIEdgeInsets(top: 23, left: 10, bottom: 23, right: 10), card: true)
|
||||
}
|
||||
|
||||
/// 订单分页入口;提交期间禁用,查询失败不清空之前已加载的订单。
|
||||
func applyLoadMore(isLoading: Bool, error: String?, enabled: Bool, action: @escaping () -> Void) {
|
||||
let button = UIButton(type: .system)
|
||||
button.setTitle(isLoading ? "加载中…" : error == nil ? "加载更多订单" : "重试加载更多", for: .normal)
|
||||
button.tintColor = DroneDockStyle.primary
|
||||
button.isEnabled = enabled && !isLoading
|
||||
button.accessibilityIdentifier = "drone.home.orders.loadMore"
|
||||
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(44) }
|
||||
button.addAction(UIAction { _ in action() }, for: .touchUpInside)
|
||||
let stack = UIStackView(arrangedSubviews: [button])
|
||||
stack.axis = .vertical
|
||||
if let error {
|
||||
let label = DroneDockStyle.label(error, size: 12, color: DroneDockStyle.secondary)
|
||||
label.numberOfLines = 0
|
||||
label.textAlignment = .center
|
||||
stack.addArrangedSubview(label)
|
||||
}
|
||||
install(stack, insets: UIEdgeInsets(top: 4, left: 16, bottom: 8, right: 16), card: false)
|
||||
}
|
||||
|
||||
private func install(_ view: UIView, insets: UIEdgeInsets, card: Bool) {
|
||||
embeddedView?.removeFromSuperview()
|
||||
embeddedView = view
|
||||
@@ -382,35 +457,22 @@ private final class DroneDockHomeContentCell: UICollectionViewCell {
|
||||
}
|
||||
}
|
||||
|
||||
/// 首页分区标题与后续订单列表入口。
|
||||
/// 首页分区标题,订单数量使用接口 total,不使用当前页条数。
|
||||
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() }
|
||||
addSubview(label)
|
||||
label.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) {
|
||||
/// 区分订单总数与统计标题,便于读取真实总数。
|
||||
func apply(title: String, isOrders: Bool) {
|
||||
label.text = title
|
||||
button.isHidden = !showsAction
|
||||
label.accessibilityIdentifier = isOrders ? "drone.home.orderCount" : nil
|
||||
}
|
||||
|
||||
@objc private func tapped() { onViewAll?() }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user