feat(drone-dock): 对接订单素材库与点位筛选

This commit is contained in:
2026-10-28 18:08:39 +08:00
parent 06460fe7e6
commit 88fa1f9b77
17 changed files with 2309 additions and 30 deletions
@@ -0,0 +1,60 @@
import Foundation
/// 订单素材库只读数据源,分别读取整单摘要和指定范围内的任务。
protocol DroneDockMaterialsServing: Sendable {
/// 获取整单摘要和购买点位;筛选任务不改变摘要口径。
@MainActor
func detail(scenicID: Int, orderNumber: String) async throws -> DroneDockMaterialDetail
/// 一次获取全部有效任务;spotID 为空时省略点位参数。
@MainActor
func tasks(scenicID: Int, orderNumber: String, spotID: Int?) async throws -> DroneDockMaterialTasks
}
/// 张工订单素材库与点位筛选接口,复用统一登录凭证和业务错误处理。
@MainActor
final class DroneDockMaterialsAPI: DroneDockMaterialsServing {
private let client: APIClient
/// 注入统一客户端,便于在测试中隔离网络。
init(client: APIClient) { self.client = client }
/// 读取根级订单摘要及 spot,不使用 workbench 或其他订单的数据回填。
func detail(scenicID: Int, orderNumber: String) async throws -> DroneDockMaterialDetail {
let queryItems = try queryItems(scenicID: scenicID, orderNumber: orderNumber)
let response: DroneDockMaterialDetail = try await client.send(APIRequest(
method: .get, path: "/api/yf-handset-app/photog/multi-plane/orders/detail", queryItems: queryItems
))
guard response.order.orderNumber == orderNumber else {
throw APIError.decodeFailed("素材库摘要与当前订单不一致,请刷新重试")
}
return response
}
/// 点位仅筛选任务;响应必须属于请求订单和点位,不发送分页参数。
func tasks(scenicID: Int, orderNumber: String, spotID: Int?) async throws -> DroneDockMaterialTasks {
var queryItems = try queryItems(scenicID: scenicID, orderNumber: orderNumber)
if let spotID {
guard spotID > 0 else { throw APIError.networkFailed("缺少有效拍摄点,请重新选择") }
queryItems.append(URLQueryItem(name: "scenic_spot_id", value: String(spotID)))
}
let response: DroneDockMaterialTasks = try await client.send(APIRequest(
method: .get, path: "/api/yf-handset-app/photog/multi-plane/tasks", queryItems: queryItems
))
guard response.orderNumber == orderNumber,
spotID == nil || response.list.allSatisfy({ $0.spotID == spotID }) else {
throw APIError.decodeFailed("素材任务与当前订单或拍摄点不一致,请刷新重试")
}
return response
}
/// 请求前验证页面范围,禁止用缺失身份请求其他订单。
private func queryItems(scenicID: Int, orderNumber: String) throws -> [URLQueryItem] {
guard scenicID > 0, !orderNumber.isEmpty, orderNumber.count <= 128,
orderNumber == orderNumber.trimmingCharacters(in: .whitespacesAndNewlines) else {
throw APIError.networkFailed("缺少有效景区或订单信息,请返回订单列表重新进入")
}
return [URLQueryItem(name: "scenic_id", value: String(scenicID)),
URLQueryItem(name: "order_number", value: orderNumber)]
}
}
@@ -0,0 +1,284 @@
import Foundation
/// 订单素材库的整单摘要和购买点位,不受当前素材筛选条件影响。
struct DroneDockMaterialDetail: Decodable, Equatable, Sendable {
/// 复用张工订单摘要中的次数、状态和操作权限。
let order: DroneDockHomeOrder
/// 按购买快照顺序返回的点位筛选项。
let spots: [DroneDockMaterialSpot]
/// 订单摘要位于根级,购买点位使用单数 spot 字段。
private enum CodingKeys: String, CodingKey { case spots = "spot" }
/// 显式空数组表示无点位;缺少配置或重复身份视为异常响应。
init(from decoder: Decoder) throws {
order = try DroneDockHomeOrder(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
spots = try container.decode([DroneDockMaterialSpot].self, forKey: .spots)
guard Set(spots.map(\.id)).count == spots.count else {
throw DecodingError.dataCorruptedError(forKey: .spots, in: container, debugDescription: "素材库点位 ID 重复")
}
}
}
/// 订单购买快照中的点位筛选项。
struct DroneDockMaterialSpot: Decodable, Equatable, Sendable {
/// 点位稳定身份,向 tasks 传递为 scenic_spot_id。
let id: Int
/// 点位名称,缺失时由页面显示占位文本。
let name: String
/// 张工点位快照字段。
private enum CodingKeys: String, CodingKey {
case id = "scenic_spot_id", name = "scenic_spot_name"
}
/// 点位身份必须有效,缺失名称不影响查看该点位任务。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.positiveMaterialID(forKey: .id)
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
}
}
/// 当前订单及点位范围内的全部有效任务;接口一次返回,无分页。
struct DroneDockMaterialTasks: Decodable, Equatable, Sendable {
/// 任务列表所属订单号。
let orderNumber: String
/// 当前范围内的任务记录数,不能用作成功拍摄次数。
let total: Int
/// 保留服务端顺序及待飞、失败等任务。
let list: [DroneDockMaterialTask]
/// tasks 响应根字段。
private enum CodingKeys: String, CodingKey { case orderNumber = "order_number", total, list }
/// 校验完整列表及订单归属,避免异常结构被展示成真实空态。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderNumber = try container.materialOrderNumber(forKey: .orderNumber)
total = try container.decode(DroneDockMaterialInteger.self, forKey: .total).value
list = try container.decode([DroneDockMaterialTask].self, forKey: .list)
guard total >= 0, total == list.count else {
throw DecodingError.dataCorruptedError(forKey: .total, in: container, debugDescription: "任务总数与完整列表不一致")
}
guard Set(list.map(\.id)).count == list.count else {
throw DecodingError.dataCorruptedError(forKey: .list, in: container, debugDescription: "素材库任务 ID 重复")
}
guard list.allSatisfy({ $0.orderNumber == orderNumber }) else {
throw DecodingError.dataCorruptedError(forKey: .list, in: container, debugDescription: "任务不属于当前订单")
}
}
}
/// 一次有效飞行任务及其原素材、当前成片,不以素材是否就绪隐藏任务。
struct DroneDockMaterialTask: Decodable, Equatable, Sendable {
/// 订单飞行任务身份,与实际飞行平台任务编号不同。
let id: Int
/// 任务所属订单号。
let orderNumber: String
/// 购买快照中的点位身份。
let spotID: Int
/// 购买快照中的点位名称,缺失时为空。
let spotName: String
/// 购买快照中的航线名称。
let airLineName: String?
/// 订单内任务序号,不代表成功拍摄次数。
let sequence: Int?
/// 后端飞行状态,未知状态原样保留。
let flightStatus: Int?
/// 本任务原素材聚合状态。
let materialStatus: Int?
/// 服务端记录的任务创建时间。
let createdAt: String?
/// 本次任务的原素材,显式空数组表示尚无素材。
let materials: [DroneDockMaterialFile]
/// 当前已交付的视频成片,未交付时为空。
let film: DroneDockMaterialFilm?
/// 张工任务字段,id 与 task_id 表示同一任务。
private enum CodingKeys: String, CodingKey {
case id, taskID = "task_id", orderNumber = "order_number"
case spotID = "scenic_spot_id", spotName = "scenic_spot_name", airLineName = "air_line_name"
case sequence = "seq", flightStatus = "flight_status", materialStatus = "material_status"
case createdAt = "created_at", materials, film
}
/// 兼容两种任务 ID 字段,但拒绝冲突、重复素材及其他任务的成片。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let identifier = try container.optionalPositiveMaterialID(forKey: .id)
let taskIdentifier = try container.optionalPositiveMaterialID(forKey: .taskID)
guard let resolvedID = identifier ?? taskIdentifier,
identifier == nil || taskIdentifier == nil || identifier == taskIdentifier else {
throw DecodingError.dataCorruptedError(forKey: .id, in: container, debugDescription: "任务 ID 缺失或不一致")
}
id = resolvedID
orderNumber = try container.materialOrderNumber(forKey: .orderNumber)
spotID = try container.positiveMaterialID(forKey: .spotID)
spotName = try container.decodeIfPresent(String.self, forKey: .spotName) ?? ""
airLineName = try container.decodeIfPresent(String.self, forKey: .airLineName)
sequence = try container.optionalMaterialInteger(forKey: .sequence)
flightStatus = try container.optionalMaterialInteger(forKey: .flightStatus)
materialStatus = try container.optionalMaterialInteger(forKey: .materialStatus)
createdAt = try container.decodeIfPresent(String.self, forKey: .createdAt)
materials = try container.decode([DroneDockMaterialFile].self, forKey: .materials)
film = try container.decodeIfPresent(DroneDockMaterialFilm.self, forKey: .film)
guard Set(materials.map(\.id)).count == materials.count else {
throw DecodingError.dataCorruptedError(forKey: .materials, in: container, debugDescription: "任务内素材 ID 重复")
}
if let filmTaskID = film?.taskID, filmTaskID != id {
throw DecodingError.dataCorruptedError(forKey: .film, in: container, debugDescription: "成片不属于当前任务")
}
}
}
/// 飞行模块回写的原素材,上传未完成时保留其状态和失败说明。
struct DroneDockMaterialFile: Decodable, Equatable, Sendable {
/// 素材稳定身份,在所属任务内唯一。
let id: Int
/// 1 为图片、2 为视频,未知值保留且不开放预览。
let fileType: Int?
/// 原素材文件名。
let fileName: String?
/// 原素材字节数,缺失时不推测。
let fileSize: Int?
/// 后端提供的封面地址。
let coverURL: String?
/// 后端提供的文件地址,未上传完成时可能为空串。
let fileURL: String?
/// 0 未开始、1 已就绪、2 上传中、3 失败。
let uploadStatus: Int?
/// 服务端返回的上传失败原因。
let failureReason: String?
/// 只有明确就绪且类型受支持的 HTTP(S) 文件才可预览。
var previewURL: URL? {
guard uploadStatus == 1, fileType == 1 || fileType == 2 else { return nil }
return DroneDockMaterialURL.preview(fileURL)
}
/// 张工原素材字段。
private enum CodingKeys: String, CodingKey {
case id, fileType = "file_type", fileName = "file_name", fileSize = "file_size"
case coverURL = "cover_url", fileURL = "file_url", uploadStatus = "upload_status"
case failureReason = "failure_reason"
}
/// 解码可为空的回写信息,素材身份仍必须有效。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.positiveMaterialID(forKey: .id)
fileType = try container.optionalMaterialInteger(forKey: .fileType)
fileName = try container.decodeIfPresent(String.self, forKey: .fileName)
fileSize = try container.optionalMaterialSize(forKey: .fileSize)
coverURL = try container.decodeIfPresent(String.self, forKey: .coverURL)
fileURL = try container.decodeIfPresent(String.self, forKey: .fileURL)
uploadStatus = try container.optionalMaterialInteger(forKey: .uploadStatus)
failureReason = try container.decodeIfPresent(String.self, forKey: .failureReason)
}
}
/// 当前任务已交付的成片;缺少有效地址时保留记录但不提供预览。
struct DroneDockMaterialFilm: Decodable, Equatable, Sendable {
/// 成片稳定身份。
let id: Int
/// 所属任务身份,接口提供时必须与外层任务一致。
let taskID: Int?
/// 成片文件名。
let fileName: String?
/// 成片字节数。
let fileSize: Int?
/// 后端提供的成片封面地址。
let coverURL: String?
/// 后端提供的成片视频地址。
let fileURL: String?
/// 已交付成片只接受有效 HTTP(S) 视频地址。
var previewURL: URL? { DroneDockMaterialURL.preview(fileURL) }
/// 张工当前成片字段。
private enum CodingKeys: String, CodingKey {
case id, taskID = "task_id", fileName = "file_name", fileSize = "file_size"
case coverURL = "cover_url", fileURL = "file_url"
}
/// 容忍未回写的展示字段,保留可校验的任务归属。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.positiveMaterialID(forKey: .id)
taskID = try container.optionalPositiveMaterialID(forKey: .taskID)
fileName = try container.decodeIfPresent(String.self, forKey: .fileName)
fileSize = try container.optionalMaterialSize(forKey: .fileSize)
coverURL = try container.decodeIfPresent(String.self, forKey: .coverURL)
fileURL = try container.decodeIfPresent(String.self, forKey: .fileURL)
}
}
/// 素材库整数读取器,兼容整数字符串并拒绝布尔、分数和任意文本。
private struct DroneDockMaterialInteger: 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 enum DroneDockMaterialURL {
/// 拒绝空值、空白字符、本地地址和无主机的 URL。
static func preview(_ value: String?) -> URL? {
guard let value, !value.isEmpty,
value.rangeOfCharacter(from: .whitespacesAndNewlines) == nil,
let url = URL(string: value), let scheme = url.scheme?.lowercased(),
["https", "http"].contains(scheme), let host = url.host, !host.isEmpty else { return nil }
return url
}
}
private extension KeyedDecodingContainer {
/// 素材、任务、点位及成片必须有正整数身份。
func positiveMaterialID(forKey key: Key) throws -> Int {
let value = try decode(DroneDockMaterialInteger.self, forKey: key).value
guard value > 0 else {
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "素材库 ID 必须为正整数")
}
return value
}
/// 可选关联身份在提供值时仍要求正整数。
func optionalPositiveMaterialID(forKey key: Key) throws -> Int? {
guard let value = try optionalMaterialInteger(forKey: key) else { return nil }
guard value > 0 else {
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "素材库关联 ID 必须为正整数")
}
return value
}
/// 状态码不限定已知枚举,缺失或 null 保留未知。
func optionalMaterialInteger(forKey key: Key) throws -> Int? {
try decodeIfPresent(DroneDockMaterialInteger.self, forKey: key)?.value
}
/// 文件大小可缺失,但不能出现负字节数。
func optionalMaterialSize(forKey key: Key) throws -> Int? {
let value = try optionalMaterialInteger(forKey: key)
if let value, value < 0 {
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "素材大小不能为负数")
}
return value
}
/// 保留订单号前导零,禁止缺失或带首尾空白的身份。
func materialOrderNumber(forKey key: Key) throws -> String {
let value = try decode(String.self, forKey: key)
guard !value.isEmpty, value == value.trimmingCharacters(in: .whitespacesAndNewlines) else {
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "订单号必须为有效非空字符串")
}
return value
}
}
@@ -0,0 +1,166 @@
import Foundation
/// 订单素材库的远程状态,整单摘要与点位筛选后的任务分别维护。
final class DroneDockMaterialsViewModel {
/// 进入页面时冻结的账号、景区和门店范围。
let context: DroneDockHomeContext
/// 入口订单仅提供身份和首次读取前的摘要。
let order: DroneDockHomeOrder
/// orders/detail 返回的整单摘要与购买点位。
private(set) var detail: DroneDockMaterialDetail?
/// 当前点位下的全部有效任务,保持服务端顺序。
private(set) var tasks: [DroneDockMaterialTask] = []
/// 当前筛选下的任务数,未知时不以零代替。
private(set) var total: Int?
/// 当前点位,nil 表示全部点位。
private(set) var selectedSpotID: Int?
/// 是否正在读取整单摘要和点位标签。
private(set) var isLoading = false
/// 是否正在读取全部或指定点位的任务。
private(set) var isLoadingTasks = false
/// 整单摘要、入口参数或会话范围错误。
private(set) var detailErrorMessage: String?
/// 当前任务列表读取错误,不改变已读取的整单摘要。
private(set) var tasksErrorMessage: String?
/// 点位标签始终来自整单购买快照,不从当前任务推导。
var spots: [DroneDockMaterialSpot] { detail?.spots ?? [] }
private let service: any DroneDockMaterialsServing
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
/// 注入只读素材服务和会话校验器,不依赖应用全局登录态。
init(context: DroneDockHomeContext, order: DroneDockHomeOrder,
service: any DroneDockMaterialsServing,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.order = order
self.service = service
self.currentContext = currentContext
}
/// 先刷新整单摘要,再读取任务;保留仍在购买快照中的点位筛选。
@MainActor
func refresh() async {
generation &+= 1
let requestGeneration = generation
detail = nil
clearTasks()
isLoading = true
isLoadingTasks = false
detailErrorMessage = nil
defer { if generation == requestGeneration { isLoading = false } }
guard await accepts(requestGeneration) else { return }
guard context.canLoad, let number = orderNumber else {
selectedSpotID = nil
detailErrorMessage = "缺少当前景区、门店或订单信息,请返回工作台重新进入"
return
}
do {
let value = try await service.detail(scenicID: context.scenicID, orderNumber: number)
guard await accepts(requestGeneration) else { return }
guard value.order.orderNumber == number else {
selectedSpotID = nil
detailErrorMessage = "素材库摘要与当前订单不一致,请刷新重试"
return
}
detail = value
if let selectedSpotID, !value.spots.contains(where: { $0.id == selectedSpotID }) {
self.selectedSpotID = nil
}
isLoading = false
await loadTasks(requestGeneration: requestGeneration, orderNumber: number)
} catch {
guard await accepts(requestGeneration) else { return }
selectedSpotID = nil
detailErrorMessage = Self.message(for: error)
}
}
/// 切换购买点位时只刷新 tasks,整单次数、状态和标签保持不变。
@MainActor
func selectSpot(id: Int?) async {
guard !isLoading, detail != nil, id != selectedSpotID,
id == nil || spots.contains(where: { $0.id == id }) else { return }
generation &+= 1
selectedSpotID = id
clearTasks()
guard let number = orderNumber else { return }
await loadTasks(requestGeneration: generation, orderNumber: number)
}
/// 任务读取失败后重试当前点位,不重复请求整单摘要。
@MainActor
func retryTasks() async {
guard !isLoading, !isLoadingTasks, detail != nil, let number = orderNumber else { return }
generation &+= 1
clearTasks()
await loadTasks(requestGeneration: generation, orderNumber: number)
}
/// 离开页面时清除敏感内容,并使所有在途响应失效。
@MainActor
func invalidate() {
generation &+= 1
detail = nil
selectedSpotID = nil
clearTasks()
isLoading = false
isLoadingTasks = false
detailErrorMessage = nil
}
private var orderNumber: String? {
guard let number = order.orderNumber, !number.isEmpty,
number == number.trimmingCharacters(in: .whitespacesAndNewlines) else { return nil }
return number
}
@MainActor
private func loadTasks(requestGeneration: Int, orderNumber: String) async {
let requestedSpotID = selectedSpotID
isLoadingTasks = true
tasksErrorMessage = nil
defer { if generation == requestGeneration { isLoadingTasks = false } }
guard await accepts(requestGeneration) else { return }
do {
let value = try await service.tasks(scenicID: context.scenicID, orderNumber: orderNumber, spotID: requestedSpotID)
guard await accepts(requestGeneration) else { return }
guard value.orderNumber == orderNumber, value.total == value.list.count,
value.list.allSatisfy({ $0.orderNumber == orderNumber && (requestedSpotID == nil || $0.spotID == requestedSpotID) }) else {
clearTasks()
tasksErrorMessage = "素材任务与当前订单或拍摄点不一致,请刷新重试"
return
}
tasks = value.list
total = value.total
} catch {
guard await accepts(requestGeneration) else { return }
clearTasks()
tasksErrorMessage = Self.message(for: error)
}
}
@MainActor
private func accepts(_ requestGeneration: Int) async -> Bool {
guard generation == requestGeneration, !Task.isCancelled else { return false }
let latest = currentContext()
guard context.hasSameIdentity(as: latest) else {
invalidate()
detailErrorMessage = "账号或景区已变化,请返回工作台重新进入"
return false
}
return true
}
@MainActor
private func clearTasks() {
tasks = []
total = nil
tasksErrorMessage = nil
}
private static func message(for error: Error) -> String? {
error is CancellationError ? nil : error.localizedDescription
}
}
@@ -7,6 +7,7 @@ final class DroneDockHomeViewController: BaseViewController {
let viewModel: DroneDockHomeViewModel
private let paymentControllerFactory: (() -> UIViewController)?
private let preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)?
private let materialsControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)?
private var refreshTask: Task<Void, Never>?
private var loadMoreTask: Task<Void, Never>?
private var isRefreshing = false
@@ -32,10 +33,12 @@ final class DroneDockHomeViewController: BaseViewController {
/// 注入可测试的数据源,不加载演示数据。
init(viewModel: DroneDockHomeViewModel, paymentControllerFactory: (() -> UIViewController)? = nil,
preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
preparationControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
materialsControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
self.viewModel = viewModel
self.paymentControllerFactory = paymentControllerFactory
self.preparationControllerFactory = preparationControllerFactory
self.materialsControllerFactory = materialsControllerFactory
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@@ -155,9 +158,9 @@ final class DroneDockHomeViewController: BaseViewController {
if let order = self.viewModel.orders.first(where: { $0.orderID == id }) {
cell.apply(homeOrder: order)
cell.onShootingTap = { [weak self] in
self?.openPreparation(orderID: id)
self?.openPrimaryAction(orderID: id)
}
cell.onMaterialsTap = { [weak self] in self?.showUnavailable("订单素材") }
cell.onMaterialsTap = { [weak self] in self?.openMaterials(orderID: id) }
}
return cell
}
@@ -292,7 +295,8 @@ final class DroneDockHomeViewController: BaseViewController {
private func openAllOrders() {
let controller = DroneDockOrdersViewController(
viewModel: viewModel.makeOrdersViewModel(), preparationControllerFactory: preparationFactory)
viewModel: viewModel.makeOrdersViewModel(), preparationControllerFactory: preparationFactory,
materialsControllerFactory: materialsFactory)
navigationController?.pushViewController(controller, animated: true)
}
@@ -307,8 +311,32 @@ final class DroneDockHomeViewController: BaseViewController {
}
}
private func openPreparation(orderID: String) {
/// 首页和全部订单页复用同一真实素材入口,进入页面后才读取摘要和任务。
private var materialsFactory: (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController {
materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
service: DroneDockMaterialsAPI(client: NetworkServices.shared.apiClient),
currentContext: { Self.currentContext() }
))
}
}
private func openMaterials(orderID: String) {
guard !isRefreshing, let order = viewModel.orders.first(where: { $0.orderID == orderID }) else { return }
guard DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
showAlert(title: "订单素材库", message: "缺少订单号,请刷新工作台后重试")
return
}
navigationController?.pushViewController(materialsFactory(order, viewModel.context), animated: true)
}
private func openPrimaryAction(orderID: String) {
guard !isRefreshing, let order = viewModel.orders.first(where: { $0.orderID == orderID }) else { return }
if order.primaryAction == "view_materials" {
openMaterials(orderID: orderID)
return
}
guard order.primaryAction == "start_shoot" else {
showUnavailable(order.actionTitle ?? "拍摄订单")
return
@@ -0,0 +1,444 @@
import AVKit
import Kingfisher
import SnapKit
import UIKit
/// 从订单详情与任务接口读取的素材库,点位筛选只改变任务列表。
@MainActor
final class DroneDockMaterialsViewController: BaseViewController {
/// 保存当前订单摘要、点位和任务的真实状态。
let viewModel: DroneDockMaterialsViewModel
/// 元数据与媒体分区独立,任务没有素材时也保留其状态。
private enum Section: Hashable { case order, filters, summary, task(Int), media(Int), message }
/// 素材 ID 只在所属任务内唯一,使用任务 ID 共同构成稳定身份。
private enum Item: Hashable {
case order, filter(Int?), summary, task(Int), file(Int, Int), film(Int, Int), message
}
/// 整页刷新更新两个接口;筛选及列表重试只读取任务。
private enum LoadAction { case refresh, filter(Int?), retry }
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var loadTask: Task<Void, Never>?
private var operation: LoadAction?
private var hasAppeared = false
/// 注入冻结订单范围的只读素材服务。
init(viewModel: DroneDockMaterialsViewModel) {
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 { loadTask?.cancel() }
override func setupNavigationBar() {
title = "订单素材库"
navigationItem.backButtonDisplayMode = .minimal
let refresh = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshTapped))
refresh.accessibilityIdentifier = "drone.materials.remote.refresh"
navigationItem.rightBarButtonItem = refresh
}
override func setupUI() {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.accessibilityIdentifier = "drone.materials.remote.list"
collectionView.delegate = self
collectionView.register(DroneDockMaterialTextCell.self, forCellWithReuseIdentifier: "text")
collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "filter")
collectionView.register(DroneDockMaterialMediaCell.self, forCellWithReuseIdentifier: "media")
let refresh = UIRefreshControl()
refresh.tintColor = DroneDockStyle.primary
refresh.addTarget(self, action: #selector(refreshTapped), 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)
guard !hasAppeared else { return }
hasAppeared = true
load(.refresh)
}
/// 确认离开后再清理;交互式返回取消或媒体预览覆盖不会丢失当前数据。
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true || parent == nil else { return }
hasAppeared = false
loadTask?.cancel()
operation = nil
viewModel.invalidate()
collectionView.refreshControl?.endRefreshing()
}
private var displayedSpotID: Int? {
if case .filter(let id) = operation { return id }
return viewModel.selectedSpotID
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] collection, path, item in
guard let self else { return nil }
switch item {
case .filter(let id):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "filter", for: path) as! DroneMaterialFilterCell
let title = id.flatMap { id in self.viewModel.spots.first { $0.id == id } }.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位"
cell.apply(title: title, id: id.map(String.init), selected: id == self.displayedSpotID, locked: self.viewModel.detail == nil)
return cell
case .file(let taskID, let fileID):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell
if let file = self.task(taskID)?.materials.first(where: { $0.id == fileID }) {
cell.apply(file: file, taskID: taskID)
}
return cell
case .film(let taskID, _):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell
if let film = self.task(taskID)?.film { cell.apply(film: film, taskID: taskID) }
return cell
default:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! DroneDockMaterialTextCell
self.configureText(cell, item: item)
return cell
}
}
}
private func configureText(_ cell: DroneDockMaterialTextCell, item: Item) {
switch item {
case .order:
guard let order = viewModel.detail?.order else { return }
cell.apply(title: order.touristTitle, body: "\(order.orderNumberText)\n\(order.packageTitle) · \(order.statusTitle)\n\(order.progressTitle)", identifier: "drone.materials.remote.order")
case .summary:
let text = viewModel.total.map { "\($0) 条任务记录 · 最新在前" } ?? "任务记录"
cell.apply(title: text, body: nil, identifier: "drone.materials.remote.summary", compact: true)
case .task(let id):
guard let task = task(id) else { return }
let number = task.sequence.map { "任务 \($0)" } ?? "任务 \(id)"
let title = "\(number) · \(Self.usable(task.spotName, fallback: "点位 \(task.spotID)"))"
var lines = ["\(Self.usable(task.airLineName, fallback: "航线待确认")) · \(Self.flightTitle(task.flightStatus))",
Self.usable(task.createdAt, fallback: "时间待确认")]
if task.materials.isEmpty { lines.append("暂无原素材") }
if task.film == nil { lines.append("暂无视频成片") }
cell.apply(title: title, body: lines.joined(separator: "\n"), identifier: "drone.materials.remote.task.\(id)")
case .message:
if operation != nil || viewModel.isLoading || viewModel.isLoadingTasks {
cell.apply(title: viewModel.detail == nil ? "正在加载订单素材库" : "正在加载任务素材", body: nil, identifier: "drone.materials.remote.loading")
} else if let error = viewModel.detailErrorMessage {
cell.apply(title: "订单信息加载失败", body: error, identifier: "drone.materials.remote.error", button: "重试", actionID: "drone.materials.remote.retry") { [weak self] in self?.load(.refresh) }
} else if let error = viewModel.tasksErrorMessage {
cell.apply(title: "任务素材加载失败", body: error, identifier: "drone.materials.remote.error", button: "重试", actionID: "drone.materials.remote.retry") { [weak self] in self?.load(.retry) }
} else {
cell.apply(title: displayedSpotID == nil ? "暂无任务记录" : "当前点位暂无任务记录", body: "拍摄任务与素材更新后,可下拉刷新查看", identifier: "drone.materials.remote.empty")
}
default: break
}
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, environment in
guard let self, let dataSource = self.dataSource else { return nil }
let sections = dataSource.snapshot().sectionIdentifiers
guard sections.indices.contains(index) else { return nil }
switch sections[index] {
case .filters:
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .estimated(104), heightDimension: .absolute(36)), subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .continuous
section.interGroupSpacing = 8
section.contentInsets = .init(top: 0, leading: 16, bottom: 8, trailing: 16)
return section
case .media:
let width = (environment.container.effectiveContentSize.width - 44) / 2
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 0.57 + 72)), repeatingSubitem: item, count: 2)
group.interItemSpacing = .fixed(12)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 0, leading: 16, bottom: 16, trailing: 16)
section.interGroupSpacing = 12
return section
default:
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .estimated(80)))
let group = NSCollectionLayoutGroup.vertical(layoutSize: item.layoutSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 0, leading: 16, bottom: 0, trailing: 16)
return section
}
}
}
private func applySnapshot(animated: Bool) {
guard dataSource != nil else { return }
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
if viewModel.detail != nil {
snapshot.appendSections([.order, .filters])
snapshot.appendItems([.order], toSection: .order)
snapshot.appendItems([.filter(nil)] + viewModel.spots.map { .filter($0.id) }, toSection: .filters)
}
if operation == nil && !viewModel.isLoading && !viewModel.isLoadingTasks && viewModel.tasksErrorMessage == nil && viewModel.detailErrorMessage == nil && viewModel.total != nil {
snapshot.appendSections([.summary])
snapshot.appendItems([.summary], toSection: .summary)
for task in viewModel.tasks {
snapshot.appendSections([.task(task.id)])
snapshot.appendItems([.task(task.id)], toSection: .task(task.id))
var media = task.materials.map { Item.file(task.id, $0.id) }
if let film = task.film { media.append(.film(task.id, film.id)) }
if !media.isEmpty {
snapshot.appendSections([.media(task.id)])
snapshot.appendItems(media, toSection: .media(task.id))
}
}
}
if viewModel.tasks.isEmpty || operation != nil || viewModel.isLoading || viewModel.isLoadingTasks || viewModel.detailErrorMessage != nil || viewModel.tasksErrorMessage != nil {
snapshot.appendSections([.message])
snapshot.appendItems([.message], toSection: .message)
}
let previous = Set(dataSource.snapshot().itemIdentifiers)
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) })
dataSource.apply(snapshot, animatingDifferences: animated)
}
private func load(_ action: LoadAction) {
loadTask?.cancel()
operation = action
applySnapshot(animated: false)
loadTask = Task { @MainActor [weak self] in
guard let self else { return }
switch action {
case .refresh: await self.viewModel.refresh()
case .filter(let id): await self.viewModel.selectSpot(id: id)
case .retry: await self.viewModel.retryTasks()
}
guard !Task.isCancelled else { return }
self.operation = nil
self.collectionView.refreshControl?.endRefreshing()
self.applySnapshot(animated: true)
}
}
@objc private func refreshTapped() { load(.refresh) }
private func task(_ id: Int) -> DroneDockMaterialTask? { viewModel.tasks.first { $0.id == id } }
private func preview(url: URL, isVideo: Bool, title: String) {
if isVideo {
let player = AVPlayerViewController()
player.player = AVPlayer(url: url)
present(player, animated: true) { player.player?.play() }
} else {
navigationController?.pushViewController(DroneDockMaterialImageViewController(url: url, title: title), animated: true)
}
}
private static func usable(_ value: String?, fallback: String) -> String {
DroneDockHomeMetric.usableText(value) ?? fallback
}
private static func flightTitle(_ status: Int?) -> String {
switch status {
case 10: "待飞行"
case 20: "执行中"
case 30: "飞行成功"
case 40: "飞行失败"
case 50: "已取消"
case 60: "待确认"
default: "飞行状态待确认"
}
}
}
extension DroneDockMaterialsViewController: UICollectionViewDelegate {
/// 点位只重读任务;仅已就绪且有合法地址的媒体可进入真实预览。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .filter(let id):
guard viewModel.detail != nil, id != displayedSpotID else { return }
load(.filter(id))
case .file(let taskID, let fileID):
guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return }
preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材")
case .film(let taskID, _):
guard operation == nil, let film = task(taskID)?.film, let url = film.previewURL else { return }
preview(url: url, isVideo: true, title: film.fileName ?? "视频成片")
default: break
}
}
}
/// 摘要、任务状态及可恢复错误共用的自适应文字行。
@MainActor
private final class DroneDockMaterialTextCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 15, weight: .semibold)
private let bodyLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let button = UIButton(type: .system)
private var action: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.numberOfLines = 0
bodyLabel.numberOfLines = 0
let stack = UIStackView(arrangedSubviews: [titleLabel, bodyLabel, button])
stack.axis = .vertical
stack.spacing = 8
stack.alignment = .leading
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 14, left: 0, bottom: 16, right: 0)) }
titleLabel.snp.makeConstraints { $0.width.equalTo(stack) }
bodyLabel.snp.makeConstraints { $0.width.equalTo(stack) }
button.tintColor = DroneDockStyle.primary
button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 切换内容时同时清除复用单元的旧操作。
func apply(title: String, body: String?, identifier: String, compact: Bool = false,
button buttonTitle: String? = nil, actionID: String? = nil, action: (() -> Void)? = nil) {
titleLabel.text = title
titleLabel.font = .systemFont(ofSize: compact ? 13 : 15, weight: .semibold)
bodyLabel.text = body
bodyLabel.isHidden = body == nil
button.isHidden = buttonTitle == nil
button.setTitle(buttonTitle, for: .normal)
button.accessibilityIdentifier = actionID
self.action = action
accessibilityIdentifier = identifier
}
@objc private func tapped() { action?() }
}
/// 加载远程缩略图并明确区分原素材、视频成片及不可预览状态。
@MainActor
private final class DroneDockMaterialMediaCell: UICollectionViewCell {
private let thumbnail = UIImageView()
private let icon = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 12, weight: .medium)
private let stateLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
thumbnail.contentMode = .scaleAspectFill
thumbnail.clipsToBounds = true
thumbnail.layer.cornerRadius = 8
thumbnail.backgroundColor = DroneDockStyle.background
icon.tintColor = DroneDockStyle.secondary
icon.contentMode = .scaleAspectFit
titleLabel.numberOfLines = 2
stateLabel.numberOfLines = 2
[thumbnail, icon, titleLabel, stateLabel].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(thumbnail.snp.width).multipliedBy(0.57) }
icon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(28) }
titleLabel.snp.makeConstraints { make in make.top.equalTo(thumbnail.snp.bottom).offset(8); make.leading.trailing.equalToSuperview() }
stateLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(4); make.leading.trailing.equalToSuperview(); make.bottom.lessThanOrEqualToSuperview() }
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func prepareForReuse() {
super.prepareForReuse()
thumbnail.kf.cancelDownloadTask()
thumbnail.image = nil
}
/// 未就绪的原素材仍显示服务端状态,但不会启动播放或下载。
func apply(file: DroneDockMaterialFile, taskID: Int) {
let state: String
switch file.uploadStatus {
case 0: state = "待上传"
case 1: state = file.previewURL == nil ? "暂不可预览" : (file.fileType == 2 ? "点击播放" : "点击预览")
case 2: state = "上传中"
case 3: state = "上传失败"
default: state = "素材状态待确认"
}
let kind = file.fileType == 1 ? "图片" : file.fileType == 2 ? "视频" : "文件"
let title = DroneDockHomeMetric.usableText(file.fileName) ?? "原素材 \(file.id)"
apply(title: title, state: "原素材 · \(kind) · \(state)", cover: file.coverURL,
fallback: file.fileType == 1 ? file.previewURL : nil, video: file.fileType == 2,
enabled: file.previewURL != nil, identifier: "drone.materials.remote.file.\(taskID).\(file.id)")
accessibilityHint = file.uploadStatus == 3 ? DroneDockHomeMetric.usableText(file.failureReason) : nil
}
/// 成片是任务中的独立视频,不混入原素材数量或上传状态。
func apply(film: DroneDockMaterialFilm, taskID: Int) {
apply(title: DroneDockHomeMetric.usableText(film.fileName) ?? "视频成片", state: "视频成片 · \(film.previewURL == nil ? "暂不可预览" : "点击播放")",
cover: film.coverURL, fallback: nil, video: true, enabled: film.previewURL != nil,
identifier: "drone.materials.remote.film.\(taskID).\(film.id)")
accessibilityHint = nil
}
private func apply(title: String, state: String, cover: String?, fallback: URL?, video: Bool, enabled: Bool, identifier: String) {
thumbnail.kf.cancelDownloadTask()
thumbnail.image = nil
let coverURL = cover.flatMap(URL.init(string:)).flatMap { url in
["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil ? url : nil
}
thumbnail.kf.setImage(with: coverURL ?? fallback)
icon.image = UIImage(systemName: video && enabled ? "play.circle.fill" : video ? "video" : "photo")
icon.isHidden = !video && (coverURL ?? fallback) != nil
titleLabel.text = title
stateLabel.text = state
accessibilityIdentifier = identifier
accessibilityLabel = "\(title),\(state)"
accessibilityTraits = enabled ? .button : [.notEnabled]
}
}
/// 通过 Kingfisher 展示真实图片,加载失败保留明确提示。
@MainActor
private final class DroneDockMaterialImageViewController: UIViewController {
private let url: URL
private let imageView = UIImageView()
private let message = UILabel()
/// 仅接收素材模型已经校验可预览的 HTTP(S) 地址。
init(url: URL, title: String) {
self.url = url
super.init(nibName: nil, bundle: nil)
self.title = title
hidesBottomBarWhenPushed = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
imageView.contentMode = .scaleAspectFit
imageView.accessibilityIdentifier = "drone.materials.remote.preview.image"
message.text = "正在加载图片"
message.textColor = .white
message.textAlignment = .center
message.numberOfLines = 0
view.addSubview(imageView)
view.addSubview(message)
imageView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
message.snp.makeConstraints { make in make.center.equalToSuperview(); make.leading.trailing.equalToSuperview().inset(24) }
imageView.kf.setImage(with: url) { [weak self] result in
switch result {
case .success: self?.message.isHidden = true
case .failure: self?.message.text = "图片加载失败,请返回后重试"
}
}
}
}
@@ -7,6 +7,7 @@ final class DroneDockOrdersViewController: BaseViewController {
/// 与首页共享接口及身份范围、独立维护分页的列表状态。
let viewModel: DroneDockOrdersViewModel
private let preparationControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private let materialsControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private let countLabel = DroneDockStyle.label(size: 17, weight: .semibold)
private let descriptionLabel = DroneDockStyle.label("分配给我的全部订单,含已完成订单", size: 12, color: DroneDockStyle.secondary)
private let filterView = DroneShootingOrderFilterView()
@@ -20,11 +21,13 @@ final class DroneDockOrdersViewController: BaseViewController {
/// 刷新替换整页,翻页保留已加载订单。
private enum LoadAction: Equatable { case refresh, more, filter(DroneShootingOrderFilter) }
/// 注入真实订单服务及与首页一致的拍摄准备入口。
/// 注入真实订单服务及与首页一致的拍摄准备、素材库入口。
init(viewModel: DroneDockOrdersViewModel,
preparationControllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController) {
preparationControllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController,
materialsControllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController) {
self.viewModel = viewModel
self.preparationControllerFactory = preparationControllerFactory
self.materialsControllerFactory = materialsControllerFactory
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@@ -106,7 +109,7 @@ final class DroneDockOrdersViewController: BaseViewController {
cell.accessibilityIdentifier = "drone.orders.order.\(id)"
cell.cardView.apply(homeOrder: order)
cell.cardView.onShootingTap = { [weak self] in self?.openPreparation(orderID: id) }
cell.cardView.onMaterialsTap = { [weak self] in self?.showUnavailable("订单素材") }
cell.cardView.onMaterialsTap = { [weak self] in self?.openMaterials(orderID: id) }
cell.cardView.onDeliveryTap = { [weak self] in self?.showUnavailable("交付成片") }
cell.cardView.onConfirmationTap = { [weak self] in self?.showUnavailable("交付确认") }
}
@@ -198,6 +201,15 @@ final class DroneDockOrdersViewController: BaseViewController {
private func showUnavailable(_ feature: String) { showAlert(title: feature, message: "该功能暂未开放") }
private func openMaterials(orderID: String) {
guard operation == nil, let order = viewModel.orders.first(where: { $0.orderID == orderID }) else { return }
guard DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
showAlert(title: "订单素材库", message: "缺少订单号,请刷新拍摄订单后重试")
return
}
navigationController?.pushViewController(materialsControllerFactory(order, viewModel.context), animated: true)
}
@objc private func refreshTriggered() { load(.refresh) }
}