feat: 完善机巢模拟调试与素材交付交互

增加禁飞期间的设备指令拦截及本地模拟拍摄流程;适配订单素材库和景区空境库,完善素材筛选、预览与下载;订单交付入口改为方式选择弹窗并复用云端上传。补充单元测试、接口记录和模拟器截图。
This commit is contained in:
2026-10-30 09:59:11 +08:00
parent e827bf8725
commit b95b251de1
100 changed files with 7256 additions and 500 deletions
+8 -1
View File
@@ -11,6 +11,9 @@ protocol URLSessionProtocol {
func data(for request: URLRequest) async throws -> (Data, URLResponse)
}
/// 仅供完全在内存中返回预设响应的传输实现,不得转发至 URLSession 或外部服务。
protocol LocalSimulationURLSession: URLSessionProtocol {}
extension URLSession: URLSessionProtocol {}
@MainActor
@@ -63,7 +66,9 @@ final class APIClient {
_ apiRequest: APIRequest<Response>,
tokenOverride: String? = nil
) async throws -> Response {
let request = try makeURLRequest(apiRequest, tokenOverride: tokenOverride)
let request = try DeviceCommandDebugPolicy.prepare(
makeURLRequest(apiRequest, tokenOverride: tokenOverride),
isLocalSimulation: session is any LocalSimulationURLSession)
logRequest(request, includeBody: apiRequest.logsPayload)
let data: Data
@@ -120,6 +125,7 @@ final class APIClient {
}
request.httpBody = jsonBody.data(using: .utf8)
request = try DeviceCommandDebugPolicy.prepare(request, isLocalSimulation: session is any LocalSimulationURLSession)
logRequest(request)
let data: Data
@@ -191,6 +197,7 @@ final class APIClient {
request.setValue(token, forHTTPHeaderField: "token")
}
request.httpBody = body
request = try DeviceCommandDebugPolicy.prepare(request, isLocalSimulation: session is any LocalSimulationURLSession)
logRequest(request)
let responseData: Data
@@ -0,0 +1,55 @@
import Foundation
/// 禁飞期间的 Debug 请求边界;模拟器和测试环境均不能视为没有真实设备副作用。
enum DeviceCommandDebugPolicy {
/// 所有 Debug 构建禁止真实设备操作,没有启动参数或设置开关可临时放行。
static var blocksLiveRequests: Bool {
#if DEBUG
true
#else
false
#endif
}
/// 页面与本地拦截共用的说明,不将未发送的请求表述为服务端执行失败。
static let blockedMessage = "当前禁止真实设备指令,请使用本地模拟调试"
/// 在日志和传输之前阻断操作请求;允许的状态读取关闭实时设备采集。
static func prepare(_ request: URLRequest, isLocalSimulation: Bool) throws -> URLRequest {
guard blocksLiveRequests, !isLocalSimulation, let url = request.url else { return request }
let path = "/" + url.path.split(separator: "/").joined(separator: "/")
// 创建虽不直接起飞,但会改变真实订单状态;禁飞调试使用本地待飞任务。
if path == "/api/yf-handset-app/photog/multi-plane/tasks/create" {
throw DeviceCommandDebugBlockedError()
}
guard path == "/api/app/airport" || path.hasPrefix("/api/app/airport/") else { return request }
let readablePaths: Set<String> = [
"/api/app/airport/home", "/api/app/airport/plane-status",
"/api/app/airport/shooting", "/api/app/airport/status"
]
guard request.httpMethod == "GET", readablePaths.contains(path) else {
throw DeviceCommandDebugBlockedError()
}
let liveKey: String
switch path {
case "/api/app/airport/plane-status", "/api/app/airport/shooting": liveKey = "live_battery"
case "/api/app/airport/status": liveKey = "live_metrics"
default: return request
}
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { throw APIError.invalidURL }
var items = components.queryItems ?? []
items.removeAll { $0.name == liveKey }
items.append(URLQueryItem(name: liveKey, value: "0"))
components.queryItems = items
guard let safeURL = components.url else { throw APIError.invalidURL }
var safeRequest = request
safeRequest.url = safeURL
return safeRequest
}
}
/// 明确表示请求在本机被阻断,任何设备指令或任务创建都未发送。
struct DeviceCommandDebugBlockedError: Error, LocalizedError {
/// 提示使用本地模拟,不伪造后端错误码或成功回执。
var errorDescription: String? { DeviceCommandDebugPolicy.blockedMessage }
}
@@ -0,0 +1,39 @@
import Foundation
/// 朱工开始拍摄服务,只使用已创建并召唤的订单飞行任务身份。
protocol DroneDockStartShooting: Sendable {
/// 提交一次开拍请求;调用方负责校验执行门禁并阻止重复提交。
@MainActor
func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse
}
/// start-shoot 合同适配;禁飞期间真实传输仍由统一客户端阻断,仅用 Mock 验证。
@MainActor
final class DroneDockStartShootAPI: DroneDockStartShooting {
private let client: APIClient
/// 注入统一客户端,测试使用不会联网的本地模拟传输。
init(client: APIClient) { self.client = client }
/// 仅 POST 任务 ID,不附带飞机、航线或未约定的模拟参数,也不自动重试。
func startShooting(taskID: Int) async throws -> DroneDockStartShootResponse {
try Task.checkCancellation()
guard taskID > 0 else { throw APIError.networkFailed("缺少有效拍摄任务 ID,请返回任务页确认") }
let response: DroneDockStartShootResponse = try await client.send(APIRequest(
method: .post, path: "/api/app/airport/start-shoot", body: StartShootBody(taskID: taskID)
))
guard let returnedID = response.orderFlightTaskID, returnedID > 0, returnedID == taskID,
response.orderFlightTask?.id == nil || response.orderFlightTask?.id == taskID else {
throw APIError.decodeFailed("开始拍摄回执的任务身份缺失或不一致,请核对原任务状态")
}
return response
}
/// 开拍只提交订单飞行任务身份,不使用航线任务 ID。
private struct StartShootBody: Encodable {
let taskID: Int
/// 朱工开拍请求的 JSON 字段。
private enum CodingKeys: String, CodingKey { case taskID = "id" }
}
}
@@ -0,0 +1,9 @@
import Foundation
/// 原素材的选择身份;文件 ID 只在所属任务内唯一,成片不计入原素材选择。
struct DroneDockMaterialSelectionID: Hashable, Sendable {
/// 所属订单飞行任务。
let taskID: Int
/// 任务中的原素材 ID。
let fileID: Int
}
@@ -22,7 +22,7 @@ struct DroneDockShootingResponse: Decodable, Equatable, Sendable {
let metrics: [DroneDockHomeMetric]
/// 景区设备连接与轮询建议,不在客户端改选推荐飞机。
let planeStatus: DroneDockShootingPlaneStatus?
/// 服务端执行门禁只用于展示,本次接入不执行其动作。
/// 执行门禁参与展示及本地模拟开拍校验,不能解除真实飞控禁令。
let executeGate: DroneDockShootingExecuteGate?
/// 服务端拍摄阶段和页面提示。
let ui: DroneDockShootingUI?
@@ -169,7 +169,7 @@ struct DroneDockShootingExecuteGate: Decodable, Equatable, Sendable {
let code: String?
/// 服务端门禁说明。
let message: String?
/// 服务端建议动作,本阶段仅展示。
/// 服务端建议动作;本地模拟开拍要求明确为 start_shoot。
let primaryAction: String?
/// 服务端建议动作名称。
let primaryActionLabel: String?
@@ -0,0 +1,58 @@
import Foundation
/// start-shoot 的受理回执;不凭请求成功推断飞行、拍摄或素材已完成。
struct DroneDockStartShootResponse: Decodable, Equatable, Sendable {
/// 文档约定的订单飞行任务 ID,API 必须核对其与请求一致。
let orderFlightTaskID: Int?
/// 服务端提供的任务摘要,嵌套身份存在时同样参与核对。
let orderFlightTask: DroneDockShootingTaskIdentity?
/// 当前任务锁定的飞机,不由客户端选择或覆盖。
let planeID: Int?
/// 服务端任务 UUID,用于后续核对,不等于订单飞行任务 ID。
let taskUUID: String?
/// 服务端返回的机场标识,仅保留已有值。
let airportSN: String?
/// 服务端受理后的阶段文案,最新设备状态由 shooting 单次回查确认。
let ui: DroneDockShootingUI?
/// 完整 data 的格式化 JSON,保留未知字段与原始类型供模拟联调展示。
let dataJSON: String
/// 朱工开拍回执字段映射。
private enum CodingKeys: String, CodingKey {
case orderFlightTaskID = "order_flight_task_id", orderFlightTask = "order_flight_task"
case planeID = "plane_id", taskUUID = "task_uuid", airportSN = "airport_sn", ui
}
/// 仅解析响应实际提供的字段,不补造任务身份或成功状态。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
orderFlightTaskID = try container.decodeIfPresent(Int.self, forKey: .orderFlightTaskID)
orderFlightTask = try container.decodeIfPresent(DroneDockShootingTaskIdentity.self, forKey: .orderFlightTask)
planeID = try container.decodeIfPresent(Int.self, forKey: .planeID)
taskUUID = try container.decodeIfPresent(String.self, forKey: .taskUUID)
airportSN = try container.decodeIfPresent(String.self, forKey: .airportSN)
ui = try container.decodeIfPresent(DroneDockShootingUI.self, forKey: .ui)
let raw = try DroneDockHomeJSONValue(from: decoder)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
dataJSON = String(decoding: try encoder.encode(DroneDockStartShootJSONSnapshot(value: raw)), as: UTF8.self)
}
}
/// 将已有 JSON 值完整格式化,不给模拟响应添加后端未提供的字段。
private struct DroneDockStartShootJSONSnapshot: Encodable {
let value: DroneDockHomeJSONValue
/// 保留字符串、数字、布尔、空值和嵌套对象,不追加业务码包裹。
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch value {
case .object(let object): try container.encode(object.mapValues { DroneDockStartShootJSONSnapshot(value: $0) })
case .array(let array): try container.encode(array.map { DroneDockStartShootJSONSnapshot(value: $0) })
case .string(let text): try container.encode(text)
case .number(let number): try container.encode(number)
case .bool(let flag): try container.encode(flag)
case .null: try container.encodeNil()
}
}
}
@@ -26,11 +26,11 @@ enum DroneDockTaskDisplayPhase: String, Equatable, Sendable {
case readError
}
/// 任务状态区可呈现的动作;开始与恢复在本轮仅禁用展示,不发送飞控。
/// 任务状态区可呈现的动作;开始仅在明确注入本地模拟服务时可用,真实飞控保持禁用。
enum DroneDockTaskDisplayAction: Equatable, Sendable {
/// 重新读取同一任务。
case refresh
/// 开始拍摄占位动作,本轮禁用。
/// 开始拍摄动作;真实入口无服务,只有本地模拟可提交验证。
case start
/// 恢复拍摄占位动作,本轮禁用。
case resume
@@ -56,7 +56,7 @@ struct DroneDockTaskPresentation: Equatable, Sendable {
let action: DroneDockTaskDisplayAction
/// 主动作名称,无动作时为 nil。
let actionTitle: String?
/// 是否可触发动作;未对接的开始、恢复和重新召唤始终为 false。
/// 是否可触发动作;真实开始、恢复和重新召唤保持禁用。
let isActionEnabled: Bool
/// 主动作下方的真实设备限制说明,未提供时不展示。
let actionNote: String?
@@ -24,6 +24,25 @@ final class DroneDockMaterialsViewModel {
private(set) var tasksErrorMessage: String?
/// 点位标签始终来自整单购买快照,不从当前任务推导。
var spots: [DroneDockMaterialSpot] { detail?.spots ?? [] }
/// 当前范围内已选择的就绪原素材,不包含独立交付成片。
private(set) var selectedMaterialIDs: Set<DroneDockMaterialSelectionID> = []
/// 只有完整读取成功且具备有效文件地址的原素材允许选择。
var selectableMaterialIDs: Set<DroneDockMaterialSelectionID> {
guard detail != nil, !isLoading, !isLoadingTasks,
detailErrorMessage == nil, tasksErrorMessage == nil else { return [] }
return Set(tasks.flatMap { task in
task.materials.filter { $0.previewURL != nil }.map {
DroneDockMaterialSelectionID(taskID: task.id, fileID: $0.id)
}
})
}
/// 当前选择数量仅用于界面展示,不表示已经下载或保存。
var selectedCount: Int { selectedMaterialIDs.count }
/// 空列表不展示全选;全部当前可用原素材被选中时才标记全选。
var allDownloadableSelected: Bool {
let selectable = selectableMaterialIDs
return !selectable.isEmpty && selectedMaterialIDs == selectable
}
private let service: any DroneDockMaterialsServing
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
@@ -39,6 +58,38 @@ final class DroneDockMaterialsViewModel {
self.currentContext = currentContext
}
/// 勾选只修改本地状态;无效、未就绪或其他任务的素材不会进入选择集合。
@MainActor
func toggleSelection(taskID: Int, fileID: Int) {
guard acceptsSelectionContext() else { return }
let identifier = DroneDockMaterialSelectionID(taskID: taskID, fileID: fileID)
guard selectableMaterialIDs.contains(identifier) else { return }
if selectedMaterialIDs.contains(identifier) {
selectedMaterialIDs.remove(identifier)
} else {
selectedMaterialIDs.insert(identifier)
}
}
/// 全选仅覆盖当前点位可用的原素材,不跨点位、订单或成片扩大范围。
@MainActor
func toggleSelectAll() {
guard acceptsSelectionContext() else { return }
let selectable = selectableMaterialIDs
guard !selectable.isEmpty else { return }
selectedMaterialIDs = selectedMaterialIDs == selectable ? [] : selectable
}
@MainActor
private func acceptsSelectionContext() -> Bool {
guard context.hasSameIdentity(as: currentContext()) else {
invalidate()
detailErrorMessage = "账号或景区已变化,请返回工作台重新进入"
return false
}
return true
}
/// 先刷新整单摘要,再读取任务;保留仍在购买快照中的点位筛选。
@MainActor
func refresh() async {
@@ -156,6 +207,7 @@ final class DroneDockMaterialsViewModel {
@MainActor
private func clearTasks() {
tasks = []
selectedMaterialIDs = []
total = nil
tasksErrorMessage = nil
}
@@ -43,6 +43,7 @@ final class DroneDockPreparationViewModel {
private let planeStatusService: any DroneDockPlaneStatusServing
private let taskCreationService: any DroneDockTaskCreating
private let shootService: any DroneDockShootServing
private let allowsTaskSubmission: Bool
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
private var planeStatusGeneration = 0
@@ -62,6 +63,7 @@ final class DroneDockPreparationViewModel {
planeStatusService: any DroneDockPlaneStatusServing,
taskCreationService: any DroneDockTaskCreating,
shootService: any DroneDockShootServing,
allowsTaskSubmission: Bool = true,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.order = order
@@ -69,12 +71,13 @@ final class DroneDockPreparationViewModel {
self.planeStatusService = planeStatusService
self.taskCreationService = taskCreationService
self.shootService = shootService
self.allowsTaskSubmission = allowsTaskSubmission
self.currentContext = currentContext
}
/// 当前阶段只创建待飞任务,不以设备电量或位置作为创建任务条件。
var canCreateTask: Bool {
guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
!hasCreatedTask, !taskCreationOutcomeUnknown, errorMessage == nil,
let info = projectInfo, info.order.canCreateTask == true,
let total = info.order.shotTotal, total > 0,
@@ -86,6 +89,9 @@ final class DroneDockPreparationViewModel {
return info.order.orderNumber == number && info.order.projectID == projectID
}
/// 当前入口是否被禁飞限制禁止提交,用于提供独立模拟入口而不放开真实写入。
var isTaskSubmissionBlocked: Bool { !allowsTaskSubmission }
/// 提交中和已有回执/不确定结果时冻结点位航线,避免显示与任务归属不一致。
var isTaskSelectionLocked: Bool {
isCreatingTask || isSummoning || isPerformingPrimaryAction || hasCreatedTask || taskCreationOutcomeUnknown
@@ -107,7 +113,7 @@ final class DroneDockPreparationViewModel {
/// 首次允许创建再召唤;明确业务拒绝后可对同任务重试,成功和未知结果锁定。
var isPrimaryActionEnabled: Bool {
guard context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
guard allowsTaskSubmission, context.canLoad, !creationContextInvalidated, !isLoading, !isCreatingTask,
!isSummoning, !isPerformingPrimaryAction, !taskCreationOutcomeUnknown,
!hasSubmittedSummon, !summonOutcomeUnknown else { return false }
if let createdTask { return createdTask.taskID > 0 }
@@ -117,7 +123,8 @@ final class DroneDockPreparationViewModel {
/// 主按钮串接创建与召唤;已有任务跳过创建,成功后的导航由页面处理。
@MainActor
func prepareAndSummon(onStateChange: @escaping @MainActor () -> Void = {}) async {
guard isPrimaryActionEnabled else { return }
// 禁飞调试在整条链开始前阻断,避免先残留真实待飞任务再拦截召唤。
guard allowsTaskSubmission, isPrimaryActionEnabled else { return }
primaryActionGeneration &+= 1
let actionGeneration = primaryActionGeneration
isPerformingPrimaryAction = true
@@ -136,7 +143,7 @@ final class DroneDockPreparationViewModel {
/// 对明确创建成功的任务发送一次召唤;只有明确业务拒绝允许之后再次提交。
@MainActor
private func summonCreatedTask(onStateChange: @escaping @MainActor () -> Void) async {
guard !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown,
guard allowsTaskSubmission, !isCreatingTask, !isSummoning, !taskCreationOutcomeUnknown,
!hasSubmittedSummon, !summonOutcomeUnknown,
let taskID = createdTask?.taskID, taskID > 0 else { return }
summonGeneration &+= 1
@@ -162,8 +169,13 @@ final class DroneDockPreparationViewModel {
hasSubmittedSummon = true
summonOutcomeUnknown = false
} catch {
if error is DeviceCommandDebugBlockedError, summonGeneration == requestGeneration {
didSendSummon = false
}
guard acceptsSummon(requestGeneration, taskID: taskID) else { return }
if case APIError.serverCode = error {
if error is DeviceCommandDebugBlockedError {
shootErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if case APIError.serverCode = error {
shootErrorMessage = error.localizedDescription
} else {
markSummonUnknown(reason: error.localizedDescription)
@@ -189,7 +201,7 @@ final class DroneDockPreparationViewModel {
/// 点击后先校验最新购买配置,再发送一次创建请求;成功留在准备页供核对。
@MainActor
func createTask(onStateChange: @escaping @MainActor () -> Void = {}) async {
guard canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID,
guard allowsTaskSubmission, canCreateTask, let spotID = selectedSpotID, let routeID = selectedRouteID,
let number = order.orderNumber, let projectID = order.projectID else { return }
taskCreationGeneration &+= 1
let requestGeneration = taskCreationGeneration
@@ -238,8 +250,13 @@ final class DroneDockPreparationViewModel {
hasCreatedTask = true
taskCreationOutcomeUnknown = false
} catch {
if error is DeviceCommandDebugBlockedError, taskCreationGeneration == requestGeneration {
didSendTaskCreation = false
}
guard acceptsTaskCreation(requestGeneration) else { return }
if didSendTaskCreation {
if error is DeviceCommandDebugBlockedError {
taskCreationErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if didSendTaskCreation {
if case APIError.serverCode = error {
taskCreationErrorMessage = error.localizedDescription
} else {
@@ -414,6 +431,7 @@ final class DroneDockPreparationViewModel {
if isCreatingTask { return "正在创建任务…" }
if isSummoning { return "正在召唤无人机…" }
if hasSubmittedSummon { return "查看拍摄任务" }
if !allowsTaskSubmission { return "仅限模拟调试" }
if summonOutcomeUnknown { return "召唤结果待核对" }
if hasCreatedTask { return shootErrorMessage == nil ? "确认并召唤" : "重试召唤" }
if taskCreationOutcomeUnknown { return "结果待核对" }
@@ -426,6 +444,7 @@ final class DroneDockPreparationViewModel {
if isCreatingTask { return "正在创建待飞任务,请勿重复点击" }
if isSummoning { return "任务已创建,正在提交召唤请求" }
if creationContextInvalidated, let errorMessage { return errorMessage }
if !allowsTaskSubmission && !hasSubmittedSummon { return DeviceCommandDebugPolicy.blockedMessage }
if let createdTask {
if hasSubmittedSummon { return "任务 \(createdTask.taskID) 的召唤请求已提交,请等待任务状态更新" }
if let shootErrorMessage { return shootErrorMessage }
@@ -1,6 +1,6 @@
import Foundation
/// 真实拍摄任务页只读状态,只按准备页传入的既有任务 ID 读取 shooting。
/// 拍摄任务状态及可选开拍流程,始终复用同一任务;禁飞调试仅为本地模拟注入开拍服务。
final class DroneDockShootingTaskViewModel {
/// 页面绑定的账号、景区和门店身份。
let context: DroneDockHomeContext
@@ -14,27 +14,47 @@ final class DroneDockShootingTaskViewModel {
private(set) var isLoading = false
/// 读取失败或身份变化时的提示。
private(set) var errorMessage: String?
/// 开拍提交及其后单次状态核对期间禁用重复操作,保留之前的显示快照。
private(set) var isStartingShooting = false
/// 开拍业务拒绝、本地拦截或结果待核对的说明。
private(set) var startErrorMessage: String?
/// 已发送但无法确认的开拍请求,不因后续读取仍允许开始而自动解除。
private(set) var startOutcomeUnknown = false
/// 当前页面是否已收到明确开拍受理回执,收到后不会再次提交。
private(set) var hasSubmittedStart = false
/// 同任务开拍回执;受理成功不直接替代 shooting 的完整状态快照。
private(set) var startResponse: DroneDockStartShootResponse?
private let service: any DroneDockShootingServing
private let startService: (any DroneDockStartShooting)?
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
private var generation = 0
private var identityInvalidated = false
private var startGeneration = 0
private var didSendStart = false
/// 只注入读取服务,不依赖创建、召唤、开始拍摄或控制服务。
/// 默认只读;只有显式注入开拍服务才提供开拍动作,当前正式入口不注入该服务。
init(context: DroneDockHomeContext, taskID: Int, order: DroneDockHomeOrder,
service: any DroneDockShootingServing,
startService: (any DroneDockStartShooting)? = nil,
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
self.context = context
self.taskID = taskID
self.order = order
self.service = service
self.startService = startService
self.currentContext = currentContext
}
/// 页面可见时读取同一任务;刷新及普通失败保留旧快照,身份失效立即清除。
@MainActor
func refresh() async {
guard !isLoading, !identityInvalidated else { return }
await refreshSnapshot(allowWhileStarting: false)
}
@MainActor
private func refreshSnapshot(allowWhileStarting: Bool) async {
guard !isLoading, !identityInvalidated, !isStartingShooting || allowWhileStarting else { return }
generation &+= 1
let requestGeneration = generation
isLoading = true
@@ -68,11 +88,14 @@ final class DroneDockShootingTaskViewModel {
/// 使旧请求失效;同一身份离页或进入后台可保留快照,账号变化始终清除并停止旧任务读取。
@MainActor
func invalidate(preservingSnapshot: Bool = false) {
invalidateStartShooting()
generation &+= 1
isLoading = false
if !context.hasSameIdentity(as: currentContext()) { identityInvalidated = true }
if identityInvalidated {
response = nil
startResponse = nil
startErrorMessage = nil
errorMessage = "账号或景区已变化,请返回工作台重新进入"
} else {
if !preservingSnapshot { response = nil }
@@ -80,6 +103,83 @@ final class DroneDockShootingTaskViewModel {
}
}
/// 只在有效读取明确到达、锁定飞机并允许 start_shoot 后开放;默认真实页面保持禁用。
var canStartShooting: Bool {
startService != nil && context.canLoad && taskID > 0 && !identityInvalidated
&& !isLoading && !isStartingShooting && errorMessage == nil
&& !hasSubmittedStart && !startOutcomeUnknown
&& resolvedDisplayPhase().0 == .ready
&& response?.executeGate?.canExecute == true
&& response?.executeGate?.primaryAction == "start_shoot"
&& (response?.currentPlane?.id ?? 0) > 0
}
/// 提交一次开拍并单次读取同任务;失败保留原快照,不轮询、不重建、不自动重发。
@MainActor
func startShooting(onStateChange: @escaping @MainActor () -> Void = {}) async {
guard canStartShooting, let startService else { return }
guard context.hasSameIdentity(as: currentContext()) else {
identityInvalidated = true
invalidate()
onStateChange()
return
}
guard !Task.isCancelled else { return }
let planeID = response?.currentPlane?.id
startGeneration &+= 1
let requestGeneration = startGeneration
isStartingShooting = true
didSendStart = false
startErrorMessage = nil
onStateChange()
defer {
if startGeneration == requestGeneration {
if Task.isCancelled && didSendStart && !hasSubmittedStart { markStartUnknown() }
isStartingShooting = false
didSendStart = false
onStateChange()
}
}
guard acceptsStart(requestGeneration) else { return }
do {
didSendStart = true
let value = try await startService.startShooting(taskID: taskID)
guard acceptsStart(requestGeneration) else { return }
guard value.orderFlightTaskID == taskID,
value.orderFlightTask?.id == nil || value.orderFlightTask?.id == taskID,
value.orderFlightTask?.orderNumber == nil || value.orderFlightTask?.orderNumber == order.orderNumber,
value.orderFlightTask?.scenicID == nil || value.orderFlightTask?.scenicID == context.scenicID,
value.planeID == nil || value.planeID == planeID else {
throw APIError.decodeFailed("开始拍摄回执与当前任务或飞机不一致,请先核对任务状态")
}
startResponse = value
hasSubmittedStart = true
startOutcomeUnknown = false
onStateChange()
guard acceptsStart(requestGeneration) else { return }
await refreshSnapshot(allowWhileStarting: true)
} catch {
if error is DeviceCommandDebugBlockedError, startGeneration == requestGeneration { didSendStart = false }
guard acceptsStart(requestGeneration) else { return }
if error is DeviceCommandDebugBlockedError {
startErrorMessage = DeviceCommandDebugPolicy.blockedMessage
} else if case APIError.serverCode = error {
startErrorMessage = error.localizedDescription
} else {
markStartUnknown(reason: error.localizedDescription)
}
}
}
/// 离页或进入后台后拒绝迟到回执;已发而未确认的请求保留待核对锁。
@MainActor
func invalidateStartShooting() {
if isStartingShooting && didSendStart && !hasSubmittedStart { markStartUnknown() }
startGeneration &+= 1
isStartingShooting = false
didSendStart = false
}
/// 优先使用当前接口标题,缺失时展示当前接口的点位和航线名称。
var title: String {
if let title = usable(response?.header?.title) { return title }
@@ -111,13 +211,18 @@ final class DroneDockShootingTaskViewModel {
?? usable(response?.orderFlightTask?.statusLabel) ?? "状态待确认"
}
/// 保留服务端阶段说明与执行门禁原因;本模块不执行门禁给出的动作。
/// 保留服务端阶段说明;未确认的开拍结果明确提示核对,不伪装为正在拍摄。
var statusMessage: String {
if response == nil {
if let errorMessage { return errorMessage }
if isLoading { return "正在读取当前拍摄任务" }
}
if resolvedDisplayPhase().0 == .failed { return failureMessage }
if startOutcomeUnknown, let startErrorMessage { return startErrorMessage }
if resolvedDisplayPhase().0 == .ready {
if let startErrorMessage { return startErrorMessage }
if hasSubmittedStart { return "开始拍摄请求已受理,请刷新确认任务状态" }
}
return usable(response?.ui?.message) ?? usable(response?.executeGate?.message) ?? "—"
}
@@ -138,10 +243,15 @@ final class DroneDockShootingTaskViewModel {
let actionTitle: String?
let enabled: Bool
switch phase {
case .ready where hasSubmittedStart || startOutcomeUnknown:
action = .refresh
actionTitle = "刷新状态"
enabled = !identityInvalidated
case .ready:
action = .start
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄"
enabled = false
actionTitle = isStartingShooting ? "正在提交开拍…"
: startErrorMessage == nil ? (usable(response?.executeGate?.primaryActionLabel) ?? "开始拍摄") : "重试开始拍摄"
enabled = canStartShooting
case .paused where response?.executeGate?.canExecute == true:
action = .resume
actionTitle = usable(response?.executeGate?.primaryActionLabel) ?? "继续拍摄"
@@ -161,7 +271,7 @@ final class DroneDockShootingTaskViewModel {
}
return DroneDockTaskPresentation(phase: phase, title: title, message: message,
deviceStatus: deviceStatusText, action: action, actionTitle: actionTitle,
isActionEnabled: enabled && !isLoading && !identityInvalidated && (errorMessage == nil || action == .refresh),
isActionEnabled: enabled && !isLoading && !isStartingShooting && !identityInvalidated && (errorMessage == nil || action == .refresh),
actionNote: phase == .failed ? retryUnavailableNote : nil)
}
@@ -189,6 +299,22 @@ final class DroneDockShootingTaskViewModel {
return !Task.isCancelled
}
@MainActor
private func acceptsStart(_ requestGeneration: Int) -> Bool {
guard startGeneration == requestGeneration else { return false }
guard context.hasSameIdentity(as: currentContext()), !identityInvalidated else {
identityInvalidated = true
invalidate()
return false
}
return !Task.isCancelled
}
private func markStartUnknown(reason: String? = nil) {
startOutcomeUnknown = true
startErrorMessage = (reason.map { "\($0)。" } ?? "") + "开始拍摄结果待核对,请刷新任务状态,勿重复提交"
}
private func matchesIdentity(_ value: DroneDockShootingResponse) -> Bool {
let taskIDs = [value.orderFlightTask?.id, value.task?.id].compactMap { $0 }
let orderNumbers = [value.orderNumber, value.orderFlightTask?.orderNumber,
@@ -83,8 +83,7 @@ enum HomeRouteHandler {
let context = ScenicMaterialContext(userID: session.userId,
scenicID: String(session.currentScenicId),
scenicName: session.currentScenicName)
// 素材接口尚未接入,正式入口使用当前景区空态,避免生成预览素材。
let viewModel = ScenicMaterialsViewModel(context: context, routes: [], groups: [])
let viewModel = ScenicMaterialsViewModel(context: context, isRemote: true)
viewController.navigationController?.pushViewController(ScenicMaterialsViewController(viewModel: viewModel), animated: true)
case "checkin_points":
viewController.navigationController?.pushViewController(PunchPointListViewController(), animated: true)
@@ -0,0 +1,43 @@
import Foundation
/// 景区空境库的只读场次及详情接口,素材下载不回写订单素材状态。
protocol ScenicMaterialsServing: Sendable {
/// 按当前景区及筛选分页读取场次。
@MainActor
func sessions(query: ScenicMaterialsQuery) async throws -> ScenicMaterialsSessionsResponse
/// 使用场次身份读取完整片段信息和授权文件地址。
@MainActor
func sessionDetail(scenicMediaID: Int) async throws -> ScenicMaterialsSessionDetailResponse
}
/// 朱工景区空境库接口,复用部署环境验证过的 token 鉴权和统一业务包。
@MainActor
final class ScenicMaterialsAPI: ScenicMaterialsServing {
private let client: APIClient
/// 注入统一网络客户端,单元测试可使用 MockURLSession。
init(client: APIClient) { self.client = client }
/// 验证请求范围及响应页码,避免拼入其他页或其他筛选的数据。
func sessions(query: ScenicMaterialsQuery) async throws -> ScenicMaterialsSessionsResponse {
let response: ScenicMaterialsSessionsResponse = try await client.send(APIRequest(
method: .get, path: "/api/app/scenic-media/sessions", queryItems: try query.queryItems(), logsPayload: false
))
guard response.page == query.page, response.pageSize == query.pageSize,
response.retentionDays == query.retentionDays,
response.filter.airLineID == (query.airLineID ?? 0),
response.filter.dateFrom == (query.dateFrom ?? ""), response.filter.dateTo == (query.dateTo ?? "") else {
throw APIError.decodeFailed("空境库场次与当前查询条件不一致,请刷新重试")
}
return response
}
/// 只传文档定义的 scenic_media_id,不传订单、任务或机巢身份。
func sessionDetail(scenicMediaID: Int) async throws -> ScenicMaterialsSessionDetailResponse {
guard scenicMediaID > 0 else { throw APIError.networkFailed("空境场次无效,请刷新重试") }
return try await client.send(APIRequest(
method: .get, path: "/api/app/scenic-media/session-detail",
queryItems: [URLQueryItem(name: "scenic_media_id", value: String(scenicMediaID))], logsPayload: false
))
}
}
@@ -0,0 +1,74 @@
import Foundation
/// 为月、日两列滚轮提供保留期内的真实日期,月份保留年份以正确处理跨年。
struct ScenicMaterialDatePickerOptions {
/// 一个月中实际可选的日期;首月和末月只包含保留期覆盖的部分。
struct Month {
/// 日历中的年份,供跨年识别及辅助功能使用。
let year: Int
/// 日历中的月份。
let number: Int
/// 当前月份内按先后排列且允许选择的日期。
let dates: [Date]
}
/// 包含端点、按日归一化的最早日期。
let minimumDate: Date
/// 包含端点、按日归一化的最晚日期。
let maximumDate: Date
/// 从最早到最晚排列的可选月份。
let months: [Month]
private let calendar: Calendar
/// 将闭区间展开为有限选项,不依赖每月天数或一天固定为 24 小时的假设。
init(minimumDate: Date, maximumDate: Date, calendar: Calendar) {
self.calendar = calendar
let minimum = calendar.startOfDay(for: minimumDate)
let maximum = max(minimum, calendar.startOfDay(for: maximumDate))
self.minimumDate = minimum
self.maximumDate = maximum
var months: [Month] = []
var day = minimum
while day <= maximum {
let year = calendar.component(.year, from: day)
let number = calendar.component(.month, from: day)
if let last = months.last, last.year == year, last.number == number {
months[months.count - 1] = Month(year: year, number: number, dates: last.dates + [day])
} else {
months.append(Month(year: year, number: number, dates: [day]))
}
guard let next = calendar.date(byAdding: .day, value: 1, to: day), next > day else { break }
day = next
}
self.months = months
}
/// 将外部值归一到允许范围内的日历日。
func clamped(_ date: Date) -> Date {
min(max(calendar.startOfDay(for: date), minimumDate), maximumDate)
}
/// 找到日期对应的月份行,保留期外值先收敛到边界。
func monthIndex(for date: Date) -> Int {
let value = clamped(date)
return months.firstIndex { month in
month.dates.first.map { $0 <= value } == true && month.dates.last.map { value <= $0 } == true
} ?? 0
}
/// 切换月份时尽量保留原日号;月末或截断的保留期会收敛到最近可选日。
func date(inMonthAt index: Int, preferredDay: Int) -> Date {
let month = months[min(max(index, 0), months.count - 1)]
return month.dates.min {
abs(calendar.component(.day, from: $0) - preferredDay)
< abs(calendar.component(.day, from: $1) - preferredDay)
} ?? minimumDate
}
/// 普通范围只显示月份;范围含同名月份时补年份,避免用户混淆。
func monthTitle(at index: Int) -> String {
let month = months[index]
let repeats = months.filter { $0.number == month.number }.count > 1
return repeats ? "\(month.year)年\(month.number)月" : "\(month.number)月"
}
}
@@ -70,12 +70,21 @@ struct ScenicMaterialClip: Hashable, Sendable {
let resolution: String
/// 本地演示封面资源名。
let coverAssetName: String
/// 正式素材原片地址;预览素材为空。
let remoteURL: URL?
/// 正式素材封面地址。
let coverURL: URL?
/// 后端返回的片段名称。
let fileLabel: String?
/// 是否来自正式接口,缺失地址时禁止回退到演示视频。
let isRemote: Bool
/// 文件是否仍可预览和下载;不可用文件仍可展示其元数据。
let isAvailable: Bool
/// 创建片段元数据,不读取本地相册或请求网络。
init(id: String, groupID: String, ordinal: Int, durationSeconds: Int, fileSizeBytes: Int64,
resolution: String, coverAssetName: String, isAvailable: Bool = true) {
resolution: String, coverAssetName: String, isAvailable: Bool = true,
remoteURL: URL? = nil, coverURL: URL? = nil, fileLabel: String? = nil, isRemote: Bool = false) {
self.id = id
self.groupID = groupID
self.ordinal = ordinal
@@ -84,16 +93,22 @@ struct ScenicMaterialClip: Hashable, Sendable {
self.resolution = resolution
self.coverAssetName = coverAssetName
self.isAvailable = isAvailable
self.remoteURL = remoteURL
self.coverURL = coverURL
self.fileLabel = fileLabel
self.isRemote = isRemote
}
/// 用于封面与预览信息的分秒时长。
var durationText: String {
guard durationSeconds >= 0 else { return "时长未知" }
let value = max(durationSeconds, 0)
return String(format: "%02d:%02d", value / 60, value % 60)
}
/// 使用十进制 MB 展示片段大小,避免将原文件与本地示例文件混淆。
var sizeText: String {
guard fileSizeBytes >= 0 else { return "大小未知" }
let megabytes = Double(max(fileSizeBytes, 0)) / 1_000_000
return megabytes.rounded() == megabytes ? String(format: "%.0fMB", megabytes) : String(format: "%.1fMB", megabytes)
}
@@ -0,0 +1,113 @@
import Foundation
/// 场次接口中已由部署响应确认的分页和保留策略;子项保留原始字段供合同映射使用。
struct ScenicMaterialsSessionsResponse: Decodable, Equatable, Sendable {
/// 当前页场次原始对象,不能把未确认的子项结构当成空列表。
let list: [[String: ScenicMaterialsJSONValue]]
/// 服务端航线分组原始对象。
let groups: [[String: ScenicMaterialsJSONValue]]
/// 当前筛选场次总数。
let total: Int
/// 服务端实际返回的页码。
let page: Int
/// 服务端实际返回的每页数量。
let pageSize: Int
/// 本次查询的素材保留窗口。
let retentionDays: Int
/// 服务端提供的保留期提示。
let retentionTips: String
/// 服务端实际应用的筛选。
let filter: ScenicMaterialsFilter
/// 当前景区可用的航线筛选对象。
let airLines: [[String: ScenicMaterialsJSONValue]]
/// 部署接口的根字段。
private enum CodingKeys: String, CodingKey {
case list, groups, total, page, pageSize = "page_size", retentionDays = "retention_days"
case retentionTips = "retention_tips", filter, filterOptions = "filter_options"
}
/// 只接受真实容器和有效分页,避免缺字段响应被误显示成空态。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
list = try container.decode([[String: ScenicMaterialsJSONValue]].self, forKey: .list)
groups = try container.decode([[String: ScenicMaterialsJSONValue]].self, forKey: .groups)
total = try container.decode(Int.self, forKey: .total)
page = try container.decode(Int.self, forKey: .page)
pageSize = try container.decode(Int.self, forKey: .pageSize)
retentionDays = try container.decode(Int.self, forKey: .retentionDays)
retentionTips = try container.decode(String.self, forKey: .retentionTips)
filter = try container.decode(ScenicMaterialsFilter.self, forKey: .filter)
airLines = try container.decode(ScenicMaterialsFilterOptions.self, forKey: .filterOptions).airLines
guard total >= 0, page > 0, (1...100).contains(pageSize), (1...365).contains(retentionDays),
list.count <= pageSize, list.count <= total else {
throw DecodingError.dataCorruptedError(forKey: .list, in: container, debugDescription: "空境库场次分页或保留期无效")
}
}
}
/// 后端实际应用的筛选,全部航线为 0、全部日期为空字符串。
struct ScenicMaterialsFilter: Decodable, Equatable, Sendable {
/// 当前航线筛选值。
let airLineID: Int
/// 当前起始日期筛选值。
let dateFrom: String
/// 当前结束日期筛选值。
let dateTo: String
/// 部署响应中的筛选字段。
private enum CodingKeys: String, CodingKey {
case airLineID = "air_line_id", dateFrom = "date_from", dateTo = "date_to"
}
}
/// filter_options 下独立返回当前景区的航线集合。
private struct ScenicMaterialsFilterOptions: Decodable {
let airLines: [[String: ScenicMaterialsJSONValue]]
/// 部署响应中的航线容器。
private enum CodingKeys: String, CodingKey { case airLines = "air_lines" }
}
/// 场次详情的已确认素材数组及完整场次信息,不借用订单素材 ID 模型。
struct ScenicMaterialsSessionDetailResponse: Decodable, Equatable, Sendable {
/// 文档明确返回的全部素材项,保留服务端所有字段。
let materials: [[String: ScenicMaterialsJSONValue]]
/// 场次详情完整对象,供依据实际合同解码归属与展示信息。
let fields: [String: ScenicMaterialsJSONValue]
/// 缺少 materials 或容器错误时报错,不伪装成没有素材。
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
fields = try container.decode([String: ScenicMaterialsJSONValue].self)
guard case let .array(values)? = fields["materials"] else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "空境场次详情缺少 materials 数组")
}
materials = try values.map { value in
guard case let .object(fields) = value else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "空境素材必须为对象")
}
return fields
}
}
}
/// 保留空境库尚未完整描述的子项 JSON,不猜测字段类型或单位。
indirect enum ScenicMaterialsJSONValue: Decodable, Equatable, Sendable {
case object([String: ScenicMaterialsJSONValue])
case array([ScenicMaterialsJSONValue])
case string(String)
case number(Decimal)
case bool(Bool)
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: ScenicMaterialsJSONValue].self) { self = .object(value) }
else { self = .array(try container.decode([ScenicMaterialsJSONValue].self)) }
}
}
@@ -0,0 +1,67 @@
import Foundation
/// 朱工空境库场次查询范围,分页和筛选均由服务端执行。
struct ScenicMaterialsQuery: Equatable, Sendable {
/// 当前景区身份,不依赖订单、机巢或飞行任务。
let scenicID: Int
/// 从 1 开始的场次页码。
let page: Int
/// 每页场次数,接口允许 1 到 100。
let pageSize: Int
/// 指定航线;nil 表示全部航线。
let airLineID: Int?
/// 可选起始日期,格式为 yyyy-MM-dd。
let dateFrom: String?
/// 可选结束日期,格式为 yyyy-MM-dd。
let dateTo: String?
/// 保留期查询窗口,默认 90 天,部署接口允许 1 到 365。
let retentionDays: Int
/// 创建完整查询快照,便于判断翻页和筛选请求是否过期。
init(scenicID: Int, page: Int = 1, pageSize: Int = 20, airLineID: Int? = nil,
dateFrom: String? = nil, dateTo: String? = nil, retentionDays: Int = 90) {
self.scenicID = scenicID
self.page = page
self.pageSize = pageSize
self.airLineID = airLineID
self.dateFrom = dateFrom
self.dateTo = dateTo
self.retentionDays = retentionDays
}
/// 校验范围后生成文档规定的 GET 参数,全部航线和全部日期不发送占位值。
func queryItems() throws -> [URLQueryItem] {
guard scenicID > 0 else { throw APIError.networkFailed("请先选择景区") }
guard page > 0, (1...100).contains(pageSize), (1...365).contains(retentionDays),
airLineID.map({ $0 > 0 }) ?? true else {
throw APIError.networkFailed("景区空境库查询参数无效")
}
guard Self.isValidDate(dateFrom), Self.isValidDate(dateTo) else {
throw APIError.networkFailed("请选择有效的日期范围")
}
if let dateFrom, let dateTo, dateFrom > dateTo {
throw APIError.networkFailed("请选择有效的日期范围")
}
var result = [URLQueryItem(name: "scenic_id", value: String(scenicID)),
URLQueryItem(name: "page", value: String(page)),
URLQueryItem(name: "page_size", value: String(pageSize)),
URLQueryItem(name: "retention_days", value: String(retentionDays))]
if let airLineID { result.append(URLQueryItem(name: "air_line_id", value: String(airLineID))) }
if let dateFrom { result.append(URLQueryItem(name: "date_from", value: dateFrom)) }
if let dateTo { result.append(URLQueryItem(name: "date_to", value: dateTo)) }
return result
}
/// 严格校验公历日期,拒绝 DateFormatter 自动纠正的越界日期。
private static func isValidDate(_ value: String?) -> Bool {
guard let value else { return true }
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd"
formatter.isLenient = false
guard let date = formatter.date(from: value) else { return false }
return formatter.string(from: date) == value
}
}
@@ -0,0 +1,175 @@
import Foundation
import Photos
/// 一项待保存的空境素材;身份仅在当前账号、景区页面的服务实例内使用。
struct ScenicMaterialDownloadItem: Sendable {
/// 当前素材的稳定标识。
let id: String
/// 服务端提供的可下载原片地址。
let remoteURL: URL
/// 本地临时文件名,保留媒体扩展名以便 Photos 识别。
let fileName: String
/// 与相册保存器一致:1 为视频,其他值为图片。
let fileType: Int
/// 创建下载项,不附加 App 登录凭证到 OSS 地址。
init(id: String, remoteURL: URL, fileName: String = "scenic-material.mp4", fileType: Int = 1) {
self.id = id
self.remoteURL = remoteURL
self.fileName = fileName
self.fileType = fileType
}
}
/// 串行下载并保存真实空境素材;取消后屏蔽旧回执,已保存的文件不重复写入相册。
@MainActor
final class ScenicMaterialDownloadService {
private let downloader: any CloudFileDownloading
private let photoSaver: any CloudPhotoSaving
private var task: Task<Void, Never>?
private var activeBatchID: UUID?
private var savedIDs = Set<String>()
/// 注入下载和相册保存依赖,测试不访问网络或系统相册。
init(downloader: any CloudFileDownloading = ScenicMaterialURLSessionDownloader(),
photoSaver: any CloudPhotoSaving = ScenicMaterialPhotoLibrarySaver()) {
self.downloader = downloader
self.photoSaver = photoSaver
}
/// 开始当前批次;同一批次的重复启动无效,重新启动会等待前次相册事务结束。
func start(items: [ScenicMaterialDownloadItem], batchID: UUID,
onEvent: @escaping @MainActor @Sendable (String, UUID, ScenicMaterialTransferEvent) -> Void,
onFailure: (@MainActor @Sendable (String, Error) -> Void)? = nil) {
guard activeBatchID != batchID else { return }
let previous = task
previous?.cancel()
activeBatchID = batchID
task = Task { @MainActor [weak self] in
// Photos 的已提交保存不可取消;先等旧事务落定,再决定是否需要重下。
await previous?.value
guard let self else { return }
defer { if self.activeBatchID == batchID { self.activeBatchID = nil } }
var visited = Set<String>()
for item in items where visited.insert(item.id).inserted {
guard self.isActive(batchID) else { return }
if self.savedIDs.contains(item.id) {
onEvent(item.id, batchID, .completed)
continue
}
var localURL: URL?
defer { if let localURL { try? FileManager.default.removeItem(at: localURL) } }
do {
localURL = try await self.downloader.downloadFile(remoteURL: item.remoteURL.absoluteString,
fileName: item.fileName) { [weak self] percent in
Task { @MainActor [weak self] in
guard let self, self.isActive(batchID), !self.savedIDs.contains(item.id) else { return }
// 下载完成只占 90%,最后一步是系统相册保存成功。
onEvent(item.id, batchID, .progress(Double(min(max(percent, 0), 100)) / 100 * 0.9))
}
}
guard self.isActive(batchID), let localURL else { return }
try await self.photoSaver.saveToPhotoLibrary(fileURL: localURL, fileType: item.fileType)
// 保存已落定,即便用户此时暂停,也保留事实以免继续时重复保存。
self.savedIDs.insert(item.id)
guard self.isActive(batchID) else { return }
onEvent(item.id, batchID, .completed)
} catch {
guard self.isActive(batchID) else { return }
onEvent(item.id, batchID, .failed)
onFailure?(item.id, error)
}
}
}
}
/// 停止下载并作废当前回执;正在提交的相册事务完成后会清理临时文件。
func stop() {
activeBatchID = nil
task?.cancel()
}
/// 等待已经启动的传输及临时文件清理完成。
func waitForPendingOperations() async { await task?.value }
private func isActive(_ batchID: UUID) -> Bool {
!Task.isCancelled && activeBatchID == batchID
}
}
/// 检查 HTTP 状态与非空响应文件的空境原片下载器。
struct ScenicMaterialURLSessionDownloader: CloudFileDownloading {
private let session: URLSession
/// 注入 URLSession 便于使用 URLProtocol 验证状态码及错误响应。
init(session: URLSession = .shared) { self.session = session }
/// 下载到唯一临时路径;失败响应及取消下载均清理 URLSession 临时文件。
func downloadFile(remoteURL: String, fileName: String,
onProgress: @escaping @Sendable (Int) -> Void) async throws -> URL {
guard let url = URL(string: remoteURL), ["https", "http"].contains(url.scheme?.lowercased() ?? ""),
url.host != nil else { throw ScenicMaterialDownloadError.invalidURL }
let delegate = ScenicMaterialDownloadProgress(onProgress: onProgress)
let (temporaryURL, response) = try await session.download(from: url, delegate: delegate)
defer { try? FileManager.default.removeItem(at: temporaryURL) }
try Task.checkCancellation()
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
throw ScenicMaterialDownloadError.httpFailure((response as? HTTPURLResponse)?.statusCode ?? 0)
}
let attributes = try FileManager.default.attributesOfItem(atPath: temporaryURL.path)
guard (attributes[.size] as? NSNumber)?.int64Value ?? 0 > 0 else {
throw ScenicMaterialDownloadError.emptyFile
}
let destination = FileManager.default.temporaryDirectory
.appendingPathComponent("\(UUID().uuidString)-\(CloudTransferFileName.sanitized(fileName))")
try FileManager.default.moveItem(at: temporaryURL, to: destination)
onProgress(100)
return destination
}
}
/// 将 URLSession 的实际字节进度传回下载服务,不虚构中间进度。
private final class ScenicMaterialDownloadProgress: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
private let onProgress: @Sendable (Int) -> Void
init(onProgress: @escaping @Sendable (Int) -> Void) { self.onProgress = onProgress }
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
guard totalBytesExpectedToWrite > 0 else { return }
onProgress(Int(min(Double(totalBytesWritten) / Double(totalBytesExpectedToWrite), 1) * 100))
}
}
/// 只请求添加相册权限,Photos 成功创建资产后才返回成功。
struct ScenicMaterialPhotoLibrarySaver: CloudPhotoSaving {
/// 保存本地真实图片或视频;授权期间取消操作不会继续提交相册事务。
func saveToPhotoLibrary(fileURL: URL, fileType: Int) async throws {
let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
try Task.checkCancellation()
guard status == .authorized || status == .limited else { throw CloudTransferError.photoPermissionDenied }
guard FileManager.default.fileExists(atPath: fileURL.path) else { throw CloudTransferError.localFileMissing }
try await PHPhotoLibrary.shared().performChanges {
let request = PHAssetCreationRequest.forAsset()
request.addResource(with: fileType == 1 ? .video : .photo, fileURL: fileURL, options: nil)
}
}
}
/// 空境原片下载中可向用户解释的错误。
enum ScenicMaterialDownloadError: LocalizedError, Equatable {
case invalidURL
case httpFailure(Int)
case emptyFile
/// 下载失败原因,避免将服务端错误页作为素材保存。
var errorDescription: String? {
switch self {
case .invalidURL: "素材地址无效"
case .httpFailure(let status): "素材下载失败(HTTP \(status))"
case .emptyFile: "素材文件为空,请稍后重试"
}
}
}
@@ -2,14 +2,16 @@ import Foundation
/// 独立景区空镜库的筛选、选择和前台下载演示逻辑;不依赖 UIKit 或机巢业务。
final class ScenicMaterialsViewModel {
/// 正式模式使用网络素材与真实相册保存,预览模式使用本地演示。
let isRemote: Bool
/// 本次页面的独立账号与景区范围。
let context: ScenicMaterialContext
/// 用于筛选的日历及其时区。
let calendar: Calendar
/// 本地演示保留天数,正式对接后由服务端配置决定。
let retentionDays = 90
private(set) var retentionDays = 90
/// 保留期首日零点,包含今天一共 90 个日历日。
let minimumDate: Date
private(set) var minimumDate: Date
/// 可选的最后一天零点,不允许选择未来日期。
let maximumDate: Date
/// 当前景区的独立空镜航线,含暂无片段的航线。
@@ -37,18 +39,29 @@ final class ScenicMaterialsViewModel {
/// 当前批次的逐项演示进度。
private(set) var progressByID: [String: Double] = [:]
/// 已确认接口的加载状态。
private(set) var isLoading = false
/// 请求失败或素材字段尚无法映射时的可重试提示。
private(set) var loadError: String?
/// 保留完整响应,非空且未确认字段时不能被当成空库。
private(set) var remoteSessions: ScenicMaterialsSessionsResponse?
/// 素材保留说明优先使用后端返回的文案。
private(set) var retentionTips = "素材保留 90 天,请及时下载"
private var loadID: UUID?
private let initialGroups: [ScenicMaterialGroup]
/// 创建演示库;可注入日历、日期和数据,测试不依赖时间、网络或登录单例。
init(context: ScenicMaterialContext = .demo, now: Date = Date(), calendar: Calendar = .current,
routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil) {
routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil, isRemote: Bool = false) {
self.isRemote = isRemote
self.context = context
self.calendar = calendar
maximumDate = calendar.startOfDay(for: now)
minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate
let demoRoutes = Self.makeRoutes(context: context)
let demoRoutes = isRemote ? [] : Self.makeRoutes(context: context)
self.routes = routes ?? demoRoutes
let data = groups ?? Self.makeGroups(context: context, routes: demoRoutes, today: maximumDate, calendar: calendar)
let data = groups ?? (isRemote ? [] : Self.makeGroups(context: context, routes: demoRoutes, today: maximumDate, calendar: calendar))
initialGroups = data
allGroups = data
}
@@ -113,10 +126,55 @@ final class ScenicMaterialsViewModel {
}
}
/// 当前空态标题,区分全库为空与有筛选但无结果。
var emptyTitle: String { hasAnyMaterials ? "没有符合条件的素材" : "暂无景区素材" }
var emptyTitle: String {
if isLoading { return "正在加载素材" }
if loadError != nil { return "素材加载失败" }
return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "没有符合条件的素材" : "暂无景区素材"
}
/// 当前空态说明。
var emptyMessage: String {
hasAnyMaterials ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里"
if isLoading { return "请稍候" }
if let loadError { return loadError }
return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里"
}
/// 读取当前景区的真实列表;在有样本确认子项合同前保留原始响应并明确报错。
func loadRemoteSessions(api: any ScenicMaterialsServing) async {
guard isRemote, !isSelectionLocked else { return }
let requestID = UUID()
loadID = requestID
defer { if loadID == requestID { isLoading = false } }
isLoading = true
loadError = nil
let query = ScenicMaterialsQuery(scenicID: Int(context.scenicID) ?? 0,
airLineID: selectedRouteID.flatMap(Int.init),
dateFrom: dateRange.map { formatDate($0.start, format: "yyyy-MM-dd") },
dateTo: dateRange.map { formatDate($0.end, format: "yyyy-MM-dd") }, retentionDays: retentionDays)
do {
let response = try await api.sessions(query: query)
guard loadID == requestID, !Task.isCancelled else { return }
remoteSessions = response
retentionDays = response.retentionDays
retentionTips = response.retentionTips
minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate
allGroups = []
routes = []
selectedIDs.removeAll()
if response.total > 0 || !response.list.isEmpty || !response.groups.isEmpty || !response.airLines.isEmpty {
// 当前文档没有非空场次/航线的字段合同,不使用猜测的 ID 下载或错配素材。
loadError = "暂时无法显示素材,请稍后重试"
}
} catch is CancellationError {
} catch {
guard loadID == requestID else { return }
loadError = error.localizedDescription
}
}
/// 离页或身份变化后作废尚未返回的列表请求。
func cancelRemoteLoad() {
loadID = nil
isLoading = false
}
/// 查找稳定航线,不依赖名称。
@@ -171,7 +229,7 @@ final class ScenicMaterialsViewModel {
/// 当前可选状态;完成、不可用、隐藏片段或锁定批次均不可新选。
func canSelect(id: String) -> Bool {
!isSelectionLocked && filteredClips.contains { $0.id == id && $0.isAvailable && !completedIDs.contains(id) }
!isSelectionLocked && filteredClips.contains { $0.id == id && $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains(id) }
}
/// 切换单项选择,不涉及预览或下载。
@@ -215,7 +273,7 @@ final class ScenicMaterialsViewModel {
@discardableResult
func startDownload() -> Bool {
guard !isSelectionLocked else { return false }
let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && !completedIDs.contains($0.id) }
let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }
guard !items.isEmpty else { return false }
batchItemIDs = items.map(\.id)
selectedIDs = Set(batchItemIDs)
@@ -285,6 +343,7 @@ final class ScenicMaterialsViewModel {
/// 切换本地状态预览,不读取真实相册,也不更改登录身份或订单。
func applyScenario(_ scenario: ScenicMaterialsScenario) {
guard !isRemote else { return }
clearBatch()
completedIDs.removeAll()
allGroups = initialGroups
@@ -320,11 +379,11 @@ final class ScenicMaterialsViewModel {
private func selectableIDs(in groupID: String) -> Set<String> {
guard let group = filteredGroups.first(where: { $0.id == groupID }) else { return [] }
return Set(group.clips.filter { $0.isAvailable && !completedIDs.contains($0.id) }.map(\.id))
return Set(group.clips.filter { $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }.map(\.id))
}
private func pruneSelection() {
let valid = Set(filteredClips.filter { $0.isAvailable && !completedIDs.contains($0.id) }.map(\.id))
let valid = Set(filteredClips.filter { $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }.map(\.id))
selectedIDs.formIntersection(valid)
}
@@ -3,6 +3,33 @@ import UIKit
/// 订单列表与素材库共用的真实成片交付页面工厂。
@MainActor
enum DroneDockDeliveryEntry {
/// 订单列表先展示方式选择,云端页面在同一弹窗内继续,关闭后再通知列表刷新。
static func makeMethodSheet(order: DroneDockHomeOrder, context: DroneDockHomeContext,
controllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController,
onDidCloseCloud: @escaping () -> Void = {}) -> UINavigationController {
let methods = DroneDockDeliveryMethodViewController(customerTitle: order.touristTitle)
let navigation = DroneDockDeliverySheetNavigationController(rootViewController: methods)
navigation.modalPresentationStyle = .pageSheet
navigation.onDidCloseCloud = onDidCloseCloud
methods.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
methods.onCloudUpload = { [weak navigation, weak methods] in
guard let navigation, let methods, navigation.topViewController === methods else { return }
let cloud = controllerFactory(order, context, nil)
if let cloud = cloud as? DroneDockDeliveryViewController {
cloud.configureSheetPresentation { [weak navigation] in navigation?.dismiss(animated: true) }
}
navigation.didOpenCloud = true
navigation.isModalInPresentation = true
navigation.sheetPresentationController?.animateChanges {
navigation.sheetPresentationController?.detents = [.large()]
navigation.sheetPresentationController?.selectedDetentIdentifier = .large
}
navigation.setNavigationBarHidden(false, animated: true)
navigation.pushViewController(cloud, animated: true)
}
return navigation
}
/// 同时传递订单与可选任务,进入页面后重新校验当前身份和上传权限。
static func makeController(order: DroneDockHomeOrder, context: DroneDockHomeContext, taskID: Int?) -> UIViewController {
let client = NetworkServices.shared.apiClient
@@ -15,3 +42,32 @@ enum DroneDockDeliveryEntry {
))
}
}
/// 统一处理手动关闭与下拉关闭,云端交付结束后只通知来源列表一次。
@MainActor
private final class DroneDockDeliverySheetNavigationController: UINavigationController, UIAdaptivePresentationControllerDelegate {
/// 云端页面已经进入,关闭弹窗后需要重读订单状态。
var didOpenCloud = false
/// 不因仅查看交付方式而刷新订单。
var onDidCloseCloud: (() -> Void)?
private var didNotifyClose = false
override func viewDidLoad() {
super.viewDidLoad()
presentationController?.delegate = self
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isBeingDismissed || presentingViewController == nil { notifyClose() }
}
/// 系统下拉关闭与按钮关闭使用同一去重通知。
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { notifyClose() }
private func notifyClose() {
guard !didNotifyClose else { return }
didNotifyClose = true
if didOpenCloud { onDidCloseCloud?() }
}
}
@@ -0,0 +1,170 @@
import SnapKit
import UIKit
/// 真实订单的交付方式弹窗,只展示方式选择并将云端交付导航交回入口。
@MainActor
final class DroneDockDeliveryMethodViewController: BaseViewController {
/// 用户选择云端上传后,由入口打开现有真实交付页。
var onCloudUpload: (() -> Void)?
/// 用户关闭弹窗后,由入口统一结束当前模态流程。
var onClose: (() -> Void)?
/// 闪传只显示未接入说明,不创建传输任务或连接设备。
private enum Phase: Equatable { case methods, nearby }
/// 两种交付方式与闪传说明使用独立、稳定的列表身份。
private enum Item: Hashable { case nearby, cloud, nearbyMessage }
private let customerTitle: String
private let headerView = DroneDeliveryUploadHeaderView()
private let footerView = DroneDeliveryUploadFooterView()
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Int, Item>!
private var phase = Phase.methods
private var hasRequestedCloud = false
/// 游客标题由选中的订单传入,本弹窗不读取网络或改变订单状态。
init(customerTitle: String) {
self.customerTitle = customerTitle
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .pageSheet
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
hasRequestedCloud = false
navigationController?.isModalInPresentation = false
isModalInPresentation = false
navigationController?.setNavigationBarHidden(true, animated: false)
configureSheet()
}
override func setupNavigationBar() {
title = "交付成片"
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func setupUI() {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = false
collectionView.showsVerticalScrollIndicator = false
collectionView.accessibilityIdentifier = "drone.delivery.method.list"
collectionView.delegate = self
collectionView.register(DroneDeliveryUploadMethodCell.self, forCellWithReuseIdentifier: "method")
collectionView.register(DroneDeliveryUploadMessageCell.self, forCellWithReuseIdentifier: "message")
[headerView, collectionView, footerView].forEach(view.addSubview)
configureDataSource()
applySnapshot(animated: false)
}
override func setupConstraints() {
headerView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.equalToSuperview()
}
collectionView.snp.makeConstraints { make in
make.top.equalTo(headerView.snp.bottom)
make.leading.trailing.equalToSuperview()
make.bottom.equalTo(footerView.snp.top)
}
footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
}
override func bindActions() {
headerView.onCloseTap = { [weak self] in self?.onClose?() }
footerView.onPrimaryTap = { [weak self] in self?.requestCloudUpload() }
footerView.onSecondaryTap = { [weak self] in self?.showPhase(.methods) }
}
private func configureSheet() {
guard let sheet = navigationController?.sheetPresentationController ?? sheetPresentationController else { return }
let identifier = UISheetPresentationController.Detent.Identifier("drone.delivery.method")
sheet.detents = [
.custom(identifier: identifier) { context in min(410, context.maximumDetentValue) },
.large()
]
sheet.selectedDetentIdentifier = identifier
sheet.prefersGrabberVisible = true
sheet.preferredCornerRadius = 22
sheet.prefersScrollingExpandsWhenScrolledToEdge = false
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] _, _ in
guard let self else { return nil }
let height: CGFloat = self.phase == .methods ? 88 : 132
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.vertical(
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)), subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = self.phase == .methods ? 12 : 0
section.contentInsets = .init(top: 4, leading: 20, bottom: 4, trailing: 20)
return section
}
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Int, Item>(collectionView: collectionView) { collection, path, item in
switch item {
case .nearby, .cloud:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "method", for: path) as! DroneDeliveryUploadMethodCell
if item == .nearby {
cell.apply(title: "面对面闪传", detail: "近距离传给游客 · 流程待确认", symbol: "wifi", identifier: "drone.delivery.method.nearby")
} else {
cell.apply(title: "云端上传", detail: "选择打卡点,上传后游客可查看", symbol: "icloud.and.arrow.up", identifier: "drone.delivery.method.cloud")
}
return cell
case .nearbyMessage:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DroneDeliveryUploadMessageCell
cell.apply(title: "闪传流程待确认", detail: "热点连接与游客接收流程暂未接入。\n请使用云端上传交付成片。", symbol: "wifi")
cell.accessibilityIdentifier = "drone.delivery.method.nearbyMessage"
return cell
}
}
}
private func applySnapshot(animated: Bool) {
guard dataSource != nil else { return }
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
switch phase {
case .methods:
headerView.apply(title: "交付成片", customer: customerTitle, detail: "请选择本次交付方式")
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批交付多个作品,不影响拍摄次数", secondaryTitle: nil)
snapshot.appendItems([.nearby, .cloud])
case .nearby:
headerView.apply(title: "面对面闪传", customer: customerTitle, detail: "本次仅展示交付入口")
footerView.apply(primaryTitle: "改用云端上传", enabled: true, identifier: "drone.delivery.method.useCloud", detail: "", secondaryTitle: "返回交付方式")
snapshot.appendItems([.nearbyMessage])
}
dataSource.apply(snapshot, animatingDifferences: animated)
collectionView.collectionViewLayout.invalidateLayout()
}
private func showPhase(_ phase: Phase) {
self.phase = phase
applySnapshot(animated: true)
collectionView.setContentOffset(.zero, animated: false)
}
private func requestCloudUpload() {
guard !hasRequestedCloud, let onCloudUpload else { return }
hasRequestedCloud = true
onCloudUpload()
}
}
extension DroneDockDeliveryMethodViewController: UICollectionViewDelegate {
/// 云端方式交回调用方,闪传方式只在当前弹窗展示待接入说明。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath), !hasRequestedCloud else { return }
switch item {
case .nearby: showPhase(.nearby)
case .cloud: requestCloudUpload()
case .nearbyMessage: break
}
}
}
@@ -19,6 +19,7 @@ final class DroneDockDeliveryViewController: BaseViewController {
private var pickerError: String?
private var ownedVideoURLs: Set<URL> = []
private var previousGestureEnabled: Bool?
private var onCloseSheet: (() -> Void)?
private weak var trackedNavigationController: UINavigationController?
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
@@ -50,15 +51,26 @@ final class DroneDockDeliveryViewController: BaseViewController {
ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard)
}
/// 订单列表以弹窗展示时复用上传流程,并将关闭动作纳入处理中退出确认。
func configureSheetPresentation(onClose: @escaping () -> Void) {
onCloseSheet = onClose
}
override func setupNavigationBar() {
title = "交付成片"
title = onCloseSheet == nil ? "交付成片" : "云端上传"
navigationItem.backButtonDisplayMode = .minimal
let back = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(backTapped))
let back = UIBarButtonItem(title: onCloseSheet == nil ? "返回" : "交付方式", style: .plain, target: self, action: #selector(backTapped))
back.accessibilityIdentifier = "drone.delivery.back"
navigationItem.leftBarButtonItem = back
let refresh = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshTapped))
refresh.accessibilityIdentifier = "drone.delivery.refresh"
navigationItem.rightBarButtonItem = refresh
if onCloseSheet != nil {
let close = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(closeSheetTapped))
close.accessibilityLabel = "关闭成片交付"
close.accessibilityIdentifier = "drone.delivery.sheet.close"
navigationItem.rightBarButtonItems = [close, refresh]
}
}
override func setupUI() {
@@ -110,6 +122,12 @@ final class DroneDockDeliveryViewController: BaseViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if onCloseSheet != nil {
navigationController?.setNavigationBarHidden(false, animated: false)
navigationController?.isModalInPresentation = true
navigationController?.sheetPresentationController?.detents = [.large()]
navigationController?.sheetPresentationController?.selectedDetentIdentifier = .large
}
trackedNavigationController = navigationController
if previousGestureEnabled == nil { previousGestureEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled }
guard !hasAppeared else { updateFooter(); return }
@@ -246,7 +264,7 @@ final class DroneDockDeliveryViewController: BaseViewController {
submitButton.setTitle(working ? "处理中…" : title, for: .normal)
submitButton.isEnabled = viewModel.canSubmit && !locked
submitButton.backgroundColor = submitButton.isEnabled ? DroneDockStyle.primary : DroneDockStyle.secondary.withAlphaComponent(0.45)
navigationItem.rightBarButtonItem?.isEnabled = !working && !isPicking && !isRefreshing
navigationItem.rightBarButtonItems?.first { $0.accessibilityIdentifier == "drone.delivery.refresh" }?.isEnabled = !working && !isPicking && !isRefreshing
navigationController?.interactivePopGestureRecognizer?.isEnabled = !working && !isStartingSubmission && !isPicking && (previousGestureEnabled ?? true)
}
@@ -368,14 +386,23 @@ final class DroneDockDeliveryViewController: BaseViewController {
}
@objc private func backTapped() {
guard viewModel.isSubmitting || isStartingSubmission || isPicking else { navigationController?.popViewController(animated: true); return }
requestExit { [weak self] in self?.navigationController?.popViewController(animated: true) }
}
@objc private func closeSheetTapped() {
requestExit { [weak self] in self?.onCloseSheet?() }
}
private func requestExit(_ exit: @escaping () -> Void) {
guard presentedViewController == nil else { return }
guard viewModel.isSubmitting || isStartingSubmission || isPicking else { exit(); return }
let alert = UIAlertController(title: "停止处理并返回?", message: "未完成的上传将停止。如果正在保存成片,返回素材库刷新可核对实际结果。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "继续处理", style: .cancel))
alert.addAction(UIAlertAction(title: "停止并返回", style: .destructive) { [weak self] _ in
guard let self else { return }
self.operationTask?.cancel()
self.viewModel.invalidate()
self.navigationController?.popViewController(animated: true)
exit()
})
present(alert, animated: true)
}
@@ -309,6 +309,7 @@ final class DroneDockHomeViewController: BaseViewController {
planeStatusService: DroneDockPlaneStatusAPI(client: NetworkServices.shared.apiClient),
taskCreationService: DroneDockTaskCreationAPI(client: NetworkServices.shared.apiClient),
shootService: DroneDockShootAPI(client: NetworkServices.shared.apiClient),
allowsTaskSubmission: !DeviceCommandDebugPolicy.blocksLiveRequests,
currentContext: { Self.currentContext() }
))
}
@@ -0,0 +1,365 @@
import Kingfisher
import SnapKit
import UIKit
/// 真实订单素材库摘要:游客与状态同排,次数始终来自订单详情。
@MainActor
final class DroneDockMaterialOrderCell: UICollectionViewCell {
private let customerLabel = DroneDockStyle.label(size: 19, weight: .semibold)
private let statusLabel = DroneDockStatusLabel()
private let numberLabel = DroneDockStyle.label(size: 13, color: UIColor(hex: 0x70809D))
private let countLabel = DroneDockStyle.label(size: 13, color: UIColor(hex: 0x5D6C88))
override init(frame: CGRect) {
super.init(frame: frame)
let row = UIStackView(arrangedSubviews: [customerLabel, statusLabel, UIView()])
row.axis = .horizontal
row.spacing = 8
row.alignment = .center
customerLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
customerLabel.lineBreakMode = .byTruncatingTail
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
numberLabel.numberOfLines = 2
countLabel.numberOfLines = 2
let stack = UIStackView(arrangedSubviews: [row, numberLabel, countLabel])
stack.axis = .vertical
stack.spacing = 9
contentView.addSubview(stack)
stack.snp.makeConstraints { make in
make.top.equalToSuperview().offset(16)
make.leading.trailing.equalToSuperview()
make.bottom.equalToSuperview().inset(18)
}
accessibilityIdentifier = "drone.materials.remote.order"
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 不根据任务数量或素材上传状态推导订单拍摄履约状态。
func apply(order: DroneDockHomeOrder) {
customerLabel.text = order.touristTitle
let tone: DroneDockStatusTone = switch order.shootStatus {
case "completed": .green
case "processing": .blue
case "pending": .orange
default: .gray
}
statusLabel.apply(title: order.statusTitle, tone: tone)
numberLabel.text = order.orderNumberText
let total = order.shotTotal.map(String.init) ?? "—"
let used = order.shotUsed.map(String.init) ?? "—"
let remain = order.shotRemain.map(String.init) ?? "—"
countLabel.text = "含\(total)次拍摄 · 已拍摄\(used)次 · 剩余\(remain)次"
accessibilityLabel = [order.touristTitle, order.statusTitle, order.orderNumberText, countLabel.text].compactMap { $0 }.joined(separator: ",")
}
}
/// 素材记录标题:点位和交付按钮同排,航线、时间、记录序号位于次行。
@MainActor
final class DroneDockMaterialRecordCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
private let metadataLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let deliveryButton = UIButton(type: .system)
private let emptyIcon = UIImageView()
private let emptyTitle = DroneDockStyle.label(size: 13, weight: .medium)
private let emptyDetail = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let emptyPanel = UIStackView()
private let separator = UIView()
private var action: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.numberOfLines = 1
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
deliveryButton.setContentCompressionResistancePriority(.required, for: .horizontal)
deliveryButton.tintColor = DroneDockStyle.primary
deliveryButton.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside)
let titleRow = UIStackView(arrangedSubviews: [titleLabel, UIView(), deliveryButton])
titleRow.axis = .horizontal
titleRow.alignment = .center
titleRow.spacing = 8
metadataLabel.numberOfLines = 2
emptyIcon.contentMode = .scaleAspectFit
emptyTitle.numberOfLines = 2
emptyDetail.numberOfLines = 0
emptyPanel.axis = .vertical
emptyPanel.alignment = .leading
emptyPanel.spacing = 6
let emptyHeading = UIStackView(arrangedSubviews: [emptyIcon, emptyTitle])
emptyHeading.axis = .horizontal
emptyHeading.alignment = .center
emptyHeading.spacing = 6
emptyIcon.snp.makeConstraints { $0.size.equalTo(16).priority(999) }
emptyPanel.addArrangedSubview(emptyHeading)
emptyPanel.addArrangedSubview(emptyDetail)
let stack = UIStackView(arrangedSubviews: [titleRow, metadataLabel, emptyPanel])
stack.axis = .vertical
stack.spacing = 7
stack.setCustomSpacing(14, after: metadataLabel)
contentView.addSubview(stack)
stack.snp.makeConstraints { make in
make.top.equalToSuperview().offset(14)
make.leading.trailing.equalToSuperview()
make.bottom.equalToSuperview().inset(14)
}
deliveryButton.snp.makeConstraints { $0.height.equalTo(44) }
separator.backgroundColor = DroneDockStyle.border
contentView.addSubview(separator)
separator.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(0.5) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 保留无素材任务的独立飞行与上传状态,不伪造文件或上传进度。
func apply(task: DroneDockMaterialTask, canDeliver: Bool, action: @escaping () -> Void) {
titleLabel.text = usable(task.spotName, fallback: "点位 \(task.spotID)")
let record = task.sequence.map { String(format: "记录%02d", $0) } ?? "记录序号待确认"
metadataLabel.text = "\(usable(task.airLineName, fallback: "航线待确认")) · \(shortDate(task.createdAt)) · \(record)"
var configuration = UIButton.Configuration.plain()
configuration.title = task.film == nil ? "交付成片" : "替换成片"
configuration.image = UIImage(systemName: "play.rectangle")
configuration.imagePadding = 5
configuration.contentInsets = .zero
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { value in
var attributes = value
attributes.font = .systemFont(ofSize: 12)
return attributes
}
deliveryButton.configuration = configuration
deliveryButton.isHidden = !canDeliver
deliveryButton.accessibilityIdentifier = "drone.materials.remote.delivery.\(task.id)"
self.action = action
emptyPanel.isHidden = !task.materials.isEmpty
separator.isHidden = !task.materials.isEmpty || task.film != nil
let state: (String, String, String, UIColor) = switch task.materialStatus {
case 0: ("素材待上传", "拍摄完成后将自动上传,请稍后刷新", "icloud.and.arrow.up", DroneDockStyle.secondary)
case 1: ("暂无可用原素材", "素材记录尚未返回,请刷新查看", "photo.on.rectangle", DroneDockStyle.secondary)
case 2: ("素材上传中", "素材正在上传,请稍后刷新查看", "icloud.and.arrow.up", DroneDockStyle.primary)
case 3: ("素材上传失败", "请刷新查看最新状态,或联系工作人员", "xmark.circle", DroneDockStyle.color(for: .red))
default: ("素材状态待确认", "暂无原素材,请稍后刷新查看", "questionmark.circle", DroneDockStyle.secondary)
}
emptyTitle.text = state.0
emptyTitle.textColor = state.3
emptyIcon.image = UIImage(systemName: state.2)
emptyIcon.tintColor = state.3
let film = task.film == nil ? " · 暂无视频成片" : ""
emptyDetail.text = "\(flightTitle(task.flightStatus))\(film)\n\(state.1)"
accessibilityIdentifier = "drone.materials.remote.task.\(task.id)"
}
private func usable(_ value: String?, fallback: String) -> String { DroneDockHomeMetric.usableText(value) ?? fallback }
private func shortDate(_ raw: String?) -> String {
guard let raw = DroneDockHomeMetric.usableText(raw) else { return "时间待确认" }
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let date = formatter.date(from: raw) else { return raw }
formatter.dateFormat = "MM-dd HH:mm"
return formatter.string(from: date)
}
private func flightTitle(_ value: Int?) -> String {
switch value {
case 10: "待飞行"
case 20: "执行中"
case 30: "飞行成功"
case 40: "飞行失败"
case 50: "已取消"
case 60: "待确认"
default: "飞行状态待确认"
}
}
@objc private func deliveryTapped() { action?() }
}
/// 真实文件的缩略图、状态和选择控件;预览与选择使用独立点击区域。
@MainActor
final class DroneDockMaterialMediaCell: UICollectionViewCell {
private let thumbnail = UIImageView()
private let icon = UIImageView()
private let previewButton = UIButton(type: .custom)
private let selectionButton = UIButton(type: .custom)
private let videoBadge = DroneDockStyle.label("视频", size: 10, color: .white)
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
private let stateLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let retryLabel = DroneDockStyle.label("重试上传", size: 11, color: DroneDockStyle.primary.withAlphaComponent(0.5))
private var previewAction: (() -> Void)?
private var selectionAction: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
thumbnail.contentMode = .scaleAspectFill
thumbnail.clipsToBounds = true
thumbnail.layer.cornerRadius = 6
thumbnail.layer.borderWidth = 2
thumbnail.backgroundColor = UIColor(hex: 0xE9EDF5)
thumbnail.accessibilityIdentifier = "drone.materials.remote.thumbnail"
icon.contentMode = .scaleAspectFit
titleLabel.lineBreakMode = .byTruncatingMiddle
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
retryLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
retryLabel.accessibilityTraits = [.button, .notEnabled]
retryLabel.accessibilityHint = "当前接口不支持重试上传,可通过页面刷新查看最新状态"
videoBadge.textAlignment = .center
videoBadge.backgroundColor = UIColor.black.withAlphaComponent(0.48)
videoBadge.layer.cornerRadius = 3
videoBadge.clipsToBounds = true
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
let nameRow = UIStackView(arrangedSubviews: [titleLabel, retryLabel])
nameRow.axis = .horizontal
nameRow.spacing = 4
nameRow.alignment = .center
[thumbnail, icon, previewButton, videoBadge, selectionButton, nameRow, stateLabel].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(thumbnail.snp.width).multipliedBy(9.0 / 16.0) }
icon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(28) }
previewButton.snp.makeConstraints { $0.edges.equalTo(thumbnail) }
selectionButton.snp.makeConstraints { make in make.top.trailing.equalTo(thumbnail); make.size.equalTo(44) }
videoBadge.snp.makeConstraints { make in make.leading.bottom.equalTo(thumbnail).inset(6); make.size.equalTo(CGSize(width: 32, height: 18)) }
nameRow.snp.makeConstraints { make in make.top.equalTo(thumbnail.snp.bottom).offset(7); make.leading.trailing.equalToSuperview() }
stateLabel.snp.makeConstraints { make in make.top.equalTo(nameRow.snp.bottom).offset(4); make.leading.trailing.equalToSuperview(); make.bottom.lessThanOrEqualToSuperview().inset(5) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func prepareForReuse() {
super.prepareForReuse()
thumbnail.kf.cancelDownloadTask()
thumbnail.image = nil
previewAction = nil
selectionAction = nil
}
/// 原素材上传就绪且 URL 有效才可勾选;Mock 图片存在时不请求远程缩略图。
func apply(file: DroneDockMaterialFile, taskID: Int, selected: Bool, selectionEnabled: Bool,
localImage: UIImage?, allowsRemoteImage: Bool, preview: @escaping () -> Void, select: @escaping () -> Void) {
let ready = file.previewURL != nil
let state: (String, UIColor) = switch file.uploadStatus {
case 0: ("待上传", DroneDockStyle.secondary)
case 1: (ready ? "上传完成 · 可下载" : "暂不可预览", ready ? DroneDockStyle.success : DroneDockStyle.secondary)
case 2: ("上传中", DroneDockStyle.primary)
case 3: ("上传失败", DroneDockStyle.color(for: .red))
default: ("素材状态待确认", DroneDockStyle.secondary)
}
let title = DroneDockHomeMetric.usableText(file.fileName) ?? "原素材 \(file.id)"
apply(title: title, state: state.0, color: state.1, cover: ready ? file.coverURL : nil,
fallback: ready && file.fileType == 1 ? file.previewURL : nil, video: file.fileType == 2,
enabled: ready, failed: file.uploadStatus == 3, localImage: ready ? localImage : nil,
allowsRemoteImage: allowsRemoteImage, identifier: "drone.materials.remote.file.\(taskID).\(file.id)")
previewAction = preview
selectionAction = select
selectionButton.isHidden = !ready
selectionButton.isEnabled = ready && selectionEnabled
selectionButton.accessibilityIdentifier = "drone.materials.remote.select.\(taskID).\(file.id)"
selectionButton.accessibilityLabel = "选择\(title)"
selectionButton.accessibilityTraits = selected ? [.button, .selected] : .button
selectionButton.setImage(DroneMaterialSelectionIcon.image(selected: selected, tint: selected ? DroneDockStyle.primary : .white), for: .normal)
selectionButton.imageView?.layer.shadowColor = UIColor.black.cgColor
selectionButton.imageView?.layer.shadowOpacity = 0.25
selectionButton.imageView?.layer.shadowRadius = 2
selectionButton.imageView?.layer.shadowOffset = .zero
thumbnail.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor
previewButton.accessibilityHint = file.uploadStatus == 3 ? DroneDockHomeMetric.usableText(file.failureReason) : nil
}
/// 已交付成片独立标记且不参与原素材全选。
func apply(film: DroneDockMaterialFilm, taskID: Int, localImage: UIImage?, allowsRemoteImage: Bool,
preview: @escaping () -> Void) {
let ready = film.previewURL != nil
apply(title: DroneDockHomeMetric.usableText(film.fileName) ?? "视频成片", state: ready ? "视频成片 · 点击播放" : "视频成片 · 暂不可预览",
color: ready ? DroneDockStyle.success : DroneDockStyle.secondary, cover: film.coverURL, fallback: nil,
video: true, enabled: ready, failed: false, localImage: localImage, allowsRemoteImage: allowsRemoteImage,
identifier: "drone.materials.remote.film.\(taskID).\(film.id)")
selectionButton.isHidden = true
selectionAction = nil
previewAction = preview
previewButton.accessibilityHint = nil
thumbnail.layer.borderColor = UIColor.clear.cgColor
}
private func apply(title: String, state: String, color: UIColor, cover: String?, fallback: URL?, video: Bool,
enabled: Bool, failed: Bool, localImage: UIImage?, allowsRemoteImage: Bool, identifier: String) {
thumbnail.kf.cancelDownloadTask()
thumbnail.image = localImage
let coverURL = cover.flatMap(URL.init(string:)).flatMap { url in
["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil ? url : nil
}
if allowsRemoteImage, enabled { thumbnail.kf.setImage(with: coverURL ?? fallback) }
icon.image = UIImage(systemName: failed ? "xmark.circle" : video ? "play.fill" : "photo")
icon.tintColor = failed ? DroneDockStyle.color(for: .red) : UIColor(hex: 0x9CA6B6)
icon.isHidden = enabled && (localImage != nil || coverURL != nil || fallback != nil)
titleLabel.text = title
stateLabel.text = state
stateLabel.textColor = color
retryLabel.isHidden = !failed
retryLabel.accessibilityIdentifier = identifier + ".retryUpload"
videoBadge.isHidden = !video || !enabled
previewButton.isEnabled = enabled
previewButton.accessibilityIdentifier = identifier + ".preview"
previewButton.accessibilityLabel = "\(title),\(state)"
accessibilityIdentifier = identifier
accessibilityLabel = "\(title),\(state)"
accessibilityTraits = enabled ? .button : [.notEnabled]
}
@objc private func previewTapped() { previewAction?() }
@objc private func selectionTapped() { selectionAction?() }
}
/// 居中展示列表加载、空态和错误;刷新失败与没有素材是不同状态。
@MainActor
final class DroneDockMaterialMessageCell: UICollectionViewCell {
private let icon = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 16, weight: .medium)
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let button = UIButton(type: .system)
private let spinner = UIActivityIndicatorView(style: .medium)
private var action: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
icon.contentMode = .scaleAspectFit
icon.tintColor = DroneDockStyle.secondary
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 2
detailLabel.textAlignment = .center
detailLabel.numberOfLines = 0
button.tintColor = DroneDockStyle.primary
button.addTarget(self, action: #selector(retryTapped), for: .touchUpInside)
let stack = UIStackView(arrangedSubviews: [icon, spinner, titleLabel, detailLabel, button])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 12
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.centerY.equalToSuperview(); make.leading.trailing.equalToSuperview().inset(12) }
icon.snp.makeConstraints { $0.size.equalTo(38).priority(999) }
button.snp.makeConstraints { $0.height.equalTo(44).priority(999) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 不将错误转换为空列表,未提供重试闭包时隐藏操作。
func apply(title: String, detail: String, identifier: String, loading: Bool = false,
error: Bool = false, retry: (() -> Void)? = nil) {
titleLabel.text = title
detailLabel.text = detail
detailLabel.isHidden = detail.isEmpty
icon.image = UIImage(systemName: error ? "exclamationmark.circle" : "photo.on.rectangle.angled")
icon.isHidden = loading
if loading { spinner.startAnimating() } else { spinner.stopAnimating() }
spinner.isHidden = !loading
spinner.alpha = loading ? 1 : 0
button.isHidden = retry == nil
button.setTitle("重试", for: .normal)
button.accessibilityIdentifier = "drone.materials.remote.retry"
action = retry
accessibilityIdentifier = identifier
}
@objc private func retryTapped() { action?() }
}
@@ -0,0 +1,196 @@
import SnapKit
import UIKit
#if DEBUG
/// 使用正式订单素材页和内存服务验证各展示状态,不读取登录身份或连接后端。
@MainActor
enum DroneDockMaterialsSimulation {
/// 支持显式场景参数,未传场景的模拟入口默认展示混合上传状态。
static func makeController(arguments: [String]) -> UIViewController? {
let flag = "--dock-materials-mock"
guard arguments.contains(flag) || arguments.contains(where: { $0.hasPrefix(flag + "=") }) else { return nil }
let value = arguments.first(where: { $0.hasPrefix(flag + "=") }).map { String($0.dropFirst(flag.count + 1)) }
return makeController(scenario: value ?? "mixed")
}
/// 创建全新模拟会话;同一页的点位筛选、选择及刷新仍由正式 ViewModel 执行。
static func makeController(scenario: String) -> UIViewController? {
let state = DroneDockMaterialsMockScenario(rawValue: scenario) ?? .mixed
guard let service = try? DroneDockMaterialsMockService(scenario: state) else { return nil }
let context = DroneDockHomeContext(userID: "local-materials-mock", accountType: "store_user",
scenicID: 901, scenicName: "本地模拟景区", storeID: 901,
photographerName: "本地演示", token: "local-materials-only")
let model = DroneDockMaterialsViewModel(context: context, order: service.order,
service: service, currentContext: { context })
let controller = DroneDockMaterialsViewController(viewModel: model,
deliveryControllerFactory: { _, _, _ in
DroneDockMaterialsMockPreviewController(title: "交付成片 · 本地演示", image: nil,
message: "本地演示仅验证入口,不连接云端或上传文件。")
},
thumbnailProvider: { taskID, fileID, isFilm in
guard isFilm || service.isReady(taskID: taskID, fileID: fileID) else { return nil }
return UIImage(named: taskID == 902 ? "drone_demo_pagoda" : fileID.isMultiple(of: 2) ? "drone_demo_mountain" : "drone_demo_tourists")
},
mediaPreviewControllerFactory: { _, isVideo, title in
DroneDockMaterialsMockPreviewController(title: title, image: UIImage(named: "drone_demo_tourists"),
message: isVideo ? "本地演示视频封面,不请求远程片源。" : "本地演示图片,不请求远程文件。")
})
controller.navigationItem.prompt = "本地演示 · 未联网"
return controller
}
}
/// 上传、记录及首屏异常的固定样例,不表示实际接口或设备状态。
private enum DroneDockMaterialsMockScenario: String {
case ready, uploading, uploadFailed, mixed, empty, loading, error, taskUploading, taskFailed, film
}
/// 通过正式解码器构造的纯内存素材服务,没有真实网络或共享账号依赖。
@MainActor
private final class DroneDockMaterialsMockService: DroneDockMaterialsServing {
private let scenario: DroneDockMaterialsMockScenario
private let detailValue: DroneDockMaterialDetail
private let taskValues: [[String: Any]]
/// 合成订单用于正式页面的入口身份,不可用于真实请求。
var order: DroneDockHomeOrder { detailValue.order }
/// 固定三条拍摄记录与两处购买点位,文件状态由场景决定。
init(scenario: DroneDockMaterialsMockScenario) throws {
self.scenario = scenario
let detail: [String: Any] = [
"order_number": "LOCAL-MOCK-MATERIALS-901", "project_id": 901,
"project_name": "模拟航拍套餐", "user_phone": "158****8888",
"shoot_count": 5, "shot_count": scenario == .empty ? 0 : 3,
"remaining_count": scenario == .empty ? 5 : 2, "shoot_status": "processing",
"order_status": 20, "can_upload_film": true, "can_create_task": true,
"spot": [["scenic_spot_id": 301, "scenic_spot_name": "三皇寨"],
["scenic_spot_id": 302, "scenic_spot_name": "金阙云宫"]]
]
detailValue = try JSONDecoder().decode(DroneDockMaterialDetail.self,
from: JSONSerialization.data(withJSONObject: detail))
taskValues = scenario == .empty ? [] : [3, 2, 1].map { sequence in
let taskID = 900 + sequence
let isPagoda = sequence == 2
let files: [[String: Any]] = [sequence * 2 - 1, sequence * 2].map { fileID in
let status = Self.uploadStatus(scenario: scenario, sequence: sequence, fileID: fileID)
return ["id": fileID, "file_name": String(format: "素材%02d", fileID),
"file_type": fileID.isMultiple(of: 2) ? 1 : 2,
"file_size": 4_194_304,
"file_url": status == 1 ? "https://mock.invalid/media/\(taskID)/\(fileID)" : "",
"cover_url": "", "upload_status": status,
"failure_reason": status == 3 ? "本地演示:素材上传失败,请刷新查看最新状态" : ""]
}
let taskOnly = scenario == .taskUploading || scenario == .taskFailed
var task: [String: Any] = [
"id": taskID, "order_number": "LOCAL-MOCK-MATERIALS-901", "seq": sequence,
"scenic_spot_id": isPagoda ? 302 : 301,
"scenic_spot_name": isPagoda ? "金阙云宫" : "三皇寨",
"air_line_name": isPagoda ? "云宫环绕" : "经典航线",
"created_at": "2026-10-29 \(sequence == 3 ? "14:32:00" : sequence == 2 ? "14:10:00" : "13:45:00")",
"flight_status": 30,
"material_status": scenario == .taskFailed || scenario == .uploadFailed ? 3 : scenario == .ready || scenario == .film ? 1 : 2,
"materials": taskOnly ? [] : files, "film": NSNull()
]
if scenario == .film, sequence == 3 {
task["film"] = ["id": 8001, "task_id": taskID, "file_name": "已交付成片",
"file_size": 8_388_608, "cover_url": "",
"file_url": "https://mock.invalid/film/\(taskID)"]
}
return task
}
}
/// 纯内存详情;加载场景等待取消,错误场景提供明确失败。
func detail(scenicID: Int, orderNumber: String) async throws -> DroneDockMaterialDetail {
try validate(scenicID: scenicID, orderNumber: orderNumber)
if scenario == .loading {
while true { try await Task.sleep(nanoseconds: 30_000_000_000) }
}
if scenario == .error { throw APIError.networkFailed("本地演示:订单素材读取失败,请稍后重试") }
try Task.checkCancellation()
return detailValue
}
/// 根据所选点位过滤内存任务,不发出 HTTP 请求。
func tasks(scenicID: Int, orderNumber: String, spotID: Int?) async throws -> DroneDockMaterialTasks {
try validate(scenicID: scenicID, orderNumber: orderNumber)
try Task.checkCancellation()
let values = taskValues.filter { spotID == nil || ($0["scenic_spot_id"] as? Int) == spotID }
return try JSONDecoder().decode(DroneDockMaterialTasks.self, from: JSONSerialization.data(withJSONObject: [
"order_number": orderNumber, "total": values.count, "list": values
]))
}
/// 仅就绪样例使用本地缩略图,上传中和失败仍保留页面占位样式。
func isReady(taskID: Int, fileID: Int) -> Bool {
guard let task = taskValues.first(where: { $0["id"] as? Int == taskID }),
let files = task["materials"] as? [[String: Any]],
let file = files.first(where: { $0["id"] as? Int == fileID }) else { return false }
return file["upload_status"] as? Int == 1
}
private func validate(scenicID: Int, orderNumber: String) throws {
guard scenicID == 901, orderNumber == "LOCAL-MOCK-MATERIALS-901" else {
throw APIError.networkFailed("本地素材演示不接受真实订单身份")
}
}
private static func uploadStatus(scenario: DroneDockMaterialsMockScenario, sequence: Int, fileID: Int) -> Int {
switch scenario {
case .uploading, .taskUploading: return 2
case .uploadFailed, .taskFailed: return 3
case .mixed:
if sequence == 3, fileID.isMultiple(of: 2) { return 2 }
if sequence == 2, !fileID.isMultiple(of: 2) { return 3 }
return 1
default: return 1
}
}
}
/// 图片预览及交付入口的本地占位,不使用播放器、云端上传或相册权限。
@MainActor
private final class DroneDockMaterialsMockPreviewController: BaseViewController {
private let image: UIImage?
private let message: String
private let imageView = UIImageView()
private let messageLabel = UILabel()
/// 固定当前演示内容,防止跳入真实媒体或上传服务。
init(title: String, image: UIImage?, message: String) {
self.image = image
self.message = message
super.init(nibName: nil, bundle: nil)
self.title = title
navigationItem.prompt = "本地演示 · 未联网"
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupUI() {
view.backgroundColor = .systemBackground
imageView.image = image
imageView.contentMode = .scaleAspectFit
messageLabel.text = message
messageLabel.numberOfLines = 0
messageLabel.font = .systemFont(ofSize: 14)
messageLabel.textAlignment = .center
view.addSubview(imageView)
view.addSubview(messageLabel)
}
override func setupConstraints() {
imageView.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.top.equalTo(view.safeAreaLayoutGuide).offset(24)
make.height.equalTo(view).multipliedBy(0.5)
}
messageLabel.snp.makeConstraints { make in
make.top.equalTo(imageView.snp.bottom).offset(16)
make.leading.trailing.equalTo(imageView)
}
}
}
#endif
@@ -8,6 +8,9 @@ import UIKit
final class DroneDockMaterialsViewController: BaseViewController {
/// 保存当前订单摘要、点位和任务的真实状态。
let viewModel: DroneDockMaterialsViewModel
private let thumbnailProvider: ((Int, Int, Bool) -> UIImage?)?
private let mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)?
private let footerView = DroneMaterialsFooterView()
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
/// 元数据与媒体分区独立,任务没有素材时也保留其状态。
@@ -28,8 +31,12 @@ final class DroneDockMaterialsViewController: BaseViewController {
/// 注入冻结订单范围的只读素材服务。
init(viewModel: DroneDockMaterialsViewModel,
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil) {
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil,
thumbnailProvider: ((Int, Int, Bool) -> UIImage?)? = nil,
mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? = nil) {
self.viewModel = viewModel
self.thumbnailProvider = thumbnailProvider
self.mediaPreviewControllerFactory = mediaPreviewControllerFactory
self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
@@ -43,7 +50,8 @@ final class DroneDockMaterialsViewController: BaseViewController {
override func setupNavigationBar() {
title = "订单素材库"
navigationItem.backButtonDisplayMode = .minimal
let refresh = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshTapped))
let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTapped))
refresh.accessibilityLabel = "刷新素材状态"
refresh.accessibilityIdentifier = "drone.materials.remote.refresh"
navigationItem.rightBarButtonItem = refresh
}
@@ -52,9 +60,16 @@ final class DroneDockMaterialsViewController: BaseViewController {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.showsVerticalScrollIndicator = false
collectionView.accessibilityIdentifier = "drone.materials.remote.list"
collectionView.delegate = self
collectionView.register(DroneDockMaterialTextCell.self, forCellWithReuseIdentifier: "text")
collectionView.register(DroneDockMaterialOrderCell.self, forCellWithReuseIdentifier: "order")
collectionView.register(DroneMaterialSelectionCell.self, forCellWithReuseIdentifier: "summary")
collectionView.register(DroneDockMaterialRecordCell.self, forCellWithReuseIdentifier: "record")
collectionView.register(DroneDockMaterialMessageCell.self, forCellWithReuseIdentifier: "message")
collectionView.register(DroneMaterialSeparatorView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
withReuseIdentifier: "separator")
collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "filter")
collectionView.register(DroneDockMaterialMediaCell.self, forCellWithReuseIdentifier: "media")
let refresh = UIRefreshControl()
@@ -62,6 +77,9 @@ final class DroneDockMaterialsViewController: BaseViewController {
refresh.addTarget(self, action: #selector(refreshTapped), for: .valueChanged)
collectionView.refreshControl = refresh
view.addSubview(collectionView)
view.addSubview(footerView)
footerView.accessibilityIdentifier = "drone.materials.remote.footer"
footerView.onPrimaryTap = { [weak self] in self?.downloadTapped() }
configureDataSource()
applySnapshot(animated: false)
}
@@ -69,8 +87,10 @@ final class DroneDockMaterialsViewController: BaseViewController {
override func setupConstraints() {
collectionView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.bottom.equalToSuperview()
make.leading.trailing.equalToSuperview()
make.bottom.equalTo(footerView.snp.top)
}
footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
}
override func viewWillAppear(_ animated: Bool) {
@@ -101,60 +121,81 @@ final class DroneDockMaterialsViewController: BaseViewController {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] collection, path, item in
guard let self else { return nil }
switch item {
case .order:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DroneDockMaterialOrderCell
if let order = self.viewModel.detail?.order { cell.apply(order: order) }
return cell
case .summary:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "summary", for: path) as! DroneMaterialSelectionCell
cell.apply(recordCount: self.viewModel.total ?? 0,
allSelected: self.viewModel.allDownloadableSelected,
enabled: self.operation == nil && !self.viewModel.selectableMaterialIDs.isEmpty)
cell.accessibilityIdentifier = "drone.materials.remote.summary"
cell.onSelectAllTap = { [weak self] in
guard let self, self.operation == nil else { return }
self.viewModel.toggleSelectAll()
self.applySnapshot(animated: false)
}
return cell
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 .task(let taskID):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "record", for: path) as! DroneDockMaterialRecordCell
if let task = self.task(taskID) {
cell.apply(task: task, canDeliver: self.operation == nil && self.viewModel.detail?.order.canUploadFilm == true) { [weak self] in
self?.openDelivery(taskID: taskID)
}
}
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)
let identity = DroneDockMaterialSelectionID(taskID: taskID, fileID: fileID)
cell.apply(file: file, taskID: taskID,
selected: self.viewModel.selectedMaterialIDs.contains(identity),
selectionEnabled: self.operation == nil && self.viewModel.selectableMaterialIDs.contains(identity),
localImage: self.thumbnailProvider?(taskID, fileID, false),
allowsRemoteImage: self.thumbnailProvider == nil,
preview: { [weak self] in self?.previewFile(taskID: taskID, fileID: fileID) },
select: { [weak self] in
guard let self, self.operation == nil else { return }
self.viewModel.toggleSelection(taskID: taskID, fileID: fileID)
self.applySnapshot(animated: false)
})
}
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) }
if let film = self.task(taskID)?.film {
cell.apply(film: film, taskID: taskID, localImage: self.thumbnailProvider?(taskID, film.id, true),
allowsRemoteImage: self.thumbnailProvider == nil) { [weak self] in self?.previewFilm(taskID: taskID) }
}
return cell
default:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! DroneDockMaterialTextCell
self.configureText(cell, item: item)
case .message:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DroneDockMaterialMessageCell
self.configureMessage(cell)
return cell
}
}
dataSource.supplementaryViewProvider = { collection, kind, path in
collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "separator", for: path)
}
}
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("暂无视频成片") }
let canDeliver = operation == nil && viewModel.detail?.order.canUploadFilm == true
cell.apply(title: title, body: lines.joined(separator: "\n"), identifier: "drone.materials.remote.task.\(id)",
button: canDeliver ? (task.film == nil ? "交付成片" : "替换成片") : nil,
actionID: "drone.materials.remote.delivery.\(id)") { [weak self] in self?.openDelivery(taskID: 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 configureMessage(_ cell: DroneDockMaterialMessageCell) {
if operation != nil || viewModel.isLoading || viewModel.isLoadingTasks {
cell.apply(title: viewModel.detail == nil ? "正在加载订单素材库" : "正在加载任务素材",
detail: "请稍候", identifier: "drone.materials.remote.loading", loading: true)
} else if let error = viewModel.detailErrorMessage {
cell.apply(title: "订单信息加载失败", detail: error, identifier: "drone.materials.remote.error", error: true) { [weak self] in self?.load(.refresh) }
} else if let error = viewModel.tasksErrorMessage {
cell.apply(title: "任务素材加载失败", detail: error, identifier: "drone.materials.remote.error", error: true) { [weak self] in self?.load(.retry) }
} else {
cell.apply(title: displayedSpotID == nil ? "暂无任务记录" : "当前点位暂无任务记录",
detail: "拍摄任务与素材更新后,可下拉刷新查看", identifier: "drone.materials.remote.empty")
}
}
@@ -175,22 +216,33 @@ final class DroneDockMaterialsViewController: BaseViewController {
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)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 9 / 16 + 51)), 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
section.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(1)),
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom)]
return section
case .message:
return self.singleColumnSection(height: .absolute(250))
case .summary:
return self.singleColumnSection(height: .absolute(46))
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
return self.singleColumnSection(height: .estimated(90))
}
}
}
private func singleColumnSection(height: NSCollectionLayoutDimension) -> NSCollectionLayoutSection {
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: height))
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>()
@@ -217,6 +269,11 @@ final class DroneDockMaterialsViewController: BaseViewController {
snapshot.appendSections([.message])
snapshot.appendItems([.message], toSection: .message)
}
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "",
primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line",
enabled: operation == nil && viewModel.selectedCount > 0,
identifier: "drone.materials.remote.download", progress: nil,
trailingText: "仅可选择已上传素材")
let previous = Set(dataSource.snapshot().itemIdentifiers)
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) })
dataSource.apply(snapshot, animatingDifferences: animated)
@@ -250,8 +307,25 @@ final class DroneDockMaterialsViewController: BaseViewController {
navigationController.pushViewController(deliveryControllerFactory(order, viewModel.context, taskID), animated: true)
}
private func downloadTapped() {
guard operation == nil, viewModel.selectedCount > 0 else { return }
showAlert(title: "下载功能暂未开放", message: "已选择的素材会保留。当前版本尚未接入下载和保存相册功能。")
}
private func previewFile(taskID: Int, fileID: Int) {
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 ?? "原素材")
}
private func previewFilm(taskID: Int) {
guard operation == nil, let film = task(taskID)?.film, let url = film.previewURL else { return }
preview(url: url, isVideo: true, title: film.fileName ?? "视频成片")
}
private func preview(url: URL, isVideo: Bool, title: String) {
if isVideo {
if let mediaPreviewControllerFactory {
navigationController?.pushViewController(mediaPreviewControllerFactory(url, isVideo, title), animated: true)
} else if isVideo {
let player = AVPlayerViewController()
player.player = AVPlayer(url: url)
present(player, animated: true) { player.player?.play() }
@@ -264,17 +338,7 @@ final class DroneDockMaterialsViewController: BaseViewController {
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 {
@@ -286,138 +350,14 @@ extension DroneDockMaterialsViewController: UICollectionViewDelegate {
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 ?? "原素材")
previewFile(taskID: taskID, fileID: fileID)
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 ?? "视频成片")
previewFilm(taskID: taskID)
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 {
@@ -16,6 +16,7 @@ final class DroneDockOrdersViewController: BaseViewController {
private var dataSource: UICollectionViewDiffableDataSource<Int, Item>!
private var loadTask: Task<Void, Never>?
private var operation: LoadAction?
private weak var deliverySheet: UINavigationController?
/// 使用订单号更新同一张卡片,空态和分页入口也纳入快照。
private enum Item: Hashable { case order(String), message, more }
@@ -92,11 +93,13 @@ final class DroneDockOrdersViewController: BaseViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard deliverySheet == nil else { return }
load(.refresh)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
guard deliverySheet == nil else { return }
loadTask?.cancel()
operation = nil
collectionView.refreshControl?.endRefreshing()
@@ -205,9 +208,16 @@ final class DroneDockOrdersViewController: BaseViewController {
private func showUnavailable(_ feature: String) { showAlert(title: feature, message: "该功能暂未开放") }
private func openDelivery(orderID: String) {
guard operation == nil, let order = viewModel.orders.first(where: { $0.orderID == orderID }),
guard operation == nil, presentedViewController == nil,
let order = viewModel.orders.first(where: { $0.orderID == orderID }),
order.canUploadFilm == true else { return }
navigationController?.pushViewController(deliveryControllerFactory(order, viewModel.context, nil), animated: true)
let sheet = DroneDockDeliveryEntry.makeMethodSheet(order: order, context: viewModel.context,
controllerFactory: deliveryControllerFactory) { [weak self] in
guard let self, self.viewIfLoaded?.window != nil else { return }
self.load(.refresh)
}
deliverySheet = sheet
present(sheet, animated: true)
}
private func openMaterials(orderID: String) {
@@ -6,6 +6,12 @@ import UIKit
enum DroneDockPreview {
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
static func navigationController(arguments: [String]) -> UINavigationController? {
if let materials = DroneDockMaterialsSimulation.makeController(arguments: arguments) {
return UINavigationController(rootViewController: materials)
}
if let simulation = DroneDockStartShootSimulation.makeController(arguments: arguments) {
return UINavigationController(rootViewController: simulation)
}
// 仅打开已存在任务进行只读联调;不经过创建或召唤流程。
if let taskArgument = arguments.first(where: { $0.hasPrefix("--dock-task-live=") }),
let taskID = Int(taskArgument.dropFirst("--dock-task-live=".count)), taskID > 0,
@@ -26,12 +26,15 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
private var isApplicationActive = false
private var automaticallyOpenedTaskID: Int?
private let taskControllerFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private let simulationRecordsProvider: (@MainActor () -> String)?
/// 注入准备页业务状态和轮询等待,便于验证任务创建及页面生命周期。
init(viewModel: DroneDockPreparationViewModel,
taskControllerFactory: (@MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil,
planeStatusPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.viewModel = viewModel
self.simulationRecordsProvider = simulationRecordsProvider
self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in
DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context)
}
@@ -51,8 +54,42 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
}
override func setupNavigationBar() {
title = "拍摄准备"
title = simulationRecordsProvider == nil ? "拍摄准备" : "拍摄准备 · 本地模拟"
navigationItem.backButtonDisplayMode = .minimal
if simulationRecordsProvider != nil {
let records = UIBarButtonItem(image: UIImage(systemName: "doc.text"), style: .plain,
target: self, action: #selector(showSimulationRecords))
records.accessibilityLabel = "查看模拟接口回执"
records.accessibilityIdentifier = "drone.preparation.mock.recordsButton"
navigationItem.rightBarButtonItem = records
}
#if DEBUG
if simulationRecordsProvider == nil, DeviceCommandDebugPolicy.blocksLiveRequests,
viewModel.isTaskSubmissionBlocked {
let simulation = UIBarButtonItem(title: "本地模拟", style: .plain,
target: self, action: #selector(openLocalSimulation))
simulation.accessibilityIdentifier = "drone.preparation.mock.entry"
navigationItem.rightBarButtonItem = simulation
}
#endif
}
#if DEBUG
/// 打开独立模拟订单,不沿用真实会话、服务或当前订单创建任务。
@objc private func openLocalSimulation() {
guard !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning,
let navigationController, navigationController.topViewController === self,
let controller = DroneDockStartShootSimulation.makePreparationController() else { return }
navigationController.pushViewController(controller, animated: true)
}
#endif
/// 显示内存传输记录,并明确说明其不是后端真实回执。
@objc private func showSimulationRecords() {
guard let simulationRecordsProvider, presentedViewController == nil,
!isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning else { return }
let controller = DroneDockSimulationRecordsViewController(records: simulationRecordsProvider())
present(UINavigationController(rootViewController: controller), animated: true)
}
override func setupUI() {
@@ -200,7 +237,8 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
if viewModel.errorMessage != nil {
applySnapshot(animated: false)
} else {
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation,
isLocalSimulation: simulationRecordsProvider != nil)
}
return viewModel.pollIntervalNanoseconds
}
@@ -214,7 +252,8 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
@objc private func applicationWillResignActive() {
isApplicationActive = false
stopPlaneStatusPolling()
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation,
isLocalSimulation: simulationRecordsProvider != nil)
}
@objc private func applicationDidBecomeActive() {
@@ -290,6 +329,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
}
private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) {
navigationItem.rightBarButtonItem?.isEnabled = !isStartingCreation && !viewModel.isCreatingTask && !viewModel.isSummoning
guard dataSource != nil else { return }
let previous = dataSource.snapshot()
let existing = Set(previous.itemIdentifiers)
@@ -312,7 +352,8 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
snapshot.appendItems([.shootResult], toSection: .shootResult)
}
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation)
footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation,
isLocalSimulation: simulationRecordsProvider != nil)
let previousPointCount = previous.sectionIdentifiers.contains(.points) ? previous.numberOfItems(inSection: .points) : 0
let previousRouteCount = previous.sectionIdentifiers.contains(.routes) ? previous.numberOfItems(inSection: .routes) : 0
let layoutChanged = previousPointCount != snapshot.numberOfItems(inSection: .points)
@@ -1,7 +1,7 @@
import SnapKit
import UIKit
/// 真实拍摄任务页:进入后仅查询同一任务,展示状态与遥测,不发送飞行控制。
/// 拍摄任务页:真实入口只读,本地模拟入口可注入开始拍摄服务验证接口流程。
@MainActor
final class DroneDockShootingTaskViewController: BaseViewController {
/// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。
@@ -20,16 +20,21 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private var compactLayout: Bool?
private var bottomInset: CGFloat = -1
private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
private let simulationRecordsProvider: (@MainActor () -> String)?
private var refreshTask: Task<Void, Never>?
private var startTask: Task<Void, Never>?
private var requestGeneration = 0
private var isPageVisible = false
private var isApplicationActive = false
private var isRequesting = false
private var isStartingAction = false
/// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。
init(viewModel: DroneDockShootingTaskViewModel,
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) {
materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil,
simulationRecordsProvider: (@MainActor () -> String)? = nil) {
self.viewModel = viewModel
self.simulationRecordsProvider = simulationRecordsProvider
self.materialsControllerFactory = materialsControllerFactory ?? { order, context in
DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel(
context: context, order: order,
@@ -45,18 +50,26 @@ final class DroneDockShootingTaskViewController: BaseViewController {
deinit {
refreshTask?.cancel()
startTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
/// 使用常规导航返回准备页,不劫持返回手势或自动创建任务。
override func setupNavigationBar() {
title = "拍摄任务"
title = simulationRecordsProvider == nil ? "拍摄任务" : "拍摄任务 · 本地模拟"
navigationItem.backButtonDisplayMode = .minimal
let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain,
target: self, action: #selector(refreshTriggered))
refresh.accessibilityLabel = "刷新任务状态"
refresh.accessibilityIdentifier = "drone.task.remote.navigationRefresh"
navigationItem.rightBarButtonItem = refresh
if simulationRecordsProvider != nil {
let records = UIBarButtonItem(image: UIImage(systemName: "doc.text"), style: .plain,
target: self, action: #selector(showSimulationRecords))
records.accessibilityLabel = "查看模拟接口回执"
records.accessibilityIdentifier = "drone.task.mock.recordsButton"
navigationItem.rightBarButtonItems = [refresh, records]
}
}
/// 顶部、中间状态和安全控制分开布局,状态切换不影响外部区域大小。
@@ -139,7 +152,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
taskTitleLabel.font = .systemFont(ofSize: compact ? 16 : 17, weight: .semibold)
}
/// 仅绑定读取、详情和已有素材入口;本轮不发送飞控指令。
/// 模拟服务明确注入时才允许开始;真实入口仍只提供读取、详情和已有素材。
override func bindActions() {
statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() }
statusView.onDetails = { [weak self] in self?.showStatusDetails() }
@@ -166,7 +179,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
private func applySnapshot() {
guard isViewLoaded else { return }
let loading = isRequesting || viewModel.isLoading
let loading = isRequesting || viewModel.isLoading || isStartingAction || viewModel.isStartingShooting
taskTitleLabel.text = viewModel.title
subtitleLabel.text = viewModel.subtitle
let telemetry = viewModel.telemetry
@@ -178,21 +191,24 @@ final class DroneDockShootingTaskViewController: BaseViewController {
deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation
statusView.apply(value, isRefreshing: loading)
statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItem?.isEnabled = isPageVisible && isApplicationActive && !loading
navigationItem.rightBarButtonItems?.forEach { $0.isEnabled = isPageVisible && isApplicationActive && !loading }
navigationItem.rightBarButtonItem?.accessibilityValue = loading ? "正在刷新" : nil
}
private func primaryActionTriggered() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting else { return }
let state = viewModel.presentation
guard state.isActionEnabled else { return }
switch state.action {
case .refresh:
refreshTaskIfVisible()
case .start:
startShootingIfAllowed()
case .materials:
guard let navigationController, navigationController.topViewController === self else { return }
navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true)
case .start, .resume, .retry, .none:
case .resume, .retry, .none:
break
}
}
@@ -204,6 +220,7 @@ final class DroneDockShootingTaskViewController: BaseViewController {
if viewModel.response != nil, let error = viewModel.errorMessage {
texts.append("刷新失败,当前显示上次数据:\(error)")
}
if let error = viewModel.startErrorMessage { texts.append(error) }
var distinct: [String] = []
for text in texts where !distinct.contains(text) { distinct.append(text) }
let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert)
@@ -213,7 +230,8 @@ final class DroneDockShootingTaskViewController: BaseViewController {
/// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。
private func refreshTaskIfVisible() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return }
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading,
!isStartingAction, !viewModel.isStartingShooting else { return }
requestGeneration &+= 1
let generation = requestGeneration
isRequesting = true
@@ -236,11 +254,44 @@ final class DroneDockShootingTaskViewController: BaseViewController {
requestGeneration &+= 1
refreshTask?.cancel()
refreshTask = nil
startTask?.cancel()
startTask = nil
isStartingAction = false
isRequesting = false
viewModel.invalidate(preservingSnapshot: true)
applySnapshot()
}
/// 点击后的同步锁覆盖 Task 调度间隙,回执成功后的单次回查由 ViewModel 协调。
private func startShootingIfAllowed() {
guard !isStartingAction, viewModel.canStartShooting else { return }
requestGeneration &+= 1
let generation = requestGeneration
isStartingAction = true
applySnapshot()
startTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.startShooting { [weak self] in self?.applySnapshot() }
guard self.isPageVisible, self.isApplicationActive,
self.requestGeneration == generation, !Task.isCancelled else { return }
self.startTask = nil
self.isStartingAction = false
self.applySnapshot()
if let error = self.viewModel.startErrorMessage {
self.showToast(error)
} else if let error = self.viewModel.errorMessage {
self.showToast("开始请求已受理,状态刷新失败:\(error)")
}
}
}
/// 模拟入口专用记录页,内容由内存传输提供,不请求后端日志或设备。
@objc private func showSimulationRecords() {
guard let simulationRecordsProvider, presentedViewController == nil else { return }
let controller = DroneDockSimulationRecordsViewController(records: simulationRecordsProvider())
present(UINavigationController(rootViewController: controller), animated: true)
}
@objc private func refreshTriggered() {
guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else {
return
@@ -260,6 +311,44 @@ final class DroneDockShootingTaskViewController: BaseViewController {
}
}
/// 以可选择的 JSON 文本展示本地模拟请求与回执,避免与真实接口联调混淆。
@MainActor
final class DroneDockSimulationRecordsViewController: BaseViewController {
private let records: String
private let textView = UITextView()
/// 固定展示打开时的内存记录快照。
init(records: String) {
self.records = records
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() {
title = "本地模拟回执(未联网)"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .done,
target: self, action: #selector(close))
}
override func setupUI() {
view.backgroundColor = .systemBackground
textView.isEditable = false
textView.font = .monospacedSystemFont(ofSize: 12, weight: .regular)
textView.text = records
textView.accessibilityIdentifier = "drone.task.mock.records"
textView.textContainerInset = UIEdgeInsets(top: 16, left: 12, bottom: 24, right: 12)
view.addSubview(textView)
}
override func setupConstraints() {
textView.snp.makeConstraints { make in make.edges.equalTo(view.safeAreaLayoutGuide) }
}
@objc private func close() { dismiss(animated: true) }
}
/// 固定底部的安全控制占位,尚未接入控制接口时不提供可执行的飞控动作。
@MainActor
private final class DroneDockTaskSafetyView: UIView {
@@ -0,0 +1,300 @@
import Foundation
import UIKit
#if DEBUG
/// 独立的准备、召唤与开拍模拟入口;所有请求在内存中处理,不复用账号或真实网络服务。
@MainActor
enum DroneDockStartShootSimulation {
/// 显式启动参数选择准备页或任务页,两个入口始终使用隔离的模拟会话。
static func makeController(arguments: [String]) -> UIViewController? {
let startsAtPreparation = arguments.contains("--dock-preparation-mock")
guard startsAtPreparation || arguments.contains("--dock-start-shoot-mock") else { return nil }
let resultArgument = arguments.first { $0.hasPrefix("--dock-start-shoot-result=") }
let result = resultArgument.flatMap {
DroneDockStartShootMockResult(rawValue: String($0.dropFirst("--dock-start-shoot-result=".count)))
} ?? .success
return makeFlow(result: result, startsAtPreparation: startsAtPreparation)
}
/// 从正式准备页进入全新的纯内存模拟,不携带真实订单、账号或设备身份。
static func makePreparationController() -> DroneDockRemotePreparationViewController? {
makeFlow(result: .success, startsAtPreparation: true) as? DroneDockRemotePreparationViewController
}
private static func makeFlow(result: DroneDockStartShootMockResult,
startsAtPreparation: Bool) -> UIViewController? {
let session = DroneDockStartShootMockSession(result: result, requiresPreparation: startsAtPreparation)
let environment = APIEnvironment(baseURL: URL(string: "https://mock.invalid")!,
webSocketURL: URL(string: "wss://mock.invalid/unused")!)
let client = APIClient(environment: environment, session: session)
let context = DroneDockHomeContext(userID: "local-start-shoot-mock", accountType: "store_user",
scenicID: 128, scenicName: "本地模拟景区", storeID: 38,
photographerName: "模拟操作员", token: "local-simulation-only")
let orderData = Data(#"{"order_number":"LOCAL-MOCK-ORDER-901","project_id":101,"project_name":"模拟五次套餐","user_phone":"本地模拟游客","shoot_count":5,"shot_count":0,"remaining_count":5}"#.utf8)
guard let order = try? JSONDecoder().decode(DroneDockHomeOrder.self, from: orderData) else { return nil }
let taskFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController = { taskID, taskOrder, taskContext in
let model = DroneDockShootingTaskViewModel(context: taskContext, taskID: taskID, order: taskOrder,
service: DroneDockShootingAPI(client: client),
startService: DroneDockStartShootAPI(client: client), currentContext: { context })
return DroneDockShootingTaskViewController(viewModel: model,
materialsControllerFactory: { _, _ in
let unavailable = UIViewController()
unavailable.title = "本地模拟不连接素材库"
unavailable.view.backgroundColor = .systemBackground
return unavailable
},
simulationRecordsProvider: { session.transcriptJSON })
}
guard startsAtPreparation else { return taskFactory(901, order, context) }
let model = DroneDockPreparationViewModel(context: context, order: order,
service: DroneDockPreparationAPI(client: client),
planeStatusService: DroneDockPlaneStatusAPI(client: client),
taskCreationService: DroneDockTaskCreationAPI(client: client),
shootService: DroneDockShootAPI(client: client), allowsTaskSubmission: true,
currentContext: { context })
return DroneDockRemotePreparationViewController(viewModel: model,
taskControllerFactory: taskFactory,
simulationRecordsProvider: { session.transcriptJSON })
}
}
/// 模拟开拍请求的三种结果,不构成真实接口结果或设备执行反馈。
private enum DroneDockStartShootMockResult: String {
case success
case businessFailure = "business-failure"
case timeout
}
/// 无任何网络转发能力的响应替身;仅接受 mock.invalid 上约定的准备、模拟召唤和开拍请求。
private final class DroneDockStartShootMockSession: LocalSimulationURLSession {
private let result: DroneDockStartShootMockResult
private let lock = NSLock()
private var hasCreated: Bool
private var hasSummoned: Bool
private var hasStarted = false
private var exchanges: [Exchange] = []
/// 固定当前实例结果,不能用参数切换到真实传输。
init(result: DroneDockStartShootMockResult, requiresPreparation: Bool) {
self.result = result
hasCreated = !requiresPreparation
hasSummoned = !requiresPreparation
}
/// 全部本地请求及完整模拟回执;任务、设备、游客均为虚构测试身份。
var transcriptJSON: String {
let records = lock.withLock { exchanges }
let items: [[String: Any]] = records.map { record in
var item: [String: Any] = ["method": record.request.httpMethod ?? "",
"path": record.request.url?.path ?? ""]
if let query = record.request.url?.query { item["query"] = query }
if let body = record.request.httpBody {
item["request_body"] = (try? JSONSerialization.jsonObject(with: body)) ?? String(decoding: body, as: UTF8.self)
}
if let response = record.responseData {
item["http_status"] = 200
item["response_body"] = (try? JSONSerialization.jsonObject(with: response)) ?? String(decoding: response, as: UTF8.self)
}
if let error = record.error { item["error"] = error }
return item
}
let object: [String: Any] = ["source": "local_mock", "description": "纯内存模拟,未调用后端或设备",
"network_sent": false, "scenario": result.rawValue, "records": items]
guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) else {
return "本地模拟记录暂不可显示;没有网络请求。"
}
return String(decoding: data, as: UTF8.self)
}
/// 模拟少量等待后返回内存响应,任何未知请求均在本机失败,绝不回退真实请求。
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
print("[LOCAL MOCK][Request] \(request.httpMethod ?? "") \(request.url?.absoluteString ?? "") — 不联网")
if let body = request.httpBody { print(String(decoding: body, as: UTF8.self)) }
do {
try Task.checkCancellation()
if request.httpMethod == "POST" { try await Task.sleep(nanoseconds: 400_000_000) }
try Task.checkCancellation()
let data = try lock.withLock { try responseData(for: request) }
lock.withLock { exchanges.append(Exchange(request: request, responseData: data, error: nil)) }
guard let url = request.url,
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) else {
throw URLError(.badURL)
}
print("[LOCAL MOCK][Response] \(String(decoding: data, as: UTF8.self))")
return (data, response)
} catch {
let message = error is CancellationError ? "本地模拟请求取消" : error.localizedDescription
lock.withLock { exchanges.append(Exchange(request: request, responseData: nil, error: message)) }
print("[LOCAL MOCK][Error] \(message) — 没有网络或设备指令")
throw error
}
}
private func responseData(for request: URLRequest) throws -> Data {
guard let url = request.url, url.scheme == "https", url.host == "mock.invalid" else {
throw URLError(.unsupportedURL)
}
if request.httpMethod == "GET", url.path == "/api/yf-handset-app/photog/multi-plane/project-info" {
guard queryMatches(url, required: ["scenic_id": "128", "project_id": "101",
"order_number": "LOCAL-MOCK-ORDER-901"]) else { throw URLError(.badURL) }
var payload = orderData()
payload["spot"] = [["scenic_spot_id": 301, "scenic_spot_name": "模拟点位", "available": true,
"air_lines": [["air_line_id": 401, "air_line_name": "模拟航线",
"available": true, "samples": []]]]]
return try envelope(payload)
}
if request.httpMethod == "GET", url.path == "/api/app/airport/plane-status" {
guard queryMatches(url, required: ["scenic_id": "128", "live_battery": "1"]) else { throw URLError(.badURL) }
let plane: [String: Any] = ["id": 201, "name": "本地模拟无人机", "sn_number": "LOCAL-MOCK-PLANE-201",
"online_status": 1, "work_status": 1, "work_status_label": "空闲(模拟)",
"status_text": "本地模拟 · 电量 95%", "battery_percent": 95,
"can_fly": true, "is_receive_order": 1]
return try envelope(["scenic_id": 128, "connected": true, "planes": [plane],
"recommend": plane, "poll_hint_ms": 30000])
}
if request.httpMethod == "POST", url.path == "/api/yf-handset-app/photog/multi-plane/tasks/create" {
guard url.query == nil, let body = request.httpBody,
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
Set(object.keys) == ["scenic_id", "order_number", "scenic_spot_id", "air_line_id"],
let values = try? JSONDecoder().decode(CreateBody.self, from: body),
values.scenicID == 128, values.orderNumber == "LOCAL-MOCK-ORDER-901",
values.spotID == 301, values.airLineID == 401 else { throw URLError(.badURL) }
guard !hasCreated else { return try envelope([:], code: 100099, message: "本地模拟:任务已经创建") }
hasCreated = true
var payload = orderData()
payload["task_id"] = 901
return try envelope(payload)
}
if request.httpMethod == "POST", url.path == "/api/app/airport/shoot" {
guard url.query == nil, let body = request.httpBody,
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
Set(object.keys) == ["id", "restart"],
let values = try? JSONDecoder().decode(ShootBody.self, from: body),
values.id == 901, !values.restart else { throw URLError(.badURL) }
guard hasCreated, !hasSummoned else {
return try envelope([:], code: 100099, message: "本地模拟:任务尚未创建或已召唤")
}
hasSummoned = true
return try envelope(["order_flight_task": taskData(), "order_flight_task_id": 901,
"plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
"task_uuid": "LOCAL-MOCK-TASK-UUID-901",
"ui": ["phase": "arrived_pending_start", "title": "无人机已到达(模拟)",
"message": "本地模拟召唤成功,没有网络或设备指令。"]])
}
if request.httpMethod == "GET", url.path == "/api/app/airport/shooting" {
let query = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
guard query.filter({ $0.name == "id" }).map(\.value) == ["901"] else {
throw URLError(.badURL)
}
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
return try envelope(shootingData())
}
guard request.httpMethod == "POST", url.path == "/api/app/airport/start-shoot",
url.query == nil, let body = request.httpBody,
let object = try JSONSerialization.jsonObject(with: body) as? [String: Any],
Set(object.keys) == ["id"],
(try? JSONDecoder().decode(StartBody.self, from: body).id) == 901 else {
throw URLError(.unsupportedURL)
}
guard hasSummoned else { return try envelope([:], code: 100099, message: "本地模拟:请先完成模拟召唤") }
guard !hasStarted else {
return try envelope([:], code: 100099, message: "本地模拟:该任务已开始,请读取任务状态")
}
switch result {
case .businessFailure:
return try envelope([:], code: 100099, message: "本地模拟:电量不足,暂不可开始拍摄")
case .timeout:
throw URLError(.timedOut)
case .success:
hasStarted = true
return try envelope([
"task_uuid": "LOCAL-MOCK-TASK-UUID-901", "order_flight_task_id": 901,
"order_flight_task": taskData(), "plane_id": 201, "airport_sn": "LOCAL-MOCK-DOCK-201",
"ui": ["phase": "shooting", "title": "无人机正在拍摄中(模拟)",
"message": "本地模拟开拍回执,不代表真实设备执行。", "primary_action": "shooting",
"commands": [["command": "flighttask_pause", "label": "紧急暂停", "sub": "悬停待命"],
["command": "return_home", "label": "立即返航", "sub": "中断任务"]]]
])
}
}
private func queryMatches(_ url: URL, required: [String: String]) -> Bool {
let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
return items.count == required.count && required.allSatisfy { key, value in
items.filter { $0.name == key }.map(\.value) == [value]
}
}
private func orderData() -> [String: Any] {
["order_number": "LOCAL-MOCK-ORDER-901", "project_id": 101, "project_name": "模拟五次套餐",
"user_phone": "本地模拟游客", "shoot_count": 5, "shot_count": 0, "remaining_count": 5,
"shoot_status": "processing", "order_status": 20, "can_create_task": true,
"can_upload_film": false, "can_confirm": false, "film_count": 0]
}
private func shootingData() -> [String: Any] {
["order_number": "LOCAL-MOCK-ORDER-901", "order_flight_task": taskData(), "task": taskData(),
"scenic": ["id": 128, "name": "本地模拟景区"],
"scenic_spot": ["id": 301, "name": "模拟点位"],
"air_line": ["id": 401, "name": "模拟航线", "scenic_spot_id": 301],
"header": ["order_number": "LOCAL-MOCK-ORDER-901", "title": "模拟点位 · 模拟航线",
"tourist_label": "本地模拟,无设备指令", "package_name": "模拟套餐 · 含5次拍摄"],
"current_plane": ["id": 201, "sn_number": "LOCAL-MOCK-PLANE-201", "online_status": 1,
"work_status": hasStarted ? 2 : 1, "work_status_label": hasStarted ? "拍摄中" : "空闲",
"status_text": hasStarted ? "模拟拍摄中 · 电量95%" : "模拟就绪 · 电量95%"],
"metrics": [["key": "battery", "value": "95%"], ["key": "env_temp", "value": "20.3℃"],
["key": "wind_speed", "value": "0m/s"], ["key": "rainfall", "value": "无雨"],
["key": "signal", "value": "良好"], ["key": "satellite", "value": "36颗"]],
"plane_status": ["scenic_id": 128, "connected": true, "poll_hint_ms": 5000],
"execute_gate": ["can_execute": !hasStarted, "code": hasStarted ? "already_started" : "ok",
"message": hasStarted ? "本地模拟:开拍已受理" : "本地模拟:允许验证开拍请求",
"primary_action": hasStarted ? "shooting" : "start_shoot",
"primary_action_label": hasStarted ? "拍摄中" : "开始拍摄"],
"ui": ["phase": hasStarted ? "shooting" : "arrived_pending_start",
"title": hasStarted ? "无人机正在拍摄中(模拟)" : "无人机已到达(模拟)",
"message": hasStarted ? "本地模拟状态回查:拍摄中,未向设备发送指令。" : "点击开始拍摄,仅验证本地接口流程。"]]
}
private func taskData() -> [String: Any] {
["id": 901, "order_number": "LOCAL-MOCK-ORDER-901", "scenic_id": 128,
"status": 20, "status_label": "执行中(模拟)", "wayline_status": 20, "wayline_status_label": "执行中(模拟)"]
}
private func envelope(_ data: [String: Any], code: Int = 100000, message: String = "local mock success") throws -> Data {
try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": data],
options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
}
/// 完整记录每次本地请求结果,数据不落到真实接口或共享会话中。
private struct Exchange {
let request: URLRequest
let responseData: Data?
let error: String?
}
/// 创建模拟任务仍验证真实合同的四项身份,不接受其他订单或航线。
private struct CreateBody: Decodable {
let scenicID: Int
let orderNumber: String
let spotID: Int
let airLineID: Int
/// 张工任务创建请求字段。
private enum CodingKeys: String, CodingKey {
case scenicID = "scenic_id", orderNumber = "order_number"
case spotID = "scenic_spot_id", airLineID = "air_line_id"
}
}
/// 召唤只接受同一模拟任务且禁止重启,不产生真实设备操作。
private struct ShootBody: Decodable {
let id: Int
let restart: Bool
}
/// 用强类型解码确认本地开拍请求的 id 为整数。
private struct StartBody: Decodable {
let id: Int
}
}
#endif
@@ -1,6 +1,34 @@
import SnapKit
import UIKit
/// 缩略图上的选择圆圈,显式绘制白色勾选以免透出背景图片。
@MainActor
enum DroneMaterialSelectionIcon {
/// 使用固定配色绘制选择状态,避免按钮重新应用系统 tint。
static func image(selected: Bool, tint: UIColor, opacity: CGFloat = 1) -> UIImage {
UIGraphicsImageRenderer(size: CGSize(width: 24, height: 24)).image { context in
context.cgContext.setAlpha(opacity)
let circle = UIBezierPath(ovalIn: CGRect(x: 1, y: 1, width: 22, height: 22))
tint.set()
if selected {
circle.fill()
UIColor.white.setStroke()
let check = UIBezierPath()
check.move(to: CGPoint(x: 6.5, y: 12))
check.addLine(to: CGPoint(x: 10.5, y: 16))
check.addLine(to: CGPoint(x: 17.5, y: 7.5))
check.lineWidth = 2.2
check.lineCapStyle = .round
check.lineJoinStyle = .round
check.stroke()
} else {
circle.lineWidth = 1.6
circle.stroke()
}
}.withRenderingMode(.alwaysOriginal)
}
}
/// 素材库的订单摘要,保留拍摄履约与素材处理相互独立的表达。
@MainActor
final class DroneMaterialOrderCell: UICollectionViewCell {
@@ -154,6 +182,15 @@ final class DroneMaterialSelectionCell: UICollectionViewCell {
config.imagePadding = 6
config.contentInsets = .zero
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 15)
let foreground = enabled ? DroneDockStyle.primary : UIColor(hex: 0xC2C9D4)
config.baseForegroundColor = foreground
config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var attributes = incoming
attributes.font = .systemFont(ofSize: 12)
attributes.foregroundColor = foreground
return attributes
}
config.imageColorTransformer = UIConfigurationColorTransformer { _ in foreground }
selectAllButton.configuration = config
selectAllButton.isEnabled = enabled
selectAllButton.accessibilityLabel = "全选可下载"
@@ -181,6 +218,13 @@ final class DroneMaterialRecordHeaderView: UICollectionReusableView {
config.imagePadding = 5
config.contentInsets = .zero
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13)
config.baseForegroundColor = DroneDockStyle.primary
config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var attributes = incoming
attributes.font = .systemFont(ofSize: 12)
attributes.foregroundColor = DroneDockStyle.primary
return attributes
}
deliveryButton.configuration = config
deliveryButton.tintColor = DroneDockStyle.primary
deliveryButton.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside)
@@ -193,7 +237,7 @@ final class DroneMaterialRecordHeaderView: UICollectionReusableView {
deliveryButton.snp.makeConstraints { make in
make.trailing.equalToSuperview()
make.centerY.equalTo(titleLabel)
make.height.equalTo(40)
make.height.equalTo(44)
}
detailLabel.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview()
@@ -229,8 +273,10 @@ final class DroneMaterialCell: UICollectionViewCell {
private let selectionButton = UIButton(type: .custom)
private let placeholderIcon = UIImageView()
private let videoBadge = UILabel()
private let nameLabel = DroneDockStyle.label(size: 12, weight: .medium)
private let statusLabel = DroneDockStyle.label(size: 11)
private let nameLabel = DroneDockStyle.label(size: 13, weight: .medium)
private let statusLabel = DroneDockStyle.label(size: 12)
private let retryUploadButton = UIButton(type: .system)
private let nameRow = UIStackView()
override init(frame: CGRect) {
super.init(frame: frame)
@@ -252,10 +298,23 @@ final class DroneMaterialCell: UICollectionViewCell {
selectionButton.imageView?.contentMode = .scaleAspectFit
selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
[thumbnail, placeholderIcon, previewButton, videoBadge, selectionButton, nameLabel, statusLabel].forEach(contentView.addSubview)
retryUploadButton.setTitle("重试上传", for: .normal)
retryUploadButton.titleLabel?.font = .systemFont(ofSize: 11)
retryUploadButton.isEnabled = false
retryUploadButton.setTitleColor(DroneDockStyle.primary.withAlphaComponent(0.55), for: .disabled)
retryUploadButton.accessibilityHint = "当前演示不执行上传重试"
nameRow.axis = .horizontal
nameRow.alignment = .center
nameRow.spacing = 6
nameRow.addArrangedSubview(nameLabel)
nameRow.addArrangedSubview(retryUploadButton)
retryUploadButton.setContentHuggingPriority(.required, for: .horizontal)
retryUploadButton.setContentCompressionResistancePriority(UILayoutPriority(999), for: .horizontal)
retryUploadButton.snp.makeConstraints { make in make.height.equalTo(16) }
[thumbnail, placeholderIcon, previewButton, videoBadge, selectionButton, nameRow, statusLabel].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in
make.leading.trailing.top.equalToSuperview()
make.height.equalTo(thumbnail.snp.width).multipliedBy(0.57)
make.height.equalTo(thumbnail.snp.width).multipliedBy(9.0 / 16.0)
}
previewButton.snp.makeConstraints { make in make.edges.equalTo(thumbnail) }
placeholderIcon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(29) }
@@ -269,13 +328,13 @@ final class DroneMaterialCell: UICollectionViewCell {
make.top.trailing.equalTo(thumbnail)
make.size.equalTo(44)
}
nameLabel.snp.makeConstraints { make in
nameRow.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview()
make.top.equalTo(thumbnail.snp.bottom).offset(7)
}
statusLabel.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview()
make.top.equalTo(nameLabel.snp.bottom).offset(4)
make.top.equalTo(nameRow.snp.bottom).offset(4)
make.bottom.lessThanOrEqualToSuperview().inset(5)
}
}
@@ -291,7 +350,10 @@ final class DroneMaterialCell: UICollectionViewCell {
thumbnail.image = material.canPreview ? UIImage(named: material.previewAssetName) : nil
thumbnail.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor
placeholderIcon.isHidden = material.canPreview
placeholderIcon.image = UIImage(systemName: material.uploadState == .failed ? "exclamationmark.icloud" : "play.fill")
placeholderIcon.image = UIImage(systemName: material.uploadState == .failed ? "xmark.circle" : "play.fill")
placeholderIcon.tintColor = material.uploadState == .failed ? DroneDockStyle.color(for: .red) : UIColor(hex: 0x9CA6B6)
retryUploadButton.isHidden = material.uploadState != .failed
retryUploadButton.accessibilityIdentifier = "drone.materials.retryUpload.\(material.id)"
videoBadge.isHidden = material.kind != .video || !material.canPreview
previewButton.isEnabled = material.canPreview
previewButton.accessibilityIdentifier = "drone.materials.preview.\(material.id)"
@@ -301,11 +363,9 @@ final class DroneMaterialCell: UICollectionViewCell {
selectionButton.accessibilityIdentifier = "drone.materials.select.\(material.id)"
selectionButton.accessibilityLabel = completed ? "\(material.title),演示完成,未写入相册" : "选择\(material.title)"
selectionButton.accessibilityTraits = selected || completed ? [.button, .selected] : .button
let symbol = UIImage(systemName: selected || completed ? "checkmark.circle.fill" : "circle",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22, weight: .regular))
let tint = completed ? DroneDockStyle.success : selected ? DroneDockStyle.primary : UIColor.white
selectionButton.setImage(symbol?.withTintColor(tint, renderingMode: .alwaysOriginal), for: .normal)
selectionButton.setImage(symbol?.withTintColor(tint.withAlphaComponent(0.6), renderingMode: .alwaysOriginal), for: .disabled)
selectionButton.setImage(DroneMaterialSelectionIcon.image(selected: selected || completed, tint: tint), for: .normal)
selectionButton.setImage(DroneMaterialSelectionIcon.image(selected: selected || completed, tint: tint, opacity: 0.6), for: .disabled)
selectionButton.imageView?.layer.shadowColor = UIColor.black.cgColor
selectionButton.imageView?.layer.shadowOpacity = 0.22
selectionButton.imageView?.layer.shadowRadius = 2
@@ -375,6 +435,9 @@ final class DroneMaterialsFooterView: UIView {
/// 返回选择状态或请求预留的交付入口。
var onSecondaryTap: (() -> Void)?
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
private let trailingLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let resultIcon = UIImageView()
private let titleRow = UIStackView()
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let progressView = UIProgressView(progressViewStyle: .default)
private let primaryButton = UIButton(type: .system)
@@ -389,7 +452,19 @@ final class DroneMaterialsFooterView: UIView {
stack.axis = .vertical
stack.spacing = 10
titleLabel.numberOfLines = 2
titleLabel.accessibilityIdentifier = "drone.materials.footer.title"
trailingLabel.accessibilityIdentifier = "drone.materials.footer.trailing"
trailingLabel.textAlignment = .right
trailingLabel.setContentHuggingPriority(.required, for: .horizontal)
trailingLabel.setContentCompressionResistancePriority(UILayoutPriority(999), for: .horizontal)
resultIcon.contentMode = .scaleAspectFit
resultIcon.accessibilityIdentifier = "drone.materials.footer.resultIcon"
titleRow.axis = .horizontal
titleRow.alignment = .center
titleRow.spacing = 8
[resultIcon, titleLabel, trailingLabel].forEach(titleRow.addArrangedSubview)
detailLabel.numberOfLines = 2
detailLabel.accessibilityIdentifier = "drone.materials.footer.detail"
progressView.progressTintColor = DroneDockStyle.primary
progressView.trackTintColor = UIColor(hex: 0xE8EDF7)
progressView.accessibilityLabel = "本次演示下载完成项数"
@@ -403,7 +478,7 @@ final class DroneMaterialsFooterView: UIView {
secondaryButton.tintColor = DroneDockStyle.secondary
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
[titleLabel, progressView, detailLabel, primaryButton, secondaryButton].forEach(stack.addArrangedSubview)
[titleRow, progressView, detailLabel, primaryButton, secondaryButton].forEach(stack.addArrangedSubview)
addSubview(divider)
addSubview(stack)
divider.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
@@ -413,8 +488,9 @@ final class DroneMaterialsFooterView: UIView {
make.bottom.equalTo(safeAreaLayoutGuide).inset(10)
}
primaryButton.snp.makeConstraints { make in make.height.equalTo(44) }
secondaryButton.snp.makeConstraints { make in make.height.equalTo(24) }
progressView.snp.makeConstraints { make in make.height.equalTo(3) }
secondaryButton.snp.makeConstraints { make in make.height.equalTo(44).priority(999) }
resultIcon.snp.makeConstraints { make in make.width.height.equalTo(21).priority(999) }
progressView.snp.makeConstraints { make in make.height.equalTo(3).priority(999) }
}
@available(*, unavailable)
@@ -423,9 +499,17 @@ final class DroneMaterialsFooterView: UIView {
/// 只接受显示值,按钮语义和下载状态由控制器及 ViewModel 决定。
func apply(title: String, detail: String, primaryTitle: String, primarySymbol: String,
enabled: Bool, identifier: String, progress: Double?, secondaryTitle: String? = nil,
tone: DroneDockStatusTone = .gray) {
tone: DroneDockStatusTone = .gray, trailingText: String? = nil,
resultSymbol: String? = nil, secondaryOutlined: Bool = false, secondaryEnabled: Bool = true) {
titleLabel.text = title
titleLabel.textColor = tone == .gray ? DroneDockStyle.text : DroneDockStyle.color(for: tone)
titleLabel.textColor = DroneDockStyle.text
titleLabel.font = .systemFont(ofSize: 13, weight: resultSymbol == nil ? .regular : .semibold)
trailingLabel.text = trailingText
trailingLabel.isHidden = trailingText == nil
trailingLabel.textColor = progress == nil ? DroneDockStyle.secondary : DroneDockStyle.primary
resultIcon.image = resultSymbol.flatMap(UIImage.init(systemName:))
resultIcon.isHidden = resultSymbol == nil
resultIcon.tintColor = DroneDockStyle.color(for: tone)
detailLabel.text = detail
detailLabel.isHidden = detail.isEmpty
progressView.isHidden = progress == nil
@@ -436,13 +520,47 @@ final class DroneMaterialsFooterView: UIView {
config.imagePadding = 7
config.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
let primaryForeground: UIColor = enabled || progress == nil ? .white : DroneDockStyle.primary
let primaryBackground = enabled ? DroneDockStyle.primary : UIColor(hex: 0xCEDBFC)
config.cornerStyle = .fixed
config.background.cornerRadius = 7
config.background.backgroundColor = primaryBackground
config.background.backgroundColorTransformer = UIConfigurationColorTransformer { _ in primaryBackground }
config.baseForegroundColor = primaryForeground
config.imageColorTransformer = UIConfigurationColorTransformer { _ in primaryForeground }
config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var attributes = incoming
attributes.font = .systemFont(ofSize: 15, weight: .medium)
attributes.foregroundColor = primaryForeground
return attributes
}
primaryButton.configuration = config
primaryButton.isEnabled = enabled
primaryButton.backgroundColor = enabled ? DroneDockStyle.primary : UIColor(hex: 0xCEDBFC)
primaryButton.backgroundColor = .clear
primaryButton.accessibilityIdentifier = identifier
secondaryButton.setTitle(secondaryTitle, for: .normal)
var secondary = UIButton.Configuration.plain()
secondary.title = secondaryTitle
secondary.image = secondaryOutlined ? UIImage(systemName: "play.rectangle") : nil
secondary.imagePadding = 6
secondary.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 14)
let secondaryForeground = secondaryOutlined ? DroneDockStyle.primary : DroneDockStyle.secondary
secondary.cornerStyle = .fixed
secondary.background.cornerRadius = 7
secondary.baseForegroundColor = secondaryForeground
secondary.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var attributes = incoming
attributes.font = .systemFont(ofSize: 12)
attributes.foregroundColor = secondaryForeground
return attributes
}
secondaryButton.configuration = secondary
secondaryButton.tintColor = secondaryOutlined ? DroneDockStyle.primary : DroneDockStyle.secondary
secondaryButton.layer.cornerRadius = 7
secondaryButton.layer.borderWidth = secondaryOutlined ? 1 : 0
secondaryButton.layer.borderColor = DroneDockStyle.primary.cgColor
secondaryButton.isHidden = secondaryTitle == nil
secondaryButton.accessibilityIdentifier = "drone.materials.continueSelecting"
secondaryButton.isEnabled = secondaryEnabled
secondaryButton.accessibilityIdentifier = secondaryOutlined ? "drone.materials.completedDelivery" : "drone.materials.continueSelecting"
}
@objc private func primaryTapped() { onPrimaryTap?() }
@@ -83,7 +83,7 @@ final class DroneMaterialsViewController: BaseViewController {
}
override func setupNavigationBar() {
title = "订单素材库"
title = "订单素材库 · 演示"
navigationItem.backButtonDisplayMode = .minimal
let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain,
target: self, action: #selector(backTapped))
@@ -170,6 +170,10 @@ final class DroneMaterialsViewController: BaseViewController {
footerView.onPrimaryTap = { [weak self] in self?.performFooterAction() }
footerView.onSecondaryTap = { [weak self] in
guard let self else { return }
if self.viewModel.downloadPhase == .completed {
self.chooseCompletedDelivery()
return
}
self.viewModel.clearBatch()
self.applySnapshot(animated: true)
}
@@ -373,37 +377,41 @@ final class DroneMaterialsViewController: BaseViewController {
footerAction = .permission
footerView.apply(title: "无法保存到手机相册", detail: "演示相册权限未开启,恢复后请手动继续。",
primaryTitle: "检查相册权限", primarySymbol: "lock", enabled: true,
identifier: "drone.materials.permission", progress: nil, tone: .orange)
identifier: "drone.materials.permission", progress: nil, tone: .blue, resultSymbol: "lock")
return
}
switch viewModel.downloadPhase {
case .idle:
footerAction = .download
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "仅可选择已上传素材 · 本次为本地演示",
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "",
primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line", enabled: viewModel.canStartDownload,
identifier: "drone.materials.download", progress: nil)
identifier: "drone.materials.download", progress: nil, trailingText: "仅可选择已上传素材")
case .downloading, .awaitingSave, .saving:
footerAction = .none
footerView.apply(title: "本次下载\(viewModel.batchTotalCount)项 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
footerView.apply(title: "本次下载\(viewModel.batchTotalCount)项",
detail: "请保持本页开启,下载期间不可更改选择",
primaryTitle: viewModel.downloadButtonTitle, primarySymbol: "arrow.triangle.2.circlepath", enabled: false,
identifier: "drone.materials.download", progress: viewModel.batchProgress, tone: .blue)
identifier: "drone.materials.download", progress: viewModel.batchProgress, tone: .blue,
trailingText: "已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项")
case .paused:
footerAction = .resume
footerView.apply(title: "下载已暂停 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
footerView.apply(title: "下载已暂停",
detail: "已完成项会保留;继续时仅处理未完成文件。",
primaryTitle: "继续下载", primarySymbol: "play.fill", enabled: true,
identifier: "drone.materials.continue", progress: viewModel.batchProgress, tone: .orange)
identifier: "drone.materials.continue", progress: viewModel.batchProgress, tone: .orange,
trailingText: "已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项", resultSymbol: "pause.circle")
case .partialFailure:
footerAction = .retry
footerView.apply(title: "部分素材下载失败", detail: "演示完成\(viewModel.completedCount)项 · 失败\(viewModel.failedCount)项,重试仅处理失败项",
footerView.apply(title: "部分素材下载失败", detail: "演示成功\(viewModel.completedCount)项 · 失败\(viewModel.failedCount)项,已完成的无需重复下载",
primaryTitle: "重试失败素材(\(viewModel.failedCount))", primarySymbol: "arrow.clockwise", enabled: viewModel.failedCount > 0,
identifier: "drone.materials.retry", progress: nil, secondaryTitle: "选择其他素材", tone: .orange)
identifier: "drone.materials.retry", progress: nil, secondaryTitle: "选择其他素材", tone: .orange,
resultSymbol: "exclamationmark.triangle")
case .completed:
footerAction = .selectMore
footerView.apply(title: "本次素材演示完成", detail: "\(viewModel.completedCount)项演示完成,未写入系统相册",
primaryTitle: "继续选择素材", primarySymbol: "checkmark.circle", enabled: true,
identifier: "drone.materials.continueSelecting", progress: nil, tone: .green)
footerView.apply(title: "本次素材下载完成(演示)", detail: "\(viewModel.completedCount)项演示完成,未写入系统相册",
primaryTitle: "继续选择素材", primarySymbol: "", enabled: true,
identifier: "drone.materials.continueSelecting", progress: nil, secondaryTitle: "交付成片", tone: .green,
resultSymbol: "checkmark.circle", secondaryOutlined: true, secondaryEnabled: delegate != nil)
}
}
@@ -419,7 +427,7 @@ final class DroneMaterialsViewController: BaseViewController {
case .selectMore:
viewModel.clearBatch()
case .permission:
showAlert(title: "相册权限演示", message: "当前为本地演示,不读取或修改系统相册权限。可在右上角演示状态中选择“模拟相册权限恢复”,再手动继续下载。")
showPermissionSimulation()
case .none:
return
}
@@ -432,6 +440,37 @@ final class DroneMaterialsViewController: BaseViewController {
transferDriver.start(viewModel: viewModel) { [weak self] in self?.applySnapshot(animated: true) }
}
/// 权限说明与恢复只作用于演示状态,不打开系统设置或请求真实 Photos 授权。
private func showPermissionSimulation() {
let alert = UIAlertController(title: "无法保存到手机相册",
message: "相册权限未开启。当前为本地演示,不读取或修改系统相册权限;模拟恢复后请手动继续下载。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "暂不下载", style: .cancel))
alert.addAction(UIAlertAction(title: "模拟恢复权限", style: .default) { [weak self] _ in
guard let self else { return }
self.viewModel.setPhotoPermission(.allowed)
self.applySnapshot(animated: true)
})
present(alert, animated: true)
}
/// 完成底栏的交付入口先明确拍摄记录,不根据下载批次猜测目标点位。
private func chooseCompletedDelivery() {
guard delegate != nil, !viewModel.sections.isEmpty else { return }
if viewModel.sections.count == 1, let record = viewModel.sections.first {
delegate?.materialsViewController(self, didRequestDelivery: record)
return
}
let sheet = UIAlertController(title: "选择拍摄记录", message: "选择需要交付成片的拍摄记录", preferredStyle: .actionSheet)
for record in viewModel.sections {
sheet.addAction(UIAlertAction(title: "\(record.pointName) · 记录\(record.sequenceNumber)", style: .default) { [weak self] _ in
guard let self else { return }
self.delegate?.materialsViewController(self, didRequestDelivery: record)
})
}
sheet.addAction(UIAlertAction(title: "取消", style: .cancel))
present(sheet, animated: true)
}
private func updateInteractivePopGesture() {
guard let gesture = navigationController?.interactivePopGestureRecognizer else { return }
if hasRunningDownload {
@@ -500,13 +500,15 @@ final class DronePreparationFooterView: UIView {
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
}
/// 按购买权限启用待飞任务创建;本阶段不提供无人机召唤或起飞入口。
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false) {
/// 绑定准备页提交许可;模拟来源仅影响文案,不改变业务权限或真实传输保护。
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false,
isLocalSimulation: Bool = false) {
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
selectionLabel.text = viewModel.selectionSummary
selectionLabel.numberOfLines = 2
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceTone)
primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal)
let title = isLocalSimulation && viewModel.canCreateTask ? "确认并召唤(模拟)" : viewModel.primaryButtonTitle
primaryButton.setTitle(title, for: .normal)
primaryButton.isEnabled = (viewModel.isPrimaryActionEnabled || viewModel.canOpenShootingTask) && !isRefreshing
primaryButton.backgroundColor = primaryButton.isEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE1E7F0)
primaryButton.setTitleColor(.white, for: .normal)
@@ -516,6 +518,9 @@ final class DronePreparationFooterView: UIView {
} else {
messageLabel.text = viewModel.planeStatusErrorMessage.map { "无人机状态获取失败:\($0)" } ?? viewModel.admissionMessage
}
if isLocalSimulation {
messageLabel.text = "本地模拟,不会向无人机发送指令\n" + (messageLabel.text ?? "")
}
messageLabel.textColor = DroneDockStyle.secondary
refreshButton.isHidden = false
refreshButton.isEnabled = !viewModel.isLoading && !viewModel.isCreatingTask && !viewModel.isSummoning && !isRefreshing
@@ -1,14 +1,15 @@
import Kingfisher
import SnapKit
import UIKit
/// 景区素材模块的局部样式,可独立于机巢业务使用。
@MainActor
enum ScenicMaterialsStyle {
static let primary = UIColor(hex: 0x3164FF)
static let primary = UIColor(hex: 0x066BFF)
static let background = UIColor.white
static let text = UIColor(hex: 0x20242C)
static let secondary = UIColor(hex: 0x9297A1)
static let border = UIColor(hex: 0xECEEF2)
static let text = UIColor(hex: 0x151515)
static let secondary = UIColor(hex: 0x8490A5)
static let border = UIColor(hex: 0xE7E9EF)
static let success = UIColor(hex: 0x17986A)
static let warning = UIColor(hex: 0xD98926)
@@ -79,8 +80,11 @@ final class ScenicMaterialClipCell: UICollectionViewCell {
/// 显示片段及本机演示传输状态;首段大图额外显示分辨率和体积。
func configure(clip: ScenicMaterialClip, selected: Bool, isSelectionEnabled: Bool,
statusText: String? = nil, progress: Double? = nil, isHero: Bool = false) {
cover.image = UIImage(named: clip.coverAssetName)
ordinalLabel.text = String(format: "片段 %02d", clip.ordinal)
cover.kf.cancelDownloadTask()
if clip.isRemote {
cover.kf.setImage(with: clip.coverURL, placeholder: UIImage(systemName: "photo"))
} else { cover.image = UIImage(named: clip.coverAssetName) }
ordinalLabel.text = clip.fileLabel ?? String(format: "片段 %02d", clip.ordinal)
metadataLabel.text = isHero ? "\(clip.durationText) · \(clip.resolution) · \(clip.sizeText)" : clip.durationText
metadataLabel.font = .monospacedDigitSystemFont(ofSize: isHero ? 11 : 10, weight: .regular)
selectionButton.setImage(UIImage(systemName: selected ? "checkmark.circle.fill" : "circle",
@@ -269,27 +273,46 @@ final class ScenicMaterialExpandCell: UICollectionViewCell {
@objc private func tapped() { onToggleExpanded?() }
}
/// 固定底部的选择/下载摘要,不直接持有 ViewModel 或执行文件操作。
/// 固定底部的选择/下载摘要,由页面显式传入布局和状态,不执行文件操作。
@MainActor
final class ScenicMaterialsFooterView: UIView {
/// 选择态左右排列;传输态显示摘要、进度和通栏按钮;结果态显示摘要和操作行。
enum Layout { case selection, progress, result }
/// 当前阶段的主要操作,例如下载、继续或重试。
var onPrimaryTap: (() -> Void)?
/// 当前阶段的次要操作,例如取消或继续选择。
var onSecondaryTap: (() -> Void)?
private let titleLabel = ScenicMaterialsStyle.label(size: 14, weight: .medium)
private let detailLabel = ScenicMaterialsStyle.label(size: 10, color: ScenicMaterialsStyle.secondary)
private let titleLabel = ScenicMaterialsStyle.label(size: 14)
private let detailLabel = ScenicMaterialsStyle.label(size: 11, color: ScenicMaterialsStyle.secondary)
private let primaryButton = UIButton(type: .custom)
private let secondaryButton = UIButton(type: .custom)
private let progressView = UIProgressView(progressViewStyle: .bar)
private let activity = UIActivityIndicatorView(style: .medium)
private let summaryRow = UIStackView()
private let actionRow = UIStackView()
private let stack = UIStackView()
private var currentLayout: Layout?
private var hasSecondaryAction = false
/// 创建随安全区延伸的白色底栏。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
setupConstraints()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
private func setupUI() {
backgroundColor = .white
titleLabel.numberOfLines = 2
titleLabel.accessibilityIdentifier = "scenic.materials.footer.title"
detailLabel.numberOfLines = 2
primaryButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .semibold)
primaryButton.titleLabel?.numberOfLines = 2
detailLabel.accessibilityIdentifier = "scenic.materials.footer.detail"
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.numberOfLines = 1
primaryButton.titleLabel?.textAlignment = .center
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(.white, for: .disabled)
@@ -297,64 +320,137 @@ final class ScenicMaterialsFooterView: UIView {
primaryButton.clipsToBounds = true
primaryButton.accessibilityIdentifier = "scenic.materials.primary"
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
secondaryButton.tintColor = ScenicMaterialsStyle.primary
secondaryButton.setTitleColor(ScenicMaterialsStyle.primary, for: .normal)
secondaryButton.titleLabel?.font = .systemFont(ofSize: 13)
secondaryButton.setTitleColor(ScenicMaterialsStyle.secondary, for: .normal)
secondaryButton.titleLabel?.font = .systemFont(ofSize: 15)
secondaryButton.titleLabel?.numberOfLines = 1
secondaryButton.titleLabel?.textAlignment = .center
secondaryButton.layer.cornerRadius = 10
secondaryButton.accessibilityIdentifier = "scenic.materials.secondary"
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
progressView.progressTintColor = ScenicMaterialsStyle.primary
progressView.trackTintColor = ScenicMaterialsStyle.border
let labels = UIStackView(arrangedSubviews: [titleLabel, detailLabel])
labels.axis = .vertical
labels.spacing = 5
let row = UIStackView(arrangedSubviews: [labels, primaryButton])
row.axis = .horizontal
row.spacing = 12
row.alignment = .center
let stack = UIStackView(arrangedSubviews: [row, progressView, secondaryButton])
progressView.trackTintColor = UIColor(hex: 0xE7EDF7)
progressView.accessibilityIdentifier = "scenic.materials.footer.progress"
activity.color = .white
activity.hidesWhenStopped = true
activity.isUserInteractionEnabled = false
activity.accessibilityIdentifier = "scenic.materials.footer.activity"
primaryButton.addSubview(activity)
summaryRow.axis = .horizontal
summaryRow.alignment = .center
summaryRow.spacing = 8
actionRow.axis = .horizontal
actionRow.alignment = .center
actionRow.spacing = 16
stack.axis = .vertical
stack.spacing = 10
let separator = UIView()
separator.backgroundColor = ScenicMaterialsStyle.border
addSubview(separator)
stack.spacing = 8
addSubview(stack)
separator.snp.makeConstraints { $0.top.leading.trailing.equalToSuperview(); $0.height.equalTo(0.5) }
stack.snp.makeConstraints {
$0.top.equalToSuperview().offset(14)
$0.leading.trailing.equalToSuperview().inset(20)
$0.bottom.equalTo(safeAreaLayoutGuide).inset(12)
}
primaryButton.snp.makeConstraints { $0.width.equalTo(158); $0.height.equalTo(46) }
progressView.snp.makeConstraints { $0.height.equalTo(3).priority(999) }
secondaryButton.snp.makeConstraints { $0.height.equalTo(32).priority(999) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
private func setupConstraints() {
stack.snp.makeConstraints {
$0.top.equalToSuperview().offset(14)
$0.leading.trailing.equalToSuperview().inset(18)
$0.bottom.equalTo(safeAreaLayoutGuide).inset(14)
}
primaryButton.snp.makeConstraints { $0.height.equalTo(46) }
progressView.snp.makeConstraints { $0.height.equalTo(3).priority(999) }
activity.snp.makeConstraints {
$0.centerY.equalToSuperview()
$0.centerX.equalToSuperview()
$0.size.equalTo(18)
}
}
/// 由当前页面状态显式刷新底栏,始终保留禁用按钮的可读标题。
/// 按产品页面的状态布局刷新底栏,忙碌按钮保持蓝色但不可重复触发。
func configure(title: String, detail: String?, primaryTitle: String, primaryEnabled: Bool,
secondaryTitle: String? = nil, progress: Float? = nil) {
secondaryTitle: String? = nil, progress: Float? = nil,
layout: Layout = .selection, isBusy: Bool = false) {
UIView.performWithoutAnimation {
if currentLayout != layout || hasSecondaryAction != (secondaryTitle != nil) {
arrange(layout, hasSecondary: secondaryTitle != nil)
}
titleLabel.attributedText = nil
titleLabel.text = title
if layout == .selection, let range = title.range(of: #"\d+"#, options: .regularExpression) {
let attributed = NSMutableAttributedString(string: title)
attributed.addAttributes([.foregroundColor: ScenicMaterialsStyle.primary,
.font: UIFont.systemFont(ofSize: 20, weight: .bold)],
range: NSRange(range, in: title))
titleLabel.attributedText = attributed
}
detailLabel.text = detail
detailLabel.isHidden = detail == nil
if primaryButton.title(for: .normal) != primaryTitle {
primaryButton.setTitle(primaryTitle, for: .normal)
primaryButton.setTitle(primaryTitle, for: .disabled)
}
primaryButton.backgroundColor = primaryEnabled ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.primary.withAlphaComponent(0.25)
detailLabel.isHidden = detail == nil || layout == .progress
primaryButton.accessibilityHint = detail
primaryButton.setTitle(primaryTitle, for: .normal)
primaryButton.setTitle(primaryTitle, for: .disabled)
let titleFont = primaryButton.titleLabel?.font ?? .systemFont(ofSize: 15, weight: .semibold)
let titleWidth = ceil(primaryTitle.size(withAttributes: [.font: titleFont]).width) + 2
activity.snp.updateConstraints { $0.centerX.equalToSuperview().offset(-titleWidth / 2 - 4) }
primaryButton.backgroundColor = primaryEnabled || isBusy ? ScenicMaterialsStyle.primary : UIColor(hex: 0xCDDFFF)
primaryButton.isEnabled = primaryEnabled
if secondaryButton.title(for: .normal) != secondaryTitle {
secondaryButton.setTitle(secondaryTitle, for: .normal)
}
secondaryButton.setTitle(secondaryTitle, for: .normal)
secondaryButton.isHidden = secondaryTitle == nil
secondaryButton.isEnabled = secondaryTitle != nil
progressView.isHidden = progress == nil
progressView.progress = min(max(progress ?? 0, 0), 1)
if isBusy { activity.startAnimating() } else { activity.stopAnimating() }
layoutIfNeeded()
}
}
@objc private func primaryTapped() { onPrimaryTap?() }
@objc private func secondaryTapped() { onSecondaryTap?() }
private func arrange(_ layout: Layout, hasSecondary: Bool) {
for container in [stack, summaryRow, actionRow] {
container.arrangedSubviews.forEach { container.removeArrangedSubview($0); $0.removeFromSuperview() }
}
titleLabel.snp.removeConstraints()
detailLabel.snp.removeConstraints()
secondaryButton.snp.removeConstraints()
actionRow.distribution = .fill
titleLabel.font = .systemFont(ofSize: layout == .selection ? 17 : 12)
detailLabel.textAlignment = layout == .selection ? .left : .right
secondaryButton.backgroundColor = layout == .result ? UIColor(hex: 0xF2F4F7) : .clear
secondaryButton.titleLabel?.font = .systemFont(ofSize: layout == .progress ? 12 : 15)
switch layout {
case .selection:
actionRow.addArrangedSubview(titleLabel)
actionRow.addArrangedSubview(primaryButton)
titleLabel.snp.makeConstraints { $0.width.equalTo(126).priority(999) }
stack.addArrangedSubview(actionRow)
stack.addArrangedSubview(detailLabel)
case .progress:
summaryRow.addArrangedSubview(titleLabel)
if hasSecondary {
summaryRow.addArrangedSubview(secondaryButton)
secondaryButton.snp.makeConstraints { $0.width.equalTo(44); $0.height.equalTo(28) }
}
actionRow.addArrangedSubview(primaryButton)
stack.addArrangedSubview(summaryRow)
stack.addArrangedSubview(progressView)
stack.addArrangedSubview(actionRow)
case .result:
summaryRow.addArrangedSubview(titleLabel)
summaryRow.addArrangedSubview(detailLabel)
titleLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
detailLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
if hasSecondary {
actionRow.addArrangedSubview(secondaryButton)
secondaryButton.snp.makeConstraints { $0.height.equalTo(46) }
actionRow.distribution = .fillEqually
}
actionRow.addArrangedSubview(primaryButton)
stack.addArrangedSubview(summaryRow)
stack.addArrangedSubview(actionRow)
}
currentLayout = layout
hasSecondaryAction = hasSecondary
}
@objc private func primaryTapped() {
guard primaryButton.isEnabled else { return }
onPrimaryTap?()
}
@objc private func secondaryTapped() {
guard secondaryButton.isEnabled, !secondaryButton.isHidden else { return }
onSecondaryTap?()
}
}
@@ -29,35 +29,31 @@ final class ScenicMaterialRouteFilterViewController: UIViewController, UITableVi
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
let desiredHeight = min(CGFloat(routes.count + 1) * 58 + 90, 460)
let desiredHeight = min(CGFloat(routes.count + 1) * 50 + 100, 460)
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, desiredHeight) }]
sheetPresentationController?.prefersGrabberVisible = true
sheetPresentationController?.preferredCornerRadius = 24
sheetPresentationController?.preferredCornerRadius = 22
}
private func setupUI() {
view.backgroundColor = .white
view.accessibilityIdentifier = "scenic.materials.route.sheet"
let title = ScenicMaterialsStyle.label("选择航线", size: 19, weight: .semibold)
let close = UIButton(type: .system)
close.setImage(UIImage(systemName: "xmark"), for: .normal)
close.tintColor = ScenicMaterialsStyle.secondary
close.accessibilityLabel = "关闭航线筛选"
close.accessibilityIdentifier = "scenic.materials.route.close"
close.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
let title = ScenicMaterialsStyle.label("选择航线", size: 18, weight: .semibold)
tableView.backgroundColor = .white
tableView.separatorStyle = .none
tableView.rowHeight = 58
tableView.separatorStyle = .singleLine
tableView.separatorColor = ScenicMaterialsStyle.border
tableView.separatorInset = .zero
tableView.tableFooterView = UIView()
tableView.rowHeight = 50
tableView.delegate = self
tableView.accessibilityIdentifier = "scenic.materials.route.list"
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "route")
[title, close, tableView].forEach(view.addSubview)
title.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(20); $0.leading.equalToSuperview().offset(22) }
close.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) }
[title, tableView].forEach(view.addSubview)
title.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(22); $0.leading.equalToSuperview().offset(18) }
tableView.snp.makeConstraints {
$0.top.equalTo(title.snp.bottom).offset(14)
$0.leading.trailing.equalToSuperview().inset(8)
$0.bottom.equalTo(view.safeAreaLayoutGuide)
$0.top.equalTo(title.snp.bottom).offset(12)
$0.leading.trailing.equalToSuperview().inset(22)
$0.bottom.equalTo(view.safeAreaLayoutGuide).inset(10)
}
dataSource = UITableViewDiffableDataSource<Int, Row>(tableView: tableView) { [weak self] table, indexPath, row in
guard let self else { return nil }
@@ -71,15 +67,27 @@ final class ScenicMaterialRouteFilterViewController: UIViewController, UITableVi
name = self.routes.first { $0.id == routeID }?.name ?? "航线暂不可用"
}
let selected = id == self.selectedRouteID
cell.textLabel?.text = name
cell.textLabel?.font = .systemFont(ofSize: 15, weight: selected ? .medium : .regular)
cell.textLabel?.textColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
var configuration = cell.defaultContentConfiguration()
configuration.text = name
configuration.textProperties.font = .systemFont(ofSize: 14, weight: selected ? .medium : .regular)
configuration.textProperties.color = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
configuration.directionalLayoutMargins = .zero
cell.contentConfiguration = configuration
cell.backgroundColor = .white
let image = UIImageView(image: UIImage(systemName: selected ? "checkmark.circle.fill" : "circle",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22)))
image.tintColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border
image.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
cell.accessoryView = image
cell.selectionStyle = .none
cell.layoutMargins = .zero
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = .zero
if selected {
let image = UIImageView(image: UIImage(systemName: "checkmark",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 16, weight: .medium)))
image.tintColor = ScenicMaterialsStyle.primary
image.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
cell.accessoryView = image
} else {
cell.accessoryView = nil
}
cell.accessibilityLabel = name
cell.accessibilityIdentifier = "scenic.materials.route.\(id ?? "all")"
cell.accessibilityTraits = selected ? [.button, .selected] : .button
return cell
@@ -99,19 +107,17 @@ final class ScenicMaterialRouteFilterViewController: UIViewController, UITableVi
dismiss(animated: true) { completion?(id) }
}
@objc private func closeTapped() { dismiss(animated: true) }
}
/// 景区素材起止日期筛选 Sheet,临时选择只在点击确定后应用。
@MainActor
final class ScenicMaterialDateFilterViewController: UIViewController {
final class ScenicMaterialDateFilterViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
/// nil/nil 表示保留期内的全部时间,其他值为按日包含端点的区间。
var onSelectRange: ((Date?, Date?) -> Void)?
/// 当前正在编辑的日期端点。
private enum Endpoint: Equatable { case start, end }
private let minimumDate: Date
private let maximumDate: Date
private let dateOptions: ScenicMaterialDatePickerOptions
private let calendar: Calendar
private var startDate: Date
private var endDate: Date
@@ -120,18 +126,19 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
private let allButton = UIButton(type: .system)
private let startButton = UIButton(type: .custom)
private let endButton = UIButton(type: .custom)
private let picker = UIDatePicker()
private let picker = UIPickerView()
/// 约束到服务端约定或演示给定的保留区间,不提供未来日期。
init(start: Date?, end: Date?, minimumDate: Date, maximumDate: Date, calendar: Calendar = .current) {
self.calendar = calendar
self.minimumDate = calendar.startOfDay(for: minimumDate)
self.maximumDate = max(calendar.startOfDay(for: minimumDate), calendar.startOfDay(for: maximumDate))
let clampedStart = min(max(calendar.startOfDay(for: start ?? maximumDate), self.minimumDate), self.maximumDate)
let clampedEnd = min(max(calendar.startOfDay(for: end ?? maximumDate), self.minimumDate), self.maximumDate)
let options = ScenicMaterialDatePickerOptions(minimumDate: minimumDate, maximumDate: maximumDate, calendar: calendar)
dateOptions = options
let clampedStart = options.clamped(start ?? maximumDate)
let clampedEnd = options.clamped(end ?? maximumDate)
self.startDate = min(clampedStart, clampedEnd)
self.endDate = max(clampedStart, clampedEnd)
usesAllDates = start == nil && end == nil
// 打开面板先编辑日期草稿;取消不会改变列表当前的“全部时间”。
usesAllDates = false
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .pageSheet
}
@@ -143,15 +150,15 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
super.viewDidLoad()
setupUI()
updateUI()
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 530) }]
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 531) }]
sheetPresentationController?.prefersGrabberVisible = true
sheetPresentationController?.preferredCornerRadius = 24
sheetPresentationController?.preferredCornerRadius = 22
}
private func setupUI() {
view.backgroundColor = .white
view.accessibilityIdentifier = "scenic.materials.date.sheet"
let title = ScenicMaterialsStyle.label("选择时间", size: 19, weight: .semibold)
let title = ScenicMaterialsStyle.label("选择时间", size: 18, weight: .semibold)
let hint = ScenicMaterialsStyle.label("选择起止日期", size: 13, color: ScenicMaterialsStyle.secondary)
allButton.addTarget(self, action: #selector(allTapped), for: .touchUpInside)
allButton.accessibilityIdentifier = "scenic.materials.date.all"
@@ -166,19 +173,14 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
let dateRow = UIStackView(arrangedSubviews: [startButton, endButton])
dateRow.distribution = .fillEqually
dateRow.spacing = 12
picker.datePickerMode = .date
picker.preferredDatePickerStyle = .wheels
picker.locale = Locale(identifier: "zh_CN")
picker.calendar = calendar
picker.timeZone = calendar.timeZone
picker.minimumDate = minimumDate
picker.maximumDate = maximumDate
picker.dataSource = self
picker.delegate = self
picker.accessibilityIdentifier = "scenic.materials.date.picker"
picker.addTarget(self, action: #selector(dateChanged), for: .valueChanged)
let retention = ScenicMaterialsStyle.label("仅显示保留期内已到来的日期", size: 11, color: ScenicMaterialsStyle.secondary)
retention.textAlignment = .center
let cancel = UIButton(type: .system)
cancel.setTitle("取消", for: .normal)
cancel.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
cancel.tintColor = ScenicMaterialsStyle.secondary
cancel.backgroundColor = UIColor(hex: 0xF5F6F8)
cancel.layer.cornerRadius = 10
@@ -186,6 +188,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
cancel.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
let confirm = UIButton(type: .system)
confirm.setTitle("确定", for: .normal)
confirm.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
confirm.setTitleColor(.white, for: .normal)
confirm.backgroundColor = ScenicMaterialsStyle.primary
confirm.layer.cornerRadius = 10
@@ -201,7 +204,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
scrollView.addSubview(content)
[title, hint, allButton, dateRow, picker, retention].forEach(content.addSubview)
actions.snp.makeConstraints {
$0.leading.trailing.equalToSuperview().inset(22)
$0.leading.trailing.equalToSuperview().inset(18)
$0.bottom.equalTo(view.safeAreaLayoutGuide).inset(12)
$0.height.equalTo(46)
}
@@ -210,21 +213,19 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
$0.bottom.equalTo(actions.snp.top).offset(-12)
}
content.snp.makeConstraints { $0.edges.equalTo(scrollView.contentLayoutGuide); $0.width.equalTo(scrollView.frameLayoutGuide) }
title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) }
hint.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(12); $0.leading.equalTo(title) }
allButton.snp.makeConstraints { $0.centerY.equalTo(hint); $0.trailing.equalToSuperview().inset(22); $0.height.equalTo(44) }
dateRow.snp.makeConstraints { $0.top.equalTo(hint.snp.bottom).offset(16); $0.leading.trailing.equalToSuperview().inset(22); $0.height.equalTo(65) }
picker.snp.makeConstraints { $0.top.equalTo(dateRow.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(12); $0.height.equalTo(210) }
retention.snp.makeConstraints { $0.top.equalTo(picker.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(20); $0.bottom.equalToSuperview().inset(4) }
title.snp.makeConstraints { $0.top.equalToSuperview().offset(24); $0.leading.equalToSuperview().offset(18) }
hint.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(22); $0.leading.equalTo(title) }
allButton.snp.makeConstraints { $0.centerY.equalTo(hint); $0.trailing.equalToSuperview().inset(18); $0.height.equalTo(36) }
dateRow.snp.makeConstraints { $0.top.equalTo(hint.snp.bottom).offset(20); $0.leading.trailing.equalToSuperview().inset(18); $0.height.equalTo(72) }
picker.snp.makeConstraints { $0.top.equalTo(dateRow.snp.bottom).offset(10); $0.leading.trailing.equalToSuperview().inset(18); $0.height.equalTo(200) }
retention.snp.makeConstraints { $0.top.equalTo(picker.snp.bottom).offset(12); $0.leading.trailing.equalToSuperview().inset(18); $0.bottom.equalToSuperview().inset(4) }
}
private func updateUI() {
var allConfiguration = UIButton.Configuration.plain()
allConfiguration.title = "全部时间"
allConfiguration.image = UIImage(systemName: usesAllDates ? "checkmark.circle.fill" : "circle")
allConfiguration.imagePadding = 5
allConfiguration.baseForegroundColor = usesAllDates ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
allConfiguration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
allConfiguration.baseForegroundColor = ScenicMaterialsStyle.primary
allConfiguration.contentInsets = .zero
allConfiguration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { input in
var output = input; output.font = .systemFont(ofSize: 12); return output
}
@@ -234,11 +235,11 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
formatter.calendar = calendar
formatter.timeZone = calendar.timeZone
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "M 月 d 日"
formatter.dateFormat = "M月d日"
for (button, value, name, candidate) in [(startButton, startDate, "开始日期", Endpoint.start), (endButton, endDate, "结束日期", Endpoint.end)] {
let active = endpoint == candidate && !usesAllDates
let foreground = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
let titleColor = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
let titleColor = ScenicMaterialsStyle.secondary
var configuration = UIButton.Configuration.plain()
configuration.title = name
configuration.subtitle = formatter.string(from: value)
@@ -254,7 +255,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
}
configuration.subtitleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var result = attributes
result.font = .systemFont(ofSize: 14, weight: active ? .medium : .regular)
result.font = .systemFont(ofSize: 18, weight: .semibold)
result.foregroundColor = foreground
return result
}
@@ -263,11 +264,17 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
button.layoutIfNeeded()
}
button.backgroundColor = active ? ScenicMaterialsStyle.primary.withAlphaComponent(0.06) : UIColor(hex: 0xF7F8FA)
button.layer.borderColor = (active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border).cgColor
button.layer.borderColor = (active ? ScenicMaterialsStyle.primary.withAlphaComponent(0.35) : ScenicMaterialsStyle.border).cgColor
button.accessibilityTraits = active ? [.button, .selected] : .button
button.accessibilityLabel = "\(name),\(formatter.string(from: value))"
}
picker.setDate(endpoint == .start ? startDate : endDate, animated: false)
let value = endpoint == .start ? startDate : endDate
let monthIndex = dateOptions.monthIndex(for: value)
picker.selectRow(monthIndex, inComponent: 0, animated: false)
picker.reloadComponent(1)
let dayIndex = dateOptions.months[monthIndex].dates.firstIndex(of: value) ?? 0
picker.selectRow(dayIndex, inComponent: 1, animated: false)
picker.accessibilityLabel = endpoint == .start ? "开始日期,月份和日期" : "结束日期,月份和日期"
picker.alpha = usesAllDates ? 0.4 : 1
picker.isUserInteractionEnabled = !usesAllDates
}
@@ -276,8 +283,50 @@ final class ScenicMaterialDateFilterViewController: UIViewController {
@objc private func startTapped() { endpoint = .start; usesAllDates = false; updateUI() }
@objc private func endTapped() { endpoint = .end; usesAllDates = false; updateUI() }
@objc private func dateChanged() {
let value = min(max(calendar.startOfDay(for: picker.date), minimumDate), maximumDate)
/// 两列分别表示保留期内的月份与所选月份内的日号。
func numberOfComponents(in pickerView: UIPickerView) -> Int { 2 }
/// 首尾月份按保留期裁剪,滚轮中不会出现不可提交的日期。
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 { return dateOptions.months.count }
return dateOptions.months[max(pickerView.selectedRow(inComponent: 0), 0)].dates.count
}
/// 使用与网页一致的 40 点行高。
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { 40 }
/// 月份和日期占据等宽两列。
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { pickerView.bounds.width / 2 }
/// 日期文案不显示年份列,辅助功能仍包含月份的年份。
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label = (view as? UILabel) ?? UILabel()
label.font = .systemFont(ofSize: 20, weight: .medium)
label.textColor = ScenicMaterialsStyle.text
label.textAlignment = .center
if component == 0 {
let month = dateOptions.months[row]
label.text = dateOptions.monthTitle(at: row)
label.accessibilityLabel = "\(month.year)年\(month.number)月"
} else {
let month = dateOptions.months[max(pickerView.selectedRow(inComponent: 0), 0)]
label.text = "\(calendar.component(.day, from: month.dates[row]))日"
label.accessibilityLabel = label.text
}
return label
}
/// 更改月份时保留日号并收敛月末;更改端点后同步修正倒置区间。
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
usesAllDates = false
let monthIndex = max(pickerView.selectedRow(inComponent: 0), 0)
let value: Date
if component == 0 {
let current = endpoint == .start ? startDate : endDate
value = dateOptions.date(inMonthAt: row, preferredDay: calendar.component(.day, from: current))
} else {
value = dateOptions.months[monthIndex].dates[row]
}
if endpoint == .start {
startDate = value
if endDate < value { endDate = value }
@@ -1,9 +1,10 @@
import Kingfisher
import AVFoundation
import AVKit
import SnapKit
import UIKit
/// 景区空镜独立预览面板,仅播放应用内演示短片,不接入订单或网络素材。
/// 景区空境视频预览,正式素材播放服务端地址,Debug 素材保留本地预览。
@MainActor
final class ScenicMaterialPreviewViewController: UIViewController {
private let clip: ScenicMaterialClip
@@ -11,10 +12,17 @@ final class ScenicMaterialPreviewViewController: UIViewController {
private let capturedAt: Date
private let calendar: Calendar
private let playerController = AVPlayerViewController()
private let contentView = UIView()
private let coverView = UIImageView()
private let playButton = UIButton(type: .system)
private let playbackStatus = ScenicMaterialsStyle.label("本地演示短片 · 非真实景区视频", size: 11, color: ScenicMaterialsStyle.secondary)
private let playbackStatus = ScenicMaterialsStyle.label(size: 13, color: ScenicMaterialsStyle.secondary)
private let playbackTime = ScenicMaterialsStyle.label(size: 11, color: ScenicMaterialsStyle.secondary)
private let progressView = UIProgressView(progressViewStyle: .bar)
private var playbackTask: Task<Void, Never>?
private var playbackObservation: ScenicMaterialPlaybackObservation?
private var playbackGeneration = UUID()
private var playbackDuration: Double?
private var playbackFinished = false
/// 预览指定片段,原片元信息与本地演示视频时长明确区分。
init(clip: ScenicMaterialClip, routeName: String, capturedAt: Date, calendar: Calendar = .current) {
@@ -32,9 +40,16 @@ final class ScenicMaterialPreviewViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 510) }]
sheetPresentationController?.detents = [.custom { [weak self] context in
guard let self else { return min(context.maximumDetentValue, 490) }
let width = max(self.view.bounds.width, 320)
let fittingSize = self.contentView.systemLayoutSizeFitting(
CGSize(width: width, height: UIView.layoutFittingCompressedSize.height),
withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
return min(context.maximumDetentValue, fittingSize.height)
}]
sheetPresentationController?.prefersGrabberVisible = true
sheetPresentationController?.preferredCornerRadius = 24
sheetPresentationController?.preferredCornerRadius = 22
NotificationCenter.default.addObserver(self, selector: #selector(pausePlayback),
name: UIApplication.willResignActiveNotification, object: nil)
}
@@ -42,37 +57,51 @@ final class ScenicMaterialPreviewViewController: UIViewController {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
pausePlayback()
playbackTask?.cancel()
playbackTask = nil
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
stopPlayback()
}
private func setupUI() {
view.backgroundColor = .white
view.accessibilityIdentifier = "scenic.materials.preview.sheet"
let title = ScenicMaterialsStyle.label("视频预览", size: 19, weight: .semibold)
let closeButton = UIButton(type: .system)
closeButton.setImage(UIImage(systemName: "xmark"), for: .normal)
closeButton.tintColor = ScenicMaterialsStyle.secondary
closeButton.accessibilityLabel = "关闭景区视频预览"
closeButton.accessibilityIdentifier = "scenic.materials.preview.close"
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
let title = ScenicMaterialsStyle.label("视频预览", size: 18, weight: .semibold)
let mediaContainer = UIView()
mediaContainer.backgroundColor = .black
mediaContainer.layer.cornerRadius = 12
mediaContainer.layer.cornerRadius = 10
mediaContainer.clipsToBounds = true
coverView.image = UIImage(named: clip.coverAssetName)
mediaContainer.accessibilityIdentifier = "scenic.materials.preview.media"
if clip.isRemote {
coverView.kf.setImage(with: clip.coverURL, placeholder: UIImage(systemName: "photo"))
playbackStatus.text = "点击播放原片"
} else {
coverView.image = UIImage(named: clip.coverAssetName)
playbackStatus.text = "本地演示短片 · 非真实景区视频"
}
coverView.contentMode = .scaleAspectFill
coverView.clipsToBounds = true
playButton.setImage(UIImage(systemName: "play.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 48)), for: .normal)
playButton.tintColor = .white
playButton.accessibilityLabel = "播放本地演示视频"
playButton.accessibilityIdentifier = "scenic.materials.preview.play"
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
updatePlayButton(isPlaying: false)
playbackStatus.numberOfLines = 2
let metadata = ScenicMaterialsStyle.label("片段 \(String(format: "%02d", clip.ordinal)) · 原片 \(clip.durationText) · \(clip.resolution) · \(clip.sizeText)", size: 12, color: ScenicMaterialsStyle.secondary)
progressView.progressTintColor = ScenicMaterialsStyle.primary
progressView.trackTintColor = ScenicMaterialsStyle.border
progressView.accessibilityIdentifier = "scenic.materials.preview.progress"
progressView.accessibilityLabel = "播放进度"
playbackTime.accessibilityIdentifier = "scenic.materials.preview.playbackTime"
resetPlaybackTime()
let metadata = ScenicMaterialsStyle.label("\(clip.resolution) · \(clip.sizeText)", size: 11, color: ScenicMaterialsStyle.secondary)
metadata.numberOfLines = 2
metadata.textAlignment = .right
metadata.accessibilityIdentifier = "scenic.materials.preview.metadata"
let route = ScenicMaterialsStyle.label(routeName, size: 17, weight: .semibold)
let timeline = UIStackView(arrangedSubviews: [playbackTime, metadata])
timeline.alignment = .top
timeline.distribution = .fillEqually
timeline.spacing = 8
let route = ScenicMaterialsStyle.label(routeName, size: 16, weight: .semibold)
route.numberOfLines = 2
route.accessibilityIdentifier = "scenic.materials.preview.route"
let formatter = DateFormatter()
@@ -80,80 +109,192 @@ final class ScenicMaterialPreviewViewController: UIViewController {
formatter.timeZone = calendar.timeZone
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "MM-dd HH:mm"
let time = ScenicMaterialsStyle.label(formatter.string(from: capturedAt), size: 12, color: ScenicMaterialsStyle.secondary)
let time = ScenicMaterialsStyle.label("\(formatter.string(from: capturedAt)) · 片段 \(clip.ordinal)", size: 12, color: ScenicMaterialsStyle.secondary)
time.accessibilityIdentifier = "scenic.materials.preview.capturedAt"
let done = UIButton(type: .system)
done.setTitle("返回素材列表", for: .normal)
done.setTitleColor(ScenicMaterialsStyle.primary, for: .normal)
done.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
done.backgroundColor = ScenicMaterialsStyle.primary.withAlphaComponent(0.07)
done.setTitleColor(.white, for: .normal)
done.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
done.backgroundColor = ScenicMaterialsStyle.primary
done.layer.cornerRadius = 10
done.accessibilityIdentifier = "scenic.materials.preview.done"
done.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
let scroll = UIScrollView()
let content = UIView()
view.addSubview(scroll)
scroll.addSubview(content)
[title, closeButton, playbackStatus, mediaContainer, metadata, route, time, done].forEach(content.addSubview)
scroll.addSubview(contentView)
[title, playbackStatus, mediaContainer, progressView, timeline, route, time, done].forEach(contentView.addSubview)
addChild(playerController)
playerController.view.backgroundColor = .black
playerController.view.isHidden = true
playerController.showsPlaybackControls = false
playerController.allowsPictureInPicturePlayback = false
playerController.exitsFullScreenWhenPlaybackEnds = true
mediaContainer.addSubview(playerController.view)
playerController.didMove(toParent: self)
mediaContainer.addSubview(coverView)
mediaContainer.addSubview(playButton)
scroll.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
content.snp.makeConstraints { $0.edges.equalTo(scroll.contentLayoutGuide); $0.width.equalTo(scroll.frameLayoutGuide) }
title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) }
closeButton.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) }
playbackStatus.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(10); $0.leading.trailing.equalToSuperview().inset(22) }
contentView.snp.makeConstraints { $0.edges.equalTo(scroll.contentLayoutGuide); $0.width.equalTo(scroll.frameLayoutGuide) }
title.snp.makeConstraints { $0.top.equalToSuperview().offset(24); $0.leading.trailing.equalToSuperview().inset(18) }
playbackStatus.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(6); $0.leading.trailing.equalTo(title) }
mediaContainer.snp.makeConstraints {
$0.top.equalTo(playbackStatus.snp.bottom).offset(14)
$0.leading.trailing.equalToSuperview().inset(22)
$0.top.equalTo(playbackStatus.snp.bottom).offset(18)
$0.leading.trailing.equalTo(title)
$0.height.equalTo(mediaContainer.snp.width).multipliedBy(9.0 / 16.0)
}
playerController.view.snp.makeConstraints { $0.edges.equalToSuperview() }
coverView.snp.makeConstraints { $0.edges.equalToSuperview() }
playButton.snp.makeConstraints { $0.edges.equalToSuperview() }
metadata.snp.makeConstraints { $0.top.equalTo(mediaContainer.snp.bottom).offset(10); $0.leading.trailing.equalTo(mediaContainer) }
route.snp.makeConstraints { $0.top.equalTo(metadata.snp.bottom).offset(17); $0.leading.trailing.equalTo(mediaContainer) }
time.snp.makeConstraints { $0.top.equalTo(route.snp.bottom).offset(8); $0.leading.trailing.equalTo(mediaContainer) }
playButton.snp.makeConstraints { $0.center.equalToSuperview(); $0.size.equalTo(44) }
progressView.snp.makeConstraints { $0.top.equalTo(mediaContainer.snp.bottom).offset(16); $0.leading.trailing.equalTo(mediaContainer); $0.height.equalTo(3) }
timeline.snp.makeConstraints { $0.top.equalTo(progressView.snp.bottom).offset(8); $0.leading.trailing.equalTo(mediaContainer) }
route.snp.makeConstraints { $0.top.equalTo(timeline.snp.bottom).offset(22); $0.leading.trailing.equalTo(mediaContainer) }
time.snp.makeConstraints { $0.top.equalTo(route.snp.bottom).offset(7); $0.leading.trailing.equalTo(mediaContainer) }
done.snp.makeConstraints {
$0.top.equalTo(time.snp.bottom).offset(18)
$0.top.equalTo(time.snp.bottom).offset(20)
$0.leading.trailing.equalTo(mediaContainer)
$0.height.equalTo(44)
$0.bottom.equalToSuperview().inset(14)
$0.height.equalTo(46)
$0.bottom.equalToSuperview().inset(18)
}
}
@objc private func playTapped() {
guard playbackTask == nil, clip.isAvailable else { return }
guard let url = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock") else {
playbackStatus.text = "本地演示视频暂不可用"
if let player = playerController.player {
if player.rate > 0 {
pausePlayback()
} else {
if playbackFinished { player.seek(to: .zero); playbackFinished = false }
player.play()
updatePlayButton(isPlaying: true)
updatePlayingStatus()
}
return
}
let demoURL = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock")
guard let url = clip.isRemote ? clip.remoteURL : demoURL else {
playbackStatus.text = "视频地址暂不可用"
return
}
playButton.isEnabled = false
playbackGeneration = UUID()
let generation = playbackGeneration
playbackTask = Task { @MainActor [weak self] in
let playable = (try? await AVURLAsset(url: url).load(.isPlayable)) == true
guard let self else { return }
let asset = AVURLAsset(url: url)
let playable = (try? await asset.load(.isPlayable)) == true
let duration = try? await asset.load(.duration)
guard let self, self.playbackGeneration == generation else { return }
self.playbackTask = nil
self.playButton.isEnabled = true
guard !Task.isCancelled, self.view.window != nil else { return }
guard playable else {
self.playbackStatus.text = "本地演示视频暂不可播放"
self.playbackStatus.text = "视频暂不可播放,请稍后重试"
return
}
self.playerController.player = AVPlayer(url: url)
let seconds = duration?.seconds ?? .nan
self.playbackDuration = seconds.isFinite && seconds > 0 ? seconds : nil
let player = AVPlayer(playerItem: AVPlayerItem(asset: asset))
self.playerController.player = player
self.playerController.view.isHidden = false
self.coverView.isHidden = true
self.playButton.isHidden = true
self.playbackStatus.text = "正在播放 3 秒本地演示 · 原片时长见下方"
self.playerController.player?.play()
self.playbackFinished = false
self.playbackObservation = ScenicMaterialPlaybackObservation(player: player) { [weak self] time in
Task { @MainActor [weak self] in
guard let self, self.playbackGeneration == generation else { return }
self.updatePlaybackProgress(time)
}
}
NotificationCenter.default.addObserver(self, selector: #selector(playbackEnded),
name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
self.updatePlaybackProgress(.zero)
self.updatePlayingStatus()
self.updatePlayButton(isPlaying: true)
player.play()
}
}
@objc private func pausePlayback() { playerController.player?.pause() }
@objc private func closeTapped() { pausePlayback(); dismiss(animated: true) }
private func updatePlaybackProgress(_ time: CMTime) {
let seconds = time.seconds.isFinite ? max(time.seconds, 0) : 0
progressView.progress = playbackDuration.map { Float(min(seconds / $0, 1)) } ?? 0
let total = playbackDuration.map(Self.durationText) ?? "时长未知"
playbackTime.text = "\(Self.durationText(seconds)) / \(total)"
}
private func updatePlayingStatus() {
if clip.isRemote {
playbackStatus.text = "正在播放原片"
} else if let duration = playbackDuration {
playbackStatus.text = "正在播放 \(Int(duration.rounded())) 秒本地演示 · 原片 \(clip.durationText)"
} else {
playbackStatus.text = "正在播放本地演示 · 原片 \(clip.durationText)"
}
}
private func updatePlayButton(isPlaying: Bool) {
let symbol = isPlaying ? "pause.fill" : "play.fill"
playButton.setImage(UIImage(systemName: symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 24)), for: .normal)
playButton.accessibilityLabel = isPlaying ? "暂停播放" : (clip.isRemote ? "播放景区视频" : "播放本地演示视频")
}
private func resetPlaybackTime() {
playbackTime.text = "00:00 / \(clip.isRemote ? "" : "原片 ")\(clip.durationText)"
}
private static func durationText(_ seconds: Double) -> String {
let value = max(Int(seconds), 0)
return String(format: "%02d:%02d", value / 60, value % 60)
}
@objc private func playbackEnded() {
playbackFinished = true
if let duration = playbackDuration { updatePlaybackProgress(CMTime(seconds: duration, preferredTimescale: 600)) }
updatePlayButton(isPlaying: false)
playbackStatus.text = clip.isRemote ? "播放结束,点击重新播放" : "本地演示已结束 · 原片 \(clip.durationText)"
}
@objc private func pausePlayback() {
playerController.player?.pause()
if playbackTask != nil {
playbackGeneration = UUID()
playbackTask?.cancel()
playbackTask = nil
playButton.isEnabled = true
}
updatePlayButton(isPlaying: false)
if playerController.player != nil {
playbackStatus.text = clip.isRemote ? "已暂停,点击继续播放" : "本地演示已暂停 · 原片 \(clip.durationText)"
}
}
private func stopPlayback() {
pausePlayback()
playbackGeneration = UUID()
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: playerController.player?.currentItem)
playbackObservation = nil
playerController.player = nil
playerController.view.isHidden = true
coverView.isHidden = false
playbackDuration = nil
playbackFinished = false
progressView.progress = 0
resetPlaybackTime()
}
@objc private func closeTapped() {
stopPlayback()
dismiss(animated: true)
}
}
/// 与播放器成对持有周期观察令牌,释放时移除观察,避免弹窗销毁后残留定时回调。
private final class ScenicMaterialPlaybackObservation {
private let player: AVPlayer
private let token: Any
init(player: AVPlayer, onTime: @escaping @Sendable (CMTime) -> Void) {
self.player = player
token = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.1, preferredTimescale: 600),
queue: .main, using: onTime)
}
deinit { player.removeTimeObserver(token) }
}
@@ -1,3 +1,4 @@
import Photos
import SnapKit
import UIKit
@@ -21,6 +22,11 @@ final class ScenicMaterialsViewController: BaseViewController {
private let emptyMessage = ScenicMaterialsStyle.label(size: 14, color: ScenicMaterialsStyle.secondary)
private let resetButton = UIButton(type: .system)
private let driver = ScenicMaterialDemoDownloadDriver()
private let downloadService = ScenicMaterialDownloadService()
private var loadTask: Task<Void, Never>?
private let refreshControl = UIRefreshControl()
private let retryButton = UIButton(type: .system)
private var authorizationTask: Task<Void, Never>?
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var isDemoPhotoPermissionAllowed: Bool
@@ -36,6 +42,36 @@ final class ScenicMaterialsViewController: BaseViewController {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
if viewModel.isRemote { reloadRemoteMaterials() }
}
@objc private func reloadRemoteMaterials() {
guard viewModel.isRemote, !viewModel.isSelectionLocked else { refreshControl.endRefreshing(); return }
loadTask?.cancel()
let session = AppStore.shared.session
guard session.accountType == .storeUser, session.userId == viewModel.context.userID,
String(session.currentScenicId) == viewModel.context.scenicID else {
refreshControl.endRefreshing()
showToast("请使用门店账号并重新进入当前景区素材库")
return
}
let api = ScenicMaterialsAPI(client: NetworkServices.shared.apiClient)
emptyTitle.text = "正在加载素材"
emptyMessage.text = "请稍候"
retryButton.isHidden = true
routeButton.isEnabled = false
dateButton.isEnabled = false
loadTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.loadRemoteSessions(api: api)
guard !Task.isCancelled else { return }
self.refreshControl.endRefreshing()
self.refreshDisplay()
}
}
override func setupNavigationBar() {
title = "景区空境库"
navigationItem.backButtonDisplayMode = .minimal
@@ -48,12 +84,14 @@ final class ScenicMaterialsViewController: BaseViewController {
navigationItem.standardAppearance = appearance
navigationItem.scrollEdgeAppearance = appearance
#if DEBUG
guard !viewModel.isRemote else { return }
var actions: [UIAction] = ScenicMaterialsScenario.allCases.map { scenario in
UIAction(title: scenario.title) { [weak self] _ in self?.applyPreviewScenario(scenario) }
}
actions.append(UIAction(title: "相册权限不足") { [weak self] _ in
guard let self else { return }
self.driver.stop()
self.downloadService.stop()
self.viewModel.pauseDownload()
self.isDemoPhotoPermissionAllowed = false
self.refreshDisplay(animated: false)
@@ -89,6 +127,10 @@ final class ScenicMaterialsViewController: BaseViewController {
view.addSubview(filterBar)
view.addSubview(collectionView)
view.addSubview(footer)
if viewModel.isRemote {
collectionView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(reloadRemoteMaterials), for: .valueChanged)
}
setupEmptyView()
configureDataSource()
refreshDisplay(animated: false)
@@ -98,7 +140,7 @@ final class ScenicMaterialsViewController: BaseViewController {
filterBar.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide).offset(10)
make.leading.trailing.equalToSuperview().inset(16)
make.height.equalTo(42)
make.height.equalTo(40)
}
collectionView.snp.makeConstraints { make in
make.top.equalTo(filterBar.snp.bottom).offset(8)
@@ -116,6 +158,7 @@ final class ScenicMaterialsViewController: BaseViewController {
footer.onSecondaryTap = { [weak self] in
guard let self else { return }
self.driver.stop()
self.downloadService.stop()
if self.viewModel.phase == .downloading || self.viewModel.phase == .paused {
self.viewModel.cancelDownload()
} else {
@@ -133,20 +176,30 @@ final class ScenicMaterialsViewController: BaseViewController {
guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true else { return }
if let coordinator = transitionCoordinator, coordinator.isInteractive {
coordinator.animate(alongsideTransition: nil) { [weak self] context in
if !context.isCancelled { self?.pauseForBackground() }
if !context.isCancelled { self?.finishLeaving() }
}
} else {
pauseForBackground()
finishLeaving()
}
}
/// 仅在确认离开页面后作废异步工作,取消返回手势继续保留原来的加载及下载。
private func finishLeaving() {
loadTask?.cancel()
viewModel.cancelRemoteLoad()
authorizationTask?.cancel()
authorizationTask = nil
pauseForBackground()
}
/// 外部演示回执后显式刷新,不自动开始或继续任何传输。
func refreshDisplay(animated: Bool = true) {
guard dataSource != nil else { return }
routeButton.setTitle(viewModel.routeFilterTitle, for: .normal)
dateButton.setTitle(viewModel.dateFilterTitle, for: .normal)
routeButton.isEnabled = !viewModel.isSelectionLocked
dateButton.isEnabled = !viewModel.isSelectionLocked
routeButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading
dateButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading
retryButton.isHidden = viewModel.loadError == nil
emptyTitle.text = viewModel.emptyTitle
emptyMessage.text = viewModel.emptyMessage
resetButton.isHidden = viewModel.selectedRouteID == nil && viewModel.dateRange == nil
@@ -184,21 +237,26 @@ final class ScenicMaterialsViewController: BaseViewController {
private func configureFilterButton(_ button: UIButton, identifier: String) {
var configuration = UIButton.Configuration.plain()
configuration.image = UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium))
configuration.imagePlacement = .trailing
configuration.imagePadding = 8
configuration.baseForegroundColor = ScenicMaterialsStyle.text
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)
configuration.cornerStyle = .fixed
configuration.background.cornerRadius = 11
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 32)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var result = incoming; result.font = .systemFont(ofSize: 13); return result
var result = incoming; result.font = .systemFont(ofSize: 15, weight: .medium); return result
}
button.configuration = configuration
button.backgroundColor = UIColor(hex: 0xF6F7F9)
button.layer.cornerRadius = 10
button.layer.borderWidth = 0.5
button.contentHorizontalAlignment = .leading
button.backgroundColor = UIColor(hex: 0xF7F8FA)
button.layer.cornerRadius = 11
button.layer.borderWidth = 1
button.layer.borderColor = ScenicMaterialsStyle.border.cgColor
button.titleLabel?.lineBreakMode = .byTruncatingTail
button.accessibilityIdentifier = identifier
let chevron = UIImageView(image: UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium)))
chevron.tintColor = ScenicMaterialsStyle.secondary
chevron.isUserInteractionEnabled = false
button.addSubview(chevron)
chevron.snp.makeConstraints { $0.trailing.equalToSuperview().inset(12); $0.centerY.equalToSuperview() }
}
private func setupEmptyView() {
@@ -213,7 +271,10 @@ final class ScenicMaterialsViewController: BaseViewController {
resetButton.tintColor = ScenicMaterialsStyle.primary
resetButton.accessibilityIdentifier = "scenic.materials.resetFilters"
emptyView.accessibilityIdentifier = "scenic.materials.empty"
let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton])
retryButton.setTitle("重新加载", for: .normal)
retryButton.accessibilityIdentifier = "scenic.materials.retry"
retryButton.addTarget(self, action: #selector(reloadRemoteMaterials), for: .touchUpInside)
let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton, retryButton])
stack.axis = .vertical
stack.spacing = 14
emptyView.addSubview(stack)
@@ -246,7 +307,7 @@ final class ScenicMaterialsViewController: BaseViewController {
return cell
case .retention, .end:
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! ScenicMaterialTextCell
cell.configure(item == .retention ? "素材保留 90 天,请及时下载" : "已显示保留期内的全部演示记录", identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end")
cell.configure(item == .retention ? self.viewModel.retentionTips : (self.viewModel.isRemote ? "已显示全部素材" : "已显示保留期内的全部演示记录"), identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end")
return cell
}
}
@@ -265,7 +326,7 @@ final class ScenicMaterialsViewController: BaseViewController {
let completed = viewModel.completedIDs.contains(clip.id)
let failed = viewModel.failedIDs.contains(clip.id)
let inBatch = viewModel.batchItemIDs.contains(clip.id)
let status: String? = completed ? "演示已下载" : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil
let status: String? = completed ? (viewModel.isRemote ? "已保存相册" : "演示已下载") : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil
cell.configure(clip: clip, selected: viewModel.selectedIDs.contains(clip.id),
isSelectionEnabled: viewModel.canSelect(id: clip.id), statusText: status,
progress: inBatch && viewModel.phase == .downloading && !completed ? viewModel.progressByID[clip.id] ?? 0 : nil,
@@ -356,20 +417,20 @@ final class ScenicMaterialsViewController: BaseViewController {
let total = viewModel.totalCount
switch viewModel.phase {
case .idle:
footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: "本地演示 · 不下载或保存真实文件",
primaryTitle: viewModel.selectedCount > 0 ? "下载所选(\(viewModel.selectedCount))" : "下载所选", primaryEnabled: viewModel.canStartDownload)
footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: viewModel.isRemote ? nil : "本地演示 · 不下载或保存真实文件",
primaryTitle: "下载所选", primaryEnabled: viewModel.canStartDownload)
case .downloading:
footer.configure(title: "下载中 · \(completed)/\(total) 段", detail: "请保持页面开启,切后台将暂停",
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress))
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress, isBusy: true)
case .paused:
footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "演示进度已保留,请手动继续",
primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消")
footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "已完成项已保留,请手动继续",
primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress)
case .partialFailure:
footer.configure(title: "演示完成 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: "未保存真实文件,成功项不重复下载",
primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择")
footer.configure(title: "已下载 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: viewModel.isRemote ? "成功项已保存相册" : "演示结果 · 未保存真实文件",
primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择", layout: .result)
case .completed:
footer.configure(title: "演示完成 \(completed) 段", detail: "未写入系统相册",
primaryTitle: "继续选择素材", primaryEnabled: true)
footer.configure(title: viewModel.isRemote ? "已保存 \(completed) 段" : "演示完成 \(completed) 段", detail: viewModel.isRemote ? "可在系统相册查看" : "未写入系统相册",
primaryTitle: "继续选择素材", primaryEnabled: true, layout: .result)
}
}
@@ -377,7 +438,27 @@ final class ScenicMaterialsViewController: BaseViewController {
if viewModel.phase == .completed {
viewModel.continueSelecting(); refreshDisplay(); return
}
if viewModel.isRemote {
guard authorizationTask == nil else { return }
authorizationTask = Task { @MainActor [weak self] in
let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
guard let self else { return }
self.authorizationTask = nil
guard !Task.isCancelled, self.view.window != nil,
UIApplication.shared.applicationState == .active else { return }
guard status == .authorized || status == .limited else {
self.presentPhotoPermissionSettings()
return
}
self.startTransfer()
}
return
}
guard isDemoPhotoPermissionAllowed else { presentPermissionDemo(); return }
startTransfer()
}
private func startTransfer() {
let started: Bool
switch viewModel.phase {
case .idle: started = viewModel.startDownload()
@@ -386,11 +467,25 @@ final class ScenicMaterialsViewController: BaseViewController {
case .downloading, .completed: started = false
}
refreshDisplay(animated: false)
if started { driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) } }
guard started else { return }
if viewModel.isRemote, let batchID = viewModel.batchID {
let items = viewModel.pendingIDs.compactMap { id -> ScenicMaterialDownloadItem? in
guard let clip = viewModel.clip(id: id), let url = clip.remoteURL else { return nil }
return ScenicMaterialDownloadItem(id: id, remoteURL: url,
fileName: url.pathExtension.isEmpty ? "scenic-material.mp4" : url.lastPathComponent)
}
downloadService.start(items: items, batchID: batchID) { [weak self] id, token, event in
self?.viewModel.receive(event, clipID: id, batchID: token)
self?.refreshDisplay(animated: false)
} onFailure: { [weak self] _, error in self?.showToast(error.localizedDescription) }
} else {
driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) }
}
}
@objc private func pauseForBackground() {
driver.stop()
downloadService.stop()
viewModel.pauseDownload()
if isViewLoaded { refreshDisplay(animated: false) }
}
@@ -400,6 +495,7 @@ final class ScenicMaterialsViewController: BaseViewController {
let picker = ScenicMaterialRouteFilterViewController(routes: viewModel.routes, selectedRouteID: viewModel.selectedRouteID)
picker.onSelectRoute = { [weak self] id in
self?.viewModel.setRoute(id: id)
self?.reloadRemoteMaterials()
self?.refreshDisplay()
self?.collectionView.setContentOffset(.zero, animated: false)
}
@@ -414,6 +510,7 @@ final class ScenicMaterialsViewController: BaseViewController {
picker.onSelectRange = { [weak self] start, end in
guard let self else { return }
if self.viewModel.setDateRange(start: start, end: end) {
self.reloadRemoteMaterials()
self.refreshDisplay()
self.collectionView.setContentOffset(.zero, animated: false)
} else { self.showToast("请选择保留期内的有效日期范围") }
@@ -423,6 +520,7 @@ final class ScenicMaterialsViewController: BaseViewController {
@objc private func resetFilters() {
viewModel.resetFilters()
reloadRemoteMaterials()
refreshDisplay()
}
@@ -433,6 +531,16 @@ final class ScenicMaterialsViewController: BaseViewController {
present(controller, animated: true)
}
private func presentPhotoPermissionSettings() {
guard presentedViewController == nil else { return }
let alert = UIAlertController(title: "需要相册保存权限", message: "请允许添加照片和视频,以保存所选素材。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in
if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
})
present(alert, animated: true)
}
private func presentPermissionDemo() {
guard presentedViewController == nil else { return }
let alert = UIAlertController(title: "需要相册保存权限", message: "真实下载需允许保存视频。此处仅演示权限流程,不读取或修改系统权限。", preferredStyle: .alert)