feat(drone-dock): 搭建素材库预览选择与下载演示
This commit is contained in:
@@ -0,0 +1,252 @@
|
||||
import Foundation
|
||||
|
||||
/// 素材内容类型,不把视频封面当作可播放视频。
|
||||
enum DroneMaterialKind: Hashable, Sendable {
|
||||
case photo, video
|
||||
|
||||
/// 素材类型展示名称。
|
||||
var title: String { self == .photo ? "照片" : "视频" }
|
||||
}
|
||||
|
||||
/// 云端上传状态独立于本机下载、相册保存和游客交付。
|
||||
enum DroneMaterialUploadState: Hashable, Sendable {
|
||||
case uploading, ready, failed, unavailable
|
||||
|
||||
/// 上传状态名称;上传中不展示虚构百分比。
|
||||
var title: String {
|
||||
switch self {
|
||||
case .uploading: "上传中"
|
||||
case .ready: "上传完成"
|
||||
case .failed: "上传失败"
|
||||
case .unavailable: "素材不可用"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 单文件下载和保存阶段;演示完成不能冒充实际写入相册。
|
||||
enum DroneMaterialDownloadState: Hashable, Sendable {
|
||||
case available
|
||||
case downloading(progress: Double)
|
||||
case paused
|
||||
case downloadFailed(message: String)
|
||||
case awaitingSave
|
||||
case saving
|
||||
case saveFailed(message: String)
|
||||
case completed(isSimulation: Bool)
|
||||
|
||||
/// 只有本设备真实保存回执才能使用非演示完成状态。
|
||||
var isCompleted: Bool {
|
||||
if case .completed = self { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
/// 下载失败与保存失败均可单独重试,权限拒绝不归入失败。
|
||||
var isFailed: Bool {
|
||||
switch self {
|
||||
case .downloadFailed, .saveFailed: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前文件是否仍在执行本地传输或保存。
|
||||
var isRunning: Bool {
|
||||
switch self {
|
||||
case .downloading, .awaitingSave, .saving: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
|
||||
/// 单文件状态文案。
|
||||
var title: String {
|
||||
switch self {
|
||||
case .available: "上传完成 · 可下载"
|
||||
case .downloading: "下载中"
|
||||
case .paused: "下载已暂停"
|
||||
case .downloadFailed: "下载失败"
|
||||
case .awaitingSave: "下载完成 · 待保存"
|
||||
case .saving: "正在演示保存"
|
||||
case .saveFailed: "保存失败"
|
||||
case .completed(let isSimulation): isSimulation ? "演示完成 · 未写入相册" : "本机已保存"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 单条原素材;预览使用本地资源,不请求真实素材接口。
|
||||
struct DroneMaterial: Hashable, Sendable {
|
||||
/// 在订单中稳定且唯一的素材标识。
|
||||
let id: String
|
||||
/// 素材展示名称。
|
||||
let title: String
|
||||
/// 图片或视频。
|
||||
let kind: DroneMaterialKind
|
||||
/// 本地图片或视频封面资源名。
|
||||
let previewAssetName: String
|
||||
/// 可选本地媒体文件;演示夹具没有真实视频文件时为 nil。
|
||||
let previewURL: URL?
|
||||
/// 已知本地示例时长,图片或未知视频使用 nil。
|
||||
let durationText: String?
|
||||
/// 云端生成和上传结果。
|
||||
var uploadState: DroneMaterialUploadState
|
||||
/// 本机下载和保存结果。
|
||||
var downloadState: DroneMaterialDownloadState
|
||||
|
||||
/// 创建独立于 UI 框架的素材快照。
|
||||
init(id: String, title: String, kind: DroneMaterialKind = .photo,
|
||||
previewAssetName: String = "drone_demo_tourists", previewURL: URL? = nil, durationText: String? = nil,
|
||||
uploadState: DroneMaterialUploadState = .ready,
|
||||
downloadState: DroneMaterialDownloadState = .available) {
|
||||
self.id = id
|
||||
self.title = title
|
||||
self.kind = kind
|
||||
self.previewAssetName = previewAssetName
|
||||
self.previewURL = previewURL
|
||||
self.durationText = durationText
|
||||
self.uploadState = uploadState
|
||||
self.downloadState = downloadState
|
||||
}
|
||||
|
||||
/// 上传成功后才允许进入预览,失败和上传中不显示假预览。
|
||||
var canPreview: Bool { uploadState == .ready }
|
||||
/// 当前可纳入选择的未完成素材;已下载待保存的文件可重选后只做保存。
|
||||
var canDownload: Bool {
|
||||
guard uploadState == .ready else { return false }
|
||||
switch downloadState {
|
||||
case .available, .paused, .downloadFailed, .awaitingSave, .saveFailed: return true
|
||||
case .downloading, .saving, .completed: return false
|
||||
}
|
||||
}
|
||||
/// 列表优先显示上传阻断,再显示本机处理阶段。
|
||||
var statusTitle: String { uploadState == .ready ? downloadState.title : uploadState.title }
|
||||
/// 列表状态的语义色。
|
||||
var statusTone: DroneDockStatusTone {
|
||||
guard uploadState == .ready else {
|
||||
switch uploadState {
|
||||
case .failed: return .red
|
||||
case .uploading: return .blue
|
||||
default: return .gray
|
||||
}
|
||||
}
|
||||
switch downloadState {
|
||||
case .available, .completed: return .green
|
||||
case .downloadFailed, .saveFailed: return .red
|
||||
case .paused: return .orange
|
||||
default: return .blue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按一次拍摄分组的原素材,不把订单次数和素材数量合并。
|
||||
struct DroneMaterialRecord: Hashable, Sendable {
|
||||
/// 拍摄记录稳定标识。
|
||||
let id: String
|
||||
/// 所属拍摄点稳定标识。
|
||||
let pointID: String
|
||||
/// 拍摄点快照名称。
|
||||
let pointName: String
|
||||
/// 本次航线快照名称。
|
||||
let routeName: String
|
||||
/// 用于最新在前排序的拍摄时间。
|
||||
let capturedAt: Date
|
||||
/// 展示用拍摄时间。
|
||||
let capturedAtText: String
|
||||
/// 订单内拍摄记录序号。
|
||||
let sequenceNumber: Int
|
||||
/// 本次拍摄生成的文件。
|
||||
var materials: [DroneMaterial]
|
||||
|
||||
/// 记录标题摘要。
|
||||
var summary: String { "\(routeName) · \(capturedAtText) · 记录\(String(format: "%02d", sequenceNumber))" }
|
||||
}
|
||||
|
||||
/// 整单素材库的点位筛选项,nil 代表全部点位。
|
||||
struct DroneMaterialPointFilter: Hashable, Sendable {
|
||||
/// 稳定点位标识,全部项使用 nil。
|
||||
let id: String?
|
||||
/// 点位展示名称。
|
||||
let title: String
|
||||
}
|
||||
|
||||
/// 列表加载结果与上传状态分别表达。
|
||||
enum DroneMaterialsListState: Hashable, Sendable {
|
||||
case loaded, loading, failed(message: String)
|
||||
}
|
||||
|
||||
/// 本地演示的相册写入许可,不查询或请求系统 Photos 权限。
|
||||
enum DroneMaterialPhotoPermission: Hashable, Sendable {
|
||||
case allowed, denied, restricted
|
||||
|
||||
/// 只有许可明确时才允许发起演示保存。
|
||||
var canSave: Bool { self == .allowed }
|
||||
}
|
||||
|
||||
/// 暂停入口用于区分生命周期和权限阻断。
|
||||
enum DroneMaterialPauseReason: Hashable, Sendable {
|
||||
case background, locked, leavingPage, permissionDenied
|
||||
}
|
||||
|
||||
/// 一批固定素材的执行引用;更换 UUID 后旧执行回执失效。
|
||||
struct DroneMaterialDownloadBatch: Hashable, Sendable {
|
||||
/// 本次执行令牌,继续和重试时更新。
|
||||
let id: UUID
|
||||
/// 批次固定范围,不受后续点位筛选影响。
|
||||
let itemIDs: [String]
|
||||
/// 是否等待用户手动继续。
|
||||
var isPaused: Bool
|
||||
/// 最近一次暂停的明确原因。
|
||||
var pauseReason: DroneMaterialPauseReason?
|
||||
}
|
||||
|
||||
/// 批次展示阶段,权限拒绝仍从独立许可属性读取。
|
||||
enum DroneMaterialDownloadPhase: Hashable, Sendable {
|
||||
case idle, downloading, awaitingSave, saving, paused, partialFailure, completed
|
||||
}
|
||||
|
||||
/// 可注入本地驱动的明确回执,不包含网络或 Photos 实现。
|
||||
enum DroneMaterialTransferEvent: Hashable, Sendable {
|
||||
case progress(Double)
|
||||
case downloadCompleted
|
||||
case downloadFailed(message: String)
|
||||
case saveStarted
|
||||
case saveFailed(message: String)
|
||||
case saveSucceeded
|
||||
}
|
||||
|
||||
/// 订单共享素材缓存;不会修改拍摄任务、拍摄次数或游客交付状态。
|
||||
struct DroneMaterialLibraryState {
|
||||
/// 按记录保存原素材。
|
||||
var records: [DroneMaterialRecord]
|
||||
/// 首次加载或显式演示的列表状态。
|
||||
var listState: DroneMaterialsListState = .loaded
|
||||
/// 当前下载批次。
|
||||
var batch: DroneMaterialDownloadBatch?
|
||||
/// 演示许可,与系统权限无关。
|
||||
var photoPermission: DroneMaterialPhotoPermission = .allowed
|
||||
/// 已映射到素材记录的成功拍摄数,后续成功可追加记录。
|
||||
var sourceShootingCount: Int = 0
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// 素材页面显式验收场景,不自动调用下载或照片写入接口。
|
||||
enum DroneMaterialsScenario: String, CaseIterable, Hashable {
|
||||
case ready, uploading, mixed, downloading, paused, partialFailure, permissionDenied, saveFailure, completed
|
||||
case empty, loading, loadFailure
|
||||
|
||||
/// Debug 场景菜单名称。
|
||||
var title: String {
|
||||
switch self {
|
||||
case .ready: "素材全部就绪"
|
||||
case .uploading: "素材上传中"
|
||||
case .mixed: "部分就绪与上传失败"
|
||||
case .downloading: "下载中"
|
||||
case .paused: "后台暂停待继续"
|
||||
case .partialFailure: "部分下载失败"
|
||||
case .permissionDenied: "相册权限拒绝(演示)"
|
||||
case .saveFailure: "下载完成但保存失败"
|
||||
case .completed: "演示完成,未写入相册"
|
||||
case .empty: "暂无素材"
|
||||
case .loading: "首次加载中"
|
||||
case .loadFailure: "列表加载失败"
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -12,6 +12,8 @@ final class DroneDockDemoStore {
|
||||
var shootingPreparations: [DroneShootingSessionKey: DroneShootingPreparationState] = [:]
|
||||
/// 当前或最近一次本地任务;飞行结束后仍保留结果页快照。
|
||||
var shootingSessions: [DroneShootingSessionKey: DroneShootingSession] = [:]
|
||||
/// 原素材和本机演示下载结果按上下文、订单隔离,页面重进时仍可读取。
|
||||
var materialLibraries: [DroneShootingSessionKey: DroneMaterialLibraryState] = [:]
|
||||
#if DEBUG
|
||||
/// 预览切换前的订单,恢复正常场景时不累计演示扣次。
|
||||
var shootingScenarioBaselines: [DroneShootingSessionKey: DroneShootingOrder] = [:]
|
||||
@@ -78,6 +80,7 @@ final class DroneDockDemoStore {
|
||||
shootingPreparations = shootingPreparations.filter { $0.key.context != context }
|
||||
shootingSessions = shootingSessions.filter { $0.key.context != context }
|
||||
shootingScenarioBaselines = shootingScenarioBaselines.filter { $0.key.context != context }
|
||||
materialLibraries = materialLibraries.filter { $0.key.context != context }
|
||||
var orders = DroneDockDemoData.orders(context: context)
|
||||
var devices = DroneDockDemoData.devices()
|
||||
switch scenario {
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
import Foundation
|
||||
|
||||
/// 订单原素材的分组、选择和前台下载规则;由 View 在明确事件后主动刷新。
|
||||
final class DroneMaterialsViewModel {
|
||||
/// 与工作台、任务和订单列表共用的本地数据源。
|
||||
let store: DroneDockDemoStore
|
||||
/// 入口订单的固定标识。
|
||||
let orderID: String
|
||||
/// 任务入口固定点位,整单入口为 nil。
|
||||
let pointID: String?
|
||||
/// 当前整单筛选;固定点位入口不能切换为其他点位。
|
||||
private(set) var selectedFilterID: String?
|
||||
/// 当前筛选范围中的人工选择,切换筛选时清空。
|
||||
private(set) var selectedIDs: Set<String> = []
|
||||
private let context: DroneDockContext
|
||||
|
||||
/// 当前上下文可访问的订单,旧页面不能操作其他景区的同名订单。
|
||||
var order: DroneShootingOrder? { isCurrentContext ? store.shootingOrder(id: orderID) : nil }
|
||||
/// 列表状态,不与素材上传失败混用。
|
||||
var listState: DroneMaterialsListState { library?.listState ?? .loaded }
|
||||
/// 当前演示保存许可,不代表系统真实 Photos 权限。
|
||||
var photoPermission: DroneMaterialPhotoPermission { library?.photoPermission ?? .denied }
|
||||
/// 固定于批次开始时的素材范围及执行令牌。
|
||||
var batch: DroneMaterialDownloadBatch? { library?.batch }
|
||||
/// 当前点位范围下按拍摄时间从新到旧排列的记录。
|
||||
var sections: [DroneMaterialRecord] {
|
||||
guard listState == .loaded else { return [] }
|
||||
return allRecords.filter { selectedFilterID == nil || $0.pointID == selectedFilterID }
|
||||
}
|
||||
/// 整单入口提供全部点位,任务入口只展示限定点位。
|
||||
var filters: [DroneMaterialPointFilter] {
|
||||
if let pointID {
|
||||
let name = allRecords.first { $0.pointID == pointID }?.pointName
|
||||
?? store.shootingPreparations[key]?.points.first { $0.id == pointID }?.name ?? "当前拍摄点"
|
||||
return [DroneMaterialPointFilter(id: pointID, title: name)]
|
||||
}
|
||||
var seen: Set<String> = []
|
||||
return [DroneMaterialPointFilter(id: nil, title: "全部点位")] + allRecords.compactMap {
|
||||
guard seen.insert($0.pointID).inserted else { return nil }
|
||||
return DroneMaterialPointFilter(id: $0.pointID, title: $0.pointName)
|
||||
}
|
||||
}
|
||||
/// 当前列表已上传且未完成的可选择素材,不包括其他筛选中的文件。
|
||||
var downloadableIDs: Set<String> { Set(sections.flatMap(\.materials).filter(\.canDownload).map(\.id)) }
|
||||
/// 当前有效的勾选项数量。
|
||||
var selectedCount: Int { selectedIDs.count }
|
||||
/// 可下载项非空且全部被选中时才显示全选标记。
|
||||
var isAllSelected: Bool { !downloadableIDs.isEmpty && downloadableIDs.isSubset(of: selectedIDs) }
|
||||
/// 批次未清除前锁定筛选和选择,继续选择入口明确结束旧批次。
|
||||
var isSelectionLocked: Bool { batch != nil }
|
||||
/// 是否可创建一个新的本地演示批次;拒权仍允许按钮展示权限说明。
|
||||
var canStartDownload: Bool { order != nil && listState == .loaded && batch == nil && !isSelectionLocked && selectedCount > 0 }
|
||||
/// 当前筛选下可预览素材;预览不会修改勾选或下载生命周期。
|
||||
var previewMaterials: [DroneMaterial] { sections.flatMap(\.materials).filter(\.canPreview) }
|
||||
/// 本批次固定文件数。
|
||||
var batchTotalCount: Int { batch?.itemIDs.count ?? 0 }
|
||||
/// 本批次真实或演示完成的数量,不把仅下载完成计作保存完成。
|
||||
var completedCount: Int { batchMaterials.filter { $0.downloadState.isCompleted }.count }
|
||||
/// 本批次明确下载失败或保存失败的数量。
|
||||
var failedCount: Int { batchMaterials.filter { $0.downloadState.isFailed }.count }
|
||||
/// 未完成且没有明确失败的文件数,继续时只处理这些文件。
|
||||
var pendingCount: Int { batchMaterials.filter { !$0.downloadState.isCompleted && !$0.downloadState.isFailed }.count }
|
||||
/// 以完成文件数统计的进度,上传中不使用此进度。
|
||||
var batchProgress: Double { batchTotalCount == 0 ? 0 : Double(completedCount) / Double(batchTotalCount) }
|
||||
/// 页面底部的批次阶段。
|
||||
var downloadPhase: DroneMaterialDownloadPhase {
|
||||
guard let batch else { return .idle }
|
||||
if batch.isPaused && pendingCount > 0 { return .paused }
|
||||
if batchMaterials.contains(where: { if case .downloading = $0.downloadState { return true }; return false }) { return .downloading }
|
||||
if batchMaterials.contains(where: { $0.downloadState == .saving }) { return .saving }
|
||||
if batchMaterials.contains(where: { $0.downloadState == .awaitingSave }) { return .awaitingSave }
|
||||
if failedCount > 0 { return .partialFailure }
|
||||
return completedCount == batchTotalCount ? .completed : .idle
|
||||
}
|
||||
/// 主操作的标题,演示成功与真实保存始终区分。
|
||||
var downloadButtonTitle: String {
|
||||
switch downloadPhase {
|
||||
case .idle: "下载所选素材"
|
||||
case .downloading, .awaitingSave, .saving: "演示下载中…"
|
||||
case .paused: "继续下载"
|
||||
case .partialFailure: "仅重试失败项"
|
||||
case .completed: "继续选择素材"
|
||||
}
|
||||
}
|
||||
/// 记录区数量摘要。
|
||||
var summaryText: String { "\(sections.count)次拍摄 · 最新在前" }
|
||||
/// 页面标题。
|
||||
var title: String { "订单素材库" }
|
||||
|
||||
private var isCurrentContext: Bool { store.context == context }
|
||||
private var key: DroneShootingSessionKey { DroneShootingSessionKey(context: context, orderID: orderID) }
|
||||
private var library: DroneMaterialLibraryState? { order != nil ? store.materialLibraries[key] : nil }
|
||||
private var allRecords: [DroneMaterialRecord] {
|
||||
(library?.records ?? []).sorted {
|
||||
if $0.capturedAt == $1.capturedAt { return $0.sequenceNumber > $1.sequenceNumber }
|
||||
return $0.capturedAt > $1.capturedAt
|
||||
}
|
||||
}
|
||||
private var batchMaterials: [DroneMaterial] {
|
||||
guard let batch else { return [] }
|
||||
let ids = Set(batch.itemIDs)
|
||||
return allRecords.flatMap(\.materials).filter { ids.contains($0.id) }
|
||||
}
|
||||
|
||||
/// 固定订单及可选任务点位;首次访问只创建对应成功记录的演示素材。
|
||||
init(store: DroneDockDemoStore, orderID: String, pointID: String? = nil) {
|
||||
self.store = store
|
||||
self.orderID = orderID
|
||||
self.pointID = pointID
|
||||
selectedFilterID = pointID
|
||||
context = store.context
|
||||
refresh()
|
||||
}
|
||||
|
||||
/// 页面出现或手动刷新时同步本地记录;不会自动完成上传或恢复暂停下载。
|
||||
func refresh() {
|
||||
guard isCurrentContext, let order else {
|
||||
pauseStoredBatch(reason: .leavingPage)
|
||||
selectedIDs = []
|
||||
return
|
||||
}
|
||||
store.ensureShootingPreparation(orderID: orderID)
|
||||
var state = store.materialLibraries[key] ?? DroneMaterialLibraryState(records: [])
|
||||
state.listState = .loaded
|
||||
if order.successfulShootingCount > state.sourceShootingCount {
|
||||
let points = store.shootingPreparations[key]?.points ?? []
|
||||
let session = store.shootingSession(orderID: orderID)
|
||||
for sequence in (state.sourceShootingCount + 1)...order.successfulShootingCount {
|
||||
state.records.append(Self.demoRecord(order: order, sequence: sequence, points: points, session: session))
|
||||
}
|
||||
state.sourceShootingCount = order.successfulShootingCount
|
||||
}
|
||||
restrictBatchToEntryScope(in: &state)
|
||||
store.materialLibraries[key] = state
|
||||
if isSelectionLocked {
|
||||
let validIDs = Set(sections.flatMap(\.materials).filter { $0.canPreview && !$0.downloadState.isCompleted }.map(\.id))
|
||||
selectedIDs.formIntersection(validIDs)
|
||||
} else {
|
||||
selectedIDs.formIntersection(downloadableIDs)
|
||||
}
|
||||
}
|
||||
|
||||
/// 显式切换整单点位筛选,清空旧范围的选择;固定点位入口拒绝扩大范围。
|
||||
func selectFilter(id: String?) {
|
||||
guard !isSelectionLocked, pointID == nil, filters.contains(where: { $0.id == id }) else { return }
|
||||
guard selectedFilterID != id else { return }
|
||||
selectedFilterID = id
|
||||
selectedIDs = []
|
||||
}
|
||||
|
||||
/// 勾选当前可下载素材,上传中、失败上传、完成项和隐藏项都不可选。
|
||||
func toggleSelection(id: String) {
|
||||
guard !isSelectionLocked, downloadableIDs.contains(id) else { return }
|
||||
if !selectedIDs.insert(id).inserted { selectedIDs.remove(id) }
|
||||
}
|
||||
|
||||
/// 全选只覆盖当前筛选可下载项,再次点击取消本范围选择。
|
||||
func selectAll() {
|
||||
guard !isSelectionLocked else { return }
|
||||
selectedIDs = isAllSelected ? [] : downloadableIDs
|
||||
}
|
||||
|
||||
/// 读取入口范围内素材;执行回执另按批次固定范围校验。
|
||||
func material(id: String) -> DroneMaterial? {
|
||||
allRecords.filter { pointID == nil || $0.pointID == pointID }.flatMap(\.materials).first { $0.id == id }
|
||||
}
|
||||
|
||||
/// 创建演示下载批次;系统权限和真实照片写入由后续真实服务单独接入。
|
||||
@discardableResult
|
||||
func startDownload() -> Bool {
|
||||
guard canStartDownload, photoPermission.canSave, var state = library else { return false }
|
||||
let ids = sections.flatMap(\.materials).map(\.id).filter { selectedIDs.contains($0) && downloadableIDs.contains($0) }
|
||||
guard !ids.isEmpty else { return false }
|
||||
state.batch = DroneMaterialDownloadBatch(id: UUID(), itemIDs: ids, isPaused: false, pauseReason: nil)
|
||||
prepareAttempts(in: &state, ids: Set(ids), retryFailures: true)
|
||||
store.materialLibraries[key] = state
|
||||
return true
|
||||
}
|
||||
|
||||
/// 后台、锁屏或离页暂停,并使暂停前回执令牌立即失效。
|
||||
func pauseDownloads(reason: DroneMaterialPauseReason) {
|
||||
guard isCurrentContext else { return }
|
||||
pauseStoredBatch(reason: reason)
|
||||
}
|
||||
|
||||
/// 离开素材页停止未完成执行;预览弹层不应调用此入口。
|
||||
func leavePage() { pauseDownloads(reason: .leavingPage) }
|
||||
|
||||
/// 回到前台只由用户手动继续;不处理失败项,不重做已完成项。
|
||||
@discardableResult
|
||||
func continueDownload() -> Bool {
|
||||
guard photoPermission.canSave, var state = library, let oldBatch = state.batch,
|
||||
oldBatch.isPaused, pendingCount > 0 else { return false }
|
||||
let ids = Set(batchMaterials.filter { !$0.downloadState.isCompleted && !$0.downloadState.isFailed }.map(\.id))
|
||||
state.batch = DroneMaterialDownloadBatch(id: UUID(), itemIDs: oldBatch.itemIDs, isPaused: false, pauseReason: nil)
|
||||
prepareAttempts(in: &state, ids: ids, retryFailures: false)
|
||||
store.materialLibraries[key] = state
|
||||
return true
|
||||
}
|
||||
|
||||
/// 只重试当前批次明确失败的文件;保存失败重试保存,不重新下载。
|
||||
@discardableResult
|
||||
func retryFailed() -> Bool {
|
||||
guard photoPermission.canSave, var state = library, let oldBatch = state.batch,
|
||||
failedCount > 0, pendingCount == 0,
|
||||
!batchMaterials.contains(where: { $0.downloadState.isRunning }) else { return false }
|
||||
let ids = Set(batchMaterials.filter { $0.downloadState.isFailed }.map(\.id))
|
||||
state.batch = DroneMaterialDownloadBatch(id: UUID(), itemIDs: oldBatch.itemIDs, isPaused: false, pauseReason: nil)
|
||||
prepareAttempts(in: &state, ids: ids, retryFailures: true)
|
||||
store.materialLibraries[key] = state
|
||||
return true
|
||||
}
|
||||
|
||||
/// 结束已停止或已完成的批次后继续选择;已完成文件永远保留。
|
||||
func clearBatch() {
|
||||
guard var state = library, !batchMaterials.contains(where: { $0.downloadState.isRunning }),
|
||||
state.batch != nil else { return }
|
||||
state.batch = nil
|
||||
store.materialLibraries[key] = state
|
||||
selectedIDs = []
|
||||
}
|
||||
|
||||
/// 设置演示许可,恢复许可不自动开始;拒权与文件失败分离。
|
||||
func setPhotoPermission(_ permission: DroneMaterialPhotoPermission) {
|
||||
guard var state = library else { return }
|
||||
state.photoPermission = permission
|
||||
store.materialLibraries[key] = state
|
||||
if !permission.canSave { pauseStoredBatch(reason: .permissionDenied) }
|
||||
}
|
||||
|
||||
/// 接收明确本地执行回执;旧批次、其他订单、暂停状态和重复保存均被忽略。
|
||||
func receive(_ event: DroneMaterialTransferEvent, materialID: String, batchID: UUID) {
|
||||
guard var state = library, let batch = state.batch, batch.id == batchID,
|
||||
!batch.isPaused, batch.itemIDs.contains(materialID), photoPermission.canSave else { return }
|
||||
mutateMaterials(in: &state) { material in
|
||||
guard material.id == materialID, material.uploadState == .ready else { return }
|
||||
switch (event, material.downloadState) {
|
||||
case (.progress(let value), .downloading(let previous)):
|
||||
guard value.isFinite else { return }
|
||||
material.downloadState = .downloading(progress: max(previous, min(1, max(0, value))))
|
||||
case (.downloadCompleted, .downloading): material.downloadState = .awaitingSave
|
||||
case (.downloadFailed(let message), .downloading): material.downloadState = .downloadFailed(message: message)
|
||||
case (.saveStarted, .awaitingSave): material.downloadState = .saving
|
||||
case (.saveFailed(let message), .saving): material.downloadState = .saveFailed(message: message)
|
||||
case (.saveSucceeded, .saving): material.downloadState = .completed(isSimulation: true)
|
||||
default: break
|
||||
}
|
||||
}
|
||||
store.materialLibraries[key] = state
|
||||
selectedIDs = selectedIDs.filter { material(id: $0)?.downloadState.isCompleted == false }
|
||||
}
|
||||
|
||||
private func pauseStoredBatch(reason: DroneMaterialPauseReason) {
|
||||
guard var state = store.materialLibraries[key], let batch = state.batch,
|
||||
batch.itemIDs.contains(where: { id in
|
||||
state.records.flatMap(\.materials).contains { $0.id == id && !$0.downloadState.isCompleted && !$0.downloadState.isFailed }
|
||||
}) else { return }
|
||||
let ids = Set(batch.itemIDs)
|
||||
mutateMaterials(in: &state) { material in
|
||||
guard ids.contains(material.id) else { return }
|
||||
switch material.downloadState {
|
||||
case .downloading: material.downloadState = .paused
|
||||
case .saving: material.downloadState = .awaitingSave
|
||||
default: break
|
||||
}
|
||||
}
|
||||
state.batch = DroneMaterialDownloadBatch(id: UUID(), itemIDs: batch.itemIDs, isPaused: true, pauseReason: reason)
|
||||
store.materialLibraries[key] = state
|
||||
}
|
||||
|
||||
private func prepareAttempts(in state: inout DroneMaterialLibraryState, ids: Set<String>, retryFailures: Bool) {
|
||||
mutateMaterials(in: &state) { material in
|
||||
guard ids.contains(material.id), material.uploadState == .ready else { return }
|
||||
switch material.downloadState {
|
||||
case .available, .paused: material.downloadState = .downloading(progress: 0)
|
||||
case .downloadFailed where retryFailures: material.downloadState = .downloading(progress: 0)
|
||||
case .saveFailed where retryFailures: material.downloadState = .awaitingSave
|
||||
default: break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func restrictBatchToEntryScope(in state: inout DroneMaterialLibraryState) {
|
||||
guard let pointID, let batch = state.batch else { return }
|
||||
let scopeIDs = Set(state.records.filter { $0.pointID == pointID }.flatMap(\.materials).map(\.id))
|
||||
guard !Set(batch.itemIDs).isSubset(of: scopeIDs) else { return }
|
||||
let originalIDs = Set(batch.itemIDs)
|
||||
mutateMaterials(in: &state) { material in
|
||||
guard originalIDs.contains(material.id) else { return }
|
||||
switch material.downloadState {
|
||||
case .downloading: material.downloadState = .paused
|
||||
case .saving: material.downloadState = .awaitingSave
|
||||
default: break
|
||||
}
|
||||
}
|
||||
let scopedIDs = batch.itemIDs.filter { scopeIDs.contains($0) }
|
||||
state.batch = scopedIDs.isEmpty ? nil : DroneMaterialDownloadBatch(
|
||||
id: UUID(), itemIDs: scopedIDs, isPaused: true, pauseReason: .leavingPage
|
||||
)
|
||||
}
|
||||
|
||||
private func mutateMaterials(in state: inout DroneMaterialLibraryState, update: (inout DroneMaterial) -> Void) {
|
||||
for recordIndex in state.records.indices {
|
||||
for materialIndex in state.records[recordIndex].materials.indices {
|
||||
update(&state.records[recordIndex].materials[materialIndex])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func demoRecord(order: DroneShootingOrder, sequence: Int, points: [DroneShootingPoint], session: DroneShootingSession?) -> DroneMaterialRecord {
|
||||
let latestSession = sequence == order.successfulShootingCount && session?.result == .succeeded ? session : nil
|
||||
let point = latestSession?.point ?? (points.isEmpty ? nil : points[(sequence - 1) % points.count])
|
||||
let pointID = point?.id ?? "demo-point-1"
|
||||
let pointName = point?.name ?? "三皇寨"
|
||||
let uploadState: DroneMaterialUploadState
|
||||
switch order.materialState {
|
||||
case .none, .uploading: uploadState = .uploading
|
||||
case .partiallyReady: uploadState = sequence == order.successfulShootingCount ? .uploading : .ready
|
||||
case .ready: uploadState = .ready
|
||||
case .failed: uploadState = sequence == 1 ? .failed : .ready
|
||||
}
|
||||
let id = "\(order.id)-record-\(sequence)"
|
||||
return DroneMaterialRecord(id: id, pointID: pointID, pointName: pointName,
|
||||
routeName: latestSession?.route.name ?? (sequence % 2 == 0 ? "云宫环绕" : "经典航线"),
|
||||
capturedAt: Date(timeIntervalSince1970: 1_792_723_000 + Double(sequence) * 1_500),
|
||||
capturedAtText: "10-23 \(String(format: "%02d:%02d", 13 + sequence / 3, (sequence * 17) % 60))",
|
||||
sequenceNumber: sequence,
|
||||
materials: [
|
||||
DroneMaterial(id: "\(id)-photo", title: "素材\(String(format: "%02d", sequence * 2 - 1))",
|
||||
previewAssetName: sequence % 2 == 0 ? "drone_demo_pagoda" : "drone_demo_tourists", uploadState: uploadState),
|
||||
DroneMaterial(id: "\(id)-video", title: "素材\(String(format: "%02d", sequence * 2))", kind: .video,
|
||||
previewAssetName: "drone_demo_mountain",
|
||||
previewURL: Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4"), durationText: "00:03",
|
||||
uploadState: order.materialState == .partiallyReady && uploadState == .uploading ? .ready : uploadState)
|
||||
])
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// 单次显式演示事件推进一个文件的一个阶段,ViewModel 不持有计时器。
|
||||
func advanceDemoDownload() {
|
||||
guard let batch, !batch.isPaused,
|
||||
let material = batchMaterials.first(where: { $0.downloadState.isRunning }) else { return }
|
||||
let event: DroneMaterialTransferEvent
|
||||
switch material.downloadState {
|
||||
case .downloading: event = .downloadCompleted
|
||||
case .awaitingSave: event = .saveStarted
|
||||
case .saving: event = .saveSucceeded
|
||||
default: return
|
||||
}
|
||||
receive(event, materialID: material.id, batchID: batch.id)
|
||||
}
|
||||
|
||||
/// 替换当前订单的本地素材验收场景,保留拍摄次数、任务与游客交付信息。
|
||||
func applyScenario(_ scenario: DroneMaterialsScenario) {
|
||||
guard let order else { return }
|
||||
var state = DroneMaterialLibraryState(records: [], sourceShootingCount: order.successfulShootingCount)
|
||||
let points = store.shootingPreparations[key]?.points ?? []
|
||||
let session = store.shootingSession(orderID: orderID)
|
||||
if order.successfulShootingCount > 0 {
|
||||
state.records = (1...order.successfulShootingCount).map { Self.demoRecord(order: order, sequence: $0, points: points, session: session) }
|
||||
}
|
||||
mutateMaterials(in: &state) { $0.uploadState = .ready; $0.downloadState = .available }
|
||||
switch scenario {
|
||||
case .empty: state.records = []
|
||||
case .loading: state.listState = .loading
|
||||
case .loadFailure: state.listState = .failed(message: "素材列表加载失败,请刷新重试。")
|
||||
case .uploading: mutateMaterials(in: &state) { $0.uploadState = .uploading }
|
||||
case .mixed:
|
||||
var index = 0
|
||||
mutateMaterials(in: &state) { material in
|
||||
material.uploadState = index == 1 ? .failed : (index == 3 ? .uploading : .ready)
|
||||
index += 1
|
||||
}
|
||||
case .permissionDenied: state.photoPermission = .denied
|
||||
case .downloading, .paused, .partialFailure, .saveFailure, .completed:
|
||||
let ids = state.records.filter { pointID == nil || $0.pointID == pointID }.flatMap(\.materials).map(\.id)
|
||||
if !ids.isEmpty {
|
||||
state.batch = DroneMaterialDownloadBatch(id: UUID(), itemIDs: ids, isPaused: scenario == .paused,
|
||||
pauseReason: scenario == .paused ? .background : nil)
|
||||
}
|
||||
var index = 0
|
||||
mutateMaterials(in: &state) { material in
|
||||
guard ids.contains(material.id) else { return }
|
||||
switch scenario {
|
||||
case .paused: material.downloadState = index == 0 ? .completed(isSimulation: true) : .paused
|
||||
case .partialFailure: material.downloadState = index == 0 ? .completed(isSimulation: true) : .downloadFailed(message: "演示连接中断")
|
||||
case .saveFailure: material.downloadState = index == 0 ? .completed(isSimulation: true) : .saveFailed(message: "演示相册写入失败")
|
||||
case .completed: material.downloadState = .completed(isSimulation: true)
|
||||
default: material.downloadState = index == 0 ? .completed(isSimulation: true) : .downloading(progress: 0.3)
|
||||
}
|
||||
index += 1
|
||||
}
|
||||
case .ready: break
|
||||
}
|
||||
store.materialLibraries[key] = state
|
||||
selectedIDs = []
|
||||
}
|
||||
#endif
|
||||
}
|
||||
Binary file not shown.
@@ -6,7 +6,7 @@ import UIKit
|
||||
enum DroneDockPreview {
|
||||
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview"]
|
||||
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview", "--dock-ui-materials-preview"]
|
||||
guard arguments.contains(where: { entryFlags.contains($0) }) else { return nil }
|
||||
let store = DroneDockDemoStore()
|
||||
if let argument = arguments.first(where: { $0.hasPrefix("--dock-ui-scenario=") }),
|
||||
@@ -48,6 +48,17 @@ enum DroneDockPreview {
|
||||
}
|
||||
navigation.setViewControllers(controllers, animated: false)
|
||||
}
|
||||
if arguments.contains("--dock-ui-materials-preview"), let order = store.orders.first(where: { $0.successfulShootingCount > 0 }) {
|
||||
let pointArgument = arguments.first { $0.hasPrefix("--dock-materials-point=") }
|
||||
let pointID = pointArgument.map { String($0.dropFirst("--dock-materials-point=".count)) }
|
||||
let materialsViewModel = DroneMaterialsViewModel(store: store, orderID: order.id, pointID: pointID)
|
||||
let scenarioArgument = arguments.first { $0.hasPrefix("--dock-materials-scenario=") }
|
||||
let scenario = scenarioArgument.flatMap { DroneMaterialsScenario(rawValue: String($0.dropFirst("--dock-materials-scenario=".count))) } ?? .mixed
|
||||
materialsViewModel.applyScenario(scenario)
|
||||
let materials = DroneMaterialsViewController(viewModel: materialsViewModel)
|
||||
materials.delegate = workbench
|
||||
navigation.setViewControllers([workbench, materials], animated: false)
|
||||
}
|
||||
return navigation
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,7 +209,7 @@ final class DroneDockWorkbenchViewController: BaseViewController {
|
||||
navigationController?.pushViewController(controller, animated: true)
|
||||
}
|
||||
|
||||
/// 拍摄进入本地准备/原任务,其他下级业务暂保留入口提示。
|
||||
/// 拍摄和素材进入对应本地页面,成片交付暂保留入口提示。
|
||||
private enum OrderEntry { case shooting, materials, delivery }
|
||||
|
||||
private func showOrderEntry(id: String, action: OrderEntry) {
|
||||
@@ -225,8 +225,8 @@ final class DroneDockWorkbenchViewController: BaseViewController {
|
||||
openShootingOrder(id: order.id, from: presenter ?? self)
|
||||
return
|
||||
case .materials:
|
||||
title = "查看素材"
|
||||
detail = order.materialState.title
|
||||
openMaterials(orderID: order.id, from: presenter ?? self)
|
||||
return
|
||||
case .delivery:
|
||||
title = "交付成片"
|
||||
detail = "\(order.deliveredVideoCount) 个已交付视频"
|
||||
@@ -258,6 +258,15 @@ final class DroneDockWorkbenchViewController: BaseViewController {
|
||||
presenter.navigationController?.pushViewController(controller, animated: true)
|
||||
}
|
||||
|
||||
private func openMaterials(orderID: String, pointID: String? = nil, from presenter: UIViewController) {
|
||||
guard viewModel.store.shootingOrder(id: orderID) != nil else { return }
|
||||
let controller = DroneMaterialsViewController(
|
||||
viewModel: DroneMaterialsViewModel(store: viewModel.store, orderID: orderID, pointID: pointID)
|
||||
)
|
||||
controller.delegate = self
|
||||
presenter.navigationController?.pushViewController(controller, animated: true)
|
||||
}
|
||||
|
||||
@objc private func receiptTapped() {
|
||||
showAlert(title: "收款码", message: "套餐收款页面将在后续搭建,当前不会创建订单或发起收款。")
|
||||
}
|
||||
@@ -312,7 +321,21 @@ extension DroneDockWorkbenchViewController: DroneShootingTaskViewControllerDeleg
|
||||
|
||||
func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestMaterialsFor order: DroneShootingOrder) {
|
||||
guard let order = viewModel.store.shootingOrder(id: order.id) else { return }
|
||||
showPreviewEntry(order: order, action: .materials, presenter: controller)
|
||||
let pointID = viewModel.store.shootingSession(orderID: order.id)?.point.id
|
||||
openMaterials(orderID: order.id, pointID: pointID, from: controller)
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockWorkbenchViewController: DroneMaterialsViewControllerDelegate {
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestPreview material: DroneMaterial) {
|
||||
guard material.canPreview else { return }
|
||||
let preview = DroneMaterialPreviewViewController(items: controller.viewModel.previewMaterials, initialMaterialID: material.id)
|
||||
controller.present(preview, animated: true)
|
||||
}
|
||||
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord) {
|
||||
guard let order = viewModel.store.shootingOrder(id: controller.viewModel.orderID) else { return }
|
||||
showPreviewEntry(order: order, action: .delivery, presenter: controller)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 素材库的订单摘要,保留拍摄履约与素材处理相互独立的表达。
|
||||
@MainActor
|
||||
final class DroneMaterialOrderCell: UICollectionViewCell {
|
||||
private let customerLabel = DroneDockStyle.label(size: 18, weight: .semibold)
|
||||
private let statusLabel = DroneDockStatusLabel()
|
||||
private let numberLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let countLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
let titleRow = UIStackView(arrangedSubviews: [customerLabel, statusLabel, UIView()])
|
||||
titleRow.axis = .horizontal
|
||||
titleRow.alignment = .center
|
||||
titleRow.spacing = 9
|
||||
let stack = UIStackView(arrangedSubviews: [titleRow, numberLabel, countLabel])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 9
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.top.equalToSuperview().offset(16)
|
||||
make.bottom.equalToSuperview().inset(18)
|
||||
}
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 显示本次入口订单的脱敏信息与拍摄次数。
|
||||
func apply(order: DroneShootingOrder?) {
|
||||
guard let order else {
|
||||
customerLabel.text = "订单信息暂不可用"
|
||||
statusLabel.isHidden = true
|
||||
numberLabel.text = "请返回订单列表重新进入"
|
||||
countLabel.text = nil
|
||||
accessibilityLabel = "订单信息暂不可用,请返回订单列表重新进入"
|
||||
return
|
||||
}
|
||||
customerLabel.text = order.customerName
|
||||
statusLabel.isHidden = false
|
||||
statusLabel.apply(title: order.fulfillmentState.title, tone: order.fulfillmentState.tone)
|
||||
numberLabel.text = order.orderNumber
|
||||
countLabel.text = "含\(order.totalShootingCount)次拍摄 · 已拍摄\(order.successfulShootingCount)次 · 剩余\(order.remainingShootingCount)次"
|
||||
accessibilityLabel = [order.customerName, order.fulfillmentState.title, order.orderNumber, countLabel.text].compactMap { $0 }.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
/// 可横向浏览的点位筛选标签,下载期间保留现有筛选并禁用交互。
|
||||
@MainActor
|
||||
final class DroneMaterialFilterCell: UICollectionViewCell {
|
||||
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
contentView.layer.cornerRadius = 7
|
||||
contentView.layer.cornerCurve = .continuous
|
||||
contentView.layer.borderWidth = 1
|
||||
titleLabel.textAlignment = .center
|
||||
contentView.addSubview(titleLabel)
|
||||
titleLabel.snp.makeConstraints { make in make.edges.equalToSuperview().inset(5) }
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 映射筛选名称、选中态与交互许可。
|
||||
func apply(title: String, id: String?, selected: Bool, locked: Bool) {
|
||||
titleLabel.text = title
|
||||
titleLabel.textColor = selected ? DroneDockStyle.primary : UIColor(hex: 0x677183)
|
||||
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.09) : .white
|
||||
contentView.layer.borderColor = (selected ? UIColor.clear : DroneDockStyle.border).cgColor
|
||||
contentView.alpha = locked ? 0.5 : 1
|
||||
accessibilityIdentifier = "drone.materials.filter.\(id ?? "all")"
|
||||
accessibilityLabel = title
|
||||
var traits: UIAccessibilityTraits = .button
|
||||
if selected { traits.insert(.selected) }
|
||||
if locked { traits.insert(.notEnabled) }
|
||||
accessibilityTraits = traits
|
||||
}
|
||||
}
|
||||
|
||||
/// 点位限定入口的只读提示,不将当前任务点位伪装成可切换筛选。
|
||||
@MainActor
|
||||
final class DroneMaterialPointContextCell: UICollectionViewCell {
|
||||
private let icon = UIImageView(image: UIImage(systemName: "mappin.circle.fill"))
|
||||
private let titleLabel = DroneDockStyle.label(size: 14, weight: .semibold)
|
||||
private let detailLabel = DroneDockStyle.label("仅显示当前打卡点素材", size: 11, color: DroneDockStyle.secondary)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
icon.tintColor = DroneDockStyle.primary
|
||||
[icon, titleLabel, detailLabel].forEach(contentView.addSubview)
|
||||
icon.snp.makeConstraints { make in make.leading.centerY.equalToSuperview(); make.size.equalTo(16) }
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.leading.equalTo(icon.snp.trailing).offset(6)
|
||||
make.centerY.equalToSuperview()
|
||||
make.trailing.lessThanOrEqualTo(detailLabel.snp.leading).offset(-8)
|
||||
}
|
||||
detailLabel.snp.makeConstraints { make in make.trailing.centerY.equalToSuperview() }
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 展示限定点位的名称。
|
||||
func apply(title: String) {
|
||||
titleLabel.text = title
|
||||
accessibilityLabel = "\(title),仅显示当前打卡点素材"
|
||||
}
|
||||
}
|
||||
|
||||
/// 素材分组上方的数量与全选控制,数量由当前可见记录提供。
|
||||
@MainActor
|
||||
final class DroneMaterialSelectionCell: UICollectionViewCell {
|
||||
/// 点击后由控制器调用 ViewModel 的全选操作。
|
||||
var onSelectAllTap: (() -> Void)?
|
||||
private let countLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let selectAllButton = UIButton(type: .system)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
selectAllButton.titleLabel?.font = .systemFont(ofSize: 12)
|
||||
selectAllButton.tintColor = DroneDockStyle.primary
|
||||
selectAllButton.accessibilityIdentifier = "drone.materials.selectAll"
|
||||
selectAllButton.addTarget(self, action: #selector(selectAllTapped), for: .touchUpInside)
|
||||
let divider = UIView()
|
||||
divider.backgroundColor = DroneDockStyle.border
|
||||
[countLabel, selectAllButton, divider].forEach(contentView.addSubview)
|
||||
countLabel.snp.makeConstraints { make in make.leading.centerY.equalToSuperview().offset(-2) }
|
||||
selectAllButton.snp.makeConstraints { make in
|
||||
make.trailing.equalToSuperview()
|
||||
make.centerY.equalTo(countLabel)
|
||||
make.leading.greaterThanOrEqualTo(countLabel.snp.trailing).offset(8)
|
||||
make.height.equalTo(44)
|
||||
}
|
||||
divider.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 全选只面向当前可下载项,上传中与失败素材不会计入。
|
||||
func apply(recordCount: Int, allSelected: Bool, enabled: Bool) {
|
||||
countLabel.text = "\(recordCount)次拍摄 · 最新在前"
|
||||
var config = UIButton.Configuration.plain()
|
||||
config.title = "全选可下载"
|
||||
config.image = UIImage(systemName: allSelected ? "checkmark.circle.fill" : "circle")
|
||||
config.imagePadding = 6
|
||||
config.contentInsets = .zero
|
||||
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 15)
|
||||
selectAllButton.configuration = config
|
||||
selectAllButton.isEnabled = enabled
|
||||
selectAllButton.accessibilityLabel = "全选可下载"
|
||||
selectAllButton.accessibilityTraits = allSelected ? [.button, .selected] : .button
|
||||
}
|
||||
|
||||
@objc private func selectAllTapped() { onSelectAllTap?() }
|
||||
}
|
||||
|
||||
/// 每条拍摄记录的点位、航线、时间与独立的交付入口。
|
||||
@MainActor
|
||||
final class DroneMaterialRecordHeaderView: UICollectionReusableView {
|
||||
/// 交付入口目前只向上层请求展示占位说明。
|
||||
var onDeliveryTap: (() -> Void)?
|
||||
private let titleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
|
||||
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let deliveryButton = UIButton(type: .system)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
deliveryButton.titleLabel?.font = .systemFont(ofSize: 12)
|
||||
var config = UIButton.Configuration.plain()
|
||||
config.title = "交付成片"
|
||||
config.image = UIImage(systemName: "play.rectangle")
|
||||
config.imagePadding = 5
|
||||
config.contentInsets = .zero
|
||||
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13)
|
||||
deliveryButton.configuration = config
|
||||
deliveryButton.tintColor = DroneDockStyle.primary
|
||||
deliveryButton.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside)
|
||||
[titleLabel, detailLabel, deliveryButton].forEach(addSubview)
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.leading.equalToSuperview()
|
||||
make.top.equalToSuperview().offset(20)
|
||||
make.trailing.lessThanOrEqualTo(deliveryButton.snp.leading).offset(-12)
|
||||
}
|
||||
deliveryButton.snp.makeConstraints { make in
|
||||
make.trailing.equalToSuperview()
|
||||
make.centerY.equalTo(titleLabel)
|
||||
make.height.equalTo(40)
|
||||
}
|
||||
detailLabel.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.top.equalTo(titleLabel.snp.bottom).offset(9)
|
||||
make.bottom.lessThanOrEqualToSuperview().inset(10)
|
||||
}
|
||||
titleLabel.accessibilityTraits = .header
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 使用完整拍摄记录身份绑定交付入口,避免仅按同名点位匹配。
|
||||
func apply(record: DroneMaterialRecord) {
|
||||
titleLabel.text = record.pointName
|
||||
detailLabel.text = record.summary
|
||||
deliveryButton.accessibilityLabel = "\(record.pointName)交付成片,记录\(record.sequenceNumber)"
|
||||
deliveryButton.accessibilityIdentifier = "drone.materials.delivery.\(record.id)"
|
||||
}
|
||||
|
||||
@objc private func deliveryTapped() { onDeliveryTap?() }
|
||||
}
|
||||
|
||||
/// 两列素材网格单元;缩略图预览与右上角多选按钮互不替代。
|
||||
@MainActor
|
||||
final class DroneMaterialCell: UICollectionViewCell {
|
||||
/// 点击就绪缩略图时请求预览。
|
||||
var onPreviewTap: (() -> Void)?
|
||||
/// 点击右上角选择控件时仅改变选择。
|
||||
var onSelectionTap: (() -> Void)?
|
||||
private let thumbnail = UIImageView()
|
||||
private let previewButton = UIButton(type: .custom)
|
||||
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)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
thumbnail.contentMode = .scaleAspectFill
|
||||
thumbnail.clipsToBounds = true
|
||||
thumbnail.layer.cornerRadius = 6
|
||||
thumbnail.layer.cornerCurve = .continuous
|
||||
thumbnail.backgroundColor = UIColor(hex: 0xE9EDF5)
|
||||
thumbnail.layer.borderWidth = 2
|
||||
placeholderIcon.contentMode = .scaleAspectFit
|
||||
placeholderIcon.tintColor = UIColor(hex: 0x9CA6B6)
|
||||
videoBadge.font = .systemFont(ofSize: 10, weight: .medium)
|
||||
videoBadge.textColor = .white
|
||||
videoBadge.backgroundColor = UIColor.black.withAlphaComponent(0.48)
|
||||
videoBadge.layer.cornerRadius = 3
|
||||
videoBadge.clipsToBounds = true
|
||||
videoBadge.textAlignment = .center
|
||||
videoBadge.text = "视频"
|
||||
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)
|
||||
thumbnail.snp.makeConstraints { make in
|
||||
make.leading.trailing.top.equalToSuperview()
|
||||
make.height.equalTo(thumbnail.snp.width).multipliedBy(0.57)
|
||||
}
|
||||
previewButton.snp.makeConstraints { make in make.edges.equalTo(thumbnail) }
|
||||
placeholderIcon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(29) }
|
||||
videoBadge.snp.makeConstraints { make in
|
||||
make.leading.equalTo(thumbnail).offset(6)
|
||||
make.bottom.equalTo(thumbnail).inset(6)
|
||||
make.width.equalTo(32)
|
||||
make.height.equalTo(18)
|
||||
}
|
||||
selectionButton.snp.makeConstraints { make in
|
||||
make.top.trailing.equalTo(thumbnail)
|
||||
make.size.equalTo(44)
|
||||
}
|
||||
nameLabel.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.bottom.lessThanOrEqualToSuperview().inset(5)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 上传未就绪时显示占位且禁选,演示完成也不会标记为本机已保存。
|
||||
func apply(material: DroneMaterial, selected: Bool, selectionEnabled: Bool, completed: Bool) {
|
||||
nameLabel.text = material.title
|
||||
statusLabel.text = material.statusTitle
|
||||
statusLabel.textColor = DroneDockStyle.color(for: material.statusTone)
|
||||
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")
|
||||
videoBadge.isHidden = material.kind != .video || !material.canPreview
|
||||
previewButton.isEnabled = material.canPreview
|
||||
previewButton.accessibilityIdentifier = "drone.materials.preview.\(material.id)"
|
||||
previewButton.accessibilityLabel = "预览\(material.title)"
|
||||
selectionButton.isHidden = material.uploadState != .ready
|
||||
selectionButton.isEnabled = selectionEnabled && !completed
|
||||
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.imageView?.layer.shadowColor = UIColor.black.cgColor
|
||||
selectionButton.imageView?.layer.shadowOpacity = 0.22
|
||||
selectionButton.imageView?.layer.shadowRadius = 2
|
||||
selectionButton.imageView?.layer.shadowOffset = .zero
|
||||
}
|
||||
|
||||
@objc private func previewTapped() { onPreviewTap?() }
|
||||
@objc private func selectionTapped() { onSelectionTap?() }
|
||||
}
|
||||
|
||||
/// 分组之间轻量的分隔线。
|
||||
@MainActor
|
||||
final class DroneMaterialSeparatorView: UICollectionReusableView {
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
let line = UIView()
|
||||
line.backgroundColor = DroneDockStyle.border
|
||||
addSubview(line)
|
||||
line.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
}
|
||||
|
||||
/// 列表加载、为空与失败时的就地说明,保留顶部订单与刷新入口。
|
||||
@MainActor
|
||||
final class DroneMaterialMessageCell: UICollectionViewCell {
|
||||
private let icon = UIImageView()
|
||||
private let titleLabel = DroneDockStyle.label(size: 16, weight: .medium)
|
||||
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
icon.tintColor = DroneDockStyle.secondary
|
||||
icon.contentMode = .scaleAspectFit
|
||||
titleLabel.textAlignment = .center
|
||||
detailLabel.textAlignment = .center
|
||||
detailLabel.numberOfLines = 0
|
||||
let stack = UIStackView(arrangedSubviews: [icon, titleLabel, detailLabel])
|
||||
stack.axis = .vertical
|
||||
stack.alignment = .center
|
||||
stack.spacing = 13
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in make.centerY.equalToSuperview().offset(-12); make.leading.trailing.equalToSuperview().inset(12) }
|
||||
icon.snp.makeConstraints { make in make.size.equalTo(38) }
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 通过明确文案区分上传等待、空记录与加载异常。
|
||||
func apply(title: String, detail: String, symbol: String) {
|
||||
titleLabel.text = title
|
||||
detailLabel.text = detail
|
||||
icon.image = UIImage(systemName: symbol)
|
||||
accessibilityLabel = "\(title),\(detail)"
|
||||
}
|
||||
}
|
||||
|
||||
/// 固定底栏以同一组件呈现选择、批次进度、暂停与演示结果。
|
||||
@MainActor
|
||||
final class DroneMaterialsFooterView: UIView {
|
||||
/// 执行当前状态对应的主要操作。
|
||||
var onPrimaryTap: (() -> Void)?
|
||||
/// 返回选择状态或请求预留的交付入口。
|
||||
var onSecondaryTap: (() -> Void)?
|
||||
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
|
||||
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let progressView = UIProgressView(progressViewStyle: .default)
|
||||
private let primaryButton = UIButton(type: .system)
|
||||
private let secondaryButton = UIButton(type: .system)
|
||||
private let stack = UIStackView()
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
backgroundColor = .white
|
||||
let divider = UIView()
|
||||
divider.backgroundColor = DroneDockStyle.border
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 10
|
||||
titleLabel.numberOfLines = 2
|
||||
detailLabel.numberOfLines = 2
|
||||
progressView.progressTintColor = DroneDockStyle.primary
|
||||
progressView.trackTintColor = UIColor(hex: 0xE8EDF7)
|
||||
progressView.accessibilityLabel = "本次演示下载完成项数"
|
||||
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
|
||||
primaryButton.layer.cornerRadius = 7
|
||||
primaryButton.layer.cornerCurve = .continuous
|
||||
primaryButton.tintColor = .white
|
||||
primaryButton.setTitleColor(.white, for: .normal)
|
||||
primaryButton.setTitleColor(UIColor.white.withAlphaComponent(0.85), for: .disabled)
|
||||
secondaryButton.titleLabel?.font = .systemFont(ofSize: 12)
|
||||
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)
|
||||
addSubview(divider)
|
||||
addSubview(stack)
|
||||
divider.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
|
||||
stack.snp.makeConstraints { make in
|
||||
make.top.equalToSuperview().offset(12)
|
||||
make.leading.trailing.equalToSuperview().inset(16)
|
||||
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) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 只接受显示值,按钮语义和下载状态由控制器及 ViewModel 决定。
|
||||
func apply(title: String, detail: String, primaryTitle: String, primarySymbol: String,
|
||||
enabled: Bool, identifier: String, progress: Double?, secondaryTitle: String? = nil,
|
||||
tone: DroneDockStatusTone = .gray) {
|
||||
titleLabel.text = title
|
||||
titleLabel.textColor = tone == .gray ? DroneDockStyle.text : DroneDockStyle.color(for: tone)
|
||||
detailLabel.text = detail
|
||||
detailLabel.isHidden = detail.isEmpty
|
||||
progressView.isHidden = progress == nil
|
||||
progressView.setProgress(Float(progress ?? 0), animated: true)
|
||||
var config = UIButton.Configuration.plain()
|
||||
config.title = primaryTitle
|
||||
config.image = UIImage(systemName: primarySymbol)
|
||||
config.imagePadding = 7
|
||||
config.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)
|
||||
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
|
||||
primaryButton.configuration = config
|
||||
primaryButton.isEnabled = enabled
|
||||
primaryButton.backgroundColor = enabled ? DroneDockStyle.primary : UIColor(hex: 0xCEDBFC)
|
||||
primaryButton.accessibilityIdentifier = identifier
|
||||
secondaryButton.setTitle(secondaryTitle, for: .normal)
|
||||
secondaryButton.isHidden = secondaryTitle == nil
|
||||
secondaryButton.accessibilityIdentifier = "drone.materials.continueSelecting"
|
||||
}
|
||||
|
||||
@objc private func primaryTapped() { onPrimaryTap?() }
|
||||
@objc private func secondaryTapped() { onSecondaryTap?() }
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
|
||||
/// 本地 UI 演示的下载回执驱动,不连接网络、不写文件或系统相册。
|
||||
@MainActor
|
||||
final class DroneMaterialDemoTransferDriver {
|
||||
private var task: Task<Void, Never>?
|
||||
private var runningBatchID: UUID?
|
||||
|
||||
/// 推进当前演示批次;相同批次不会重复启动,实际结果由 ViewModel 校验。
|
||||
func start(viewModel: DroneMaterialsViewModel, onTransferUpdate: @escaping () -> Void) {
|
||||
guard let batch = viewModel.batch, !batch.isPaused else { return }
|
||||
guard runningBatchID != batch.id || task == nil else { return }
|
||||
stop()
|
||||
let batchID = batch.id
|
||||
runningBatchID = batchID
|
||||
task = Task { @MainActor [weak self, weak viewModel] in
|
||||
guard let self, let viewModel else { return }
|
||||
defer {
|
||||
if self.runningBatchID == batchID {
|
||||
self.task = nil
|
||||
self.runningBatchID = nil
|
||||
}
|
||||
}
|
||||
for materialID in batch.itemIDs {
|
||||
guard self.isCurrent(viewModel, batchID: batchID),
|
||||
let material = viewModel.material(id: materialID) else { return }
|
||||
switch material.downloadState {
|
||||
case .downloading, .paused, .available:
|
||||
for progress in [0.2, 0.45, 0.7, 1.0] {
|
||||
guard await self.wait(viewModel, batchID: batchID) else { return }
|
||||
viewModel.receive(.progress(progress), materialID: materialID, batchID: batchID)
|
||||
onTransferUpdate()
|
||||
}
|
||||
viewModel.receive(.downloadCompleted, materialID: materialID, batchID: batchID)
|
||||
onTransferUpdate()
|
||||
case .awaitingSave: break
|
||||
default: continue
|
||||
}
|
||||
guard self.isCurrent(viewModel, batchID: batchID) else { return }
|
||||
viewModel.receive(.saveStarted, materialID: materialID, batchID: batchID)
|
||||
onTransferUpdate()
|
||||
guard await self.wait(viewModel, batchID: batchID) else { return }
|
||||
viewModel.receive(.saveSucceeded, materialID: materialID, batchID: batchID)
|
||||
onTransferUpdate()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 取消演示回执;调用方再通知 ViewModel 暂停,返回前台不会自动启动。
|
||||
func stop() {
|
||||
task?.cancel()
|
||||
task = nil
|
||||
runningBatchID = nil
|
||||
}
|
||||
|
||||
private func isCurrent(_ viewModel: DroneMaterialsViewModel, batchID: UUID) -> Bool {
|
||||
!Task.isCancelled && runningBatchID == batchID
|
||||
&& viewModel.batch?.id == batchID && viewModel.batch?.isPaused == false
|
||||
}
|
||||
|
||||
private func wait(_ viewModel: DroneMaterialsViewModel, batchID: UUID) async -> Bool {
|
||||
do { try await Task.sleep(nanoseconds: 180_000_000) } catch { return false }
|
||||
return isCurrent(viewModel, batchID: batchID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
import AVFoundation
|
||||
import AVKit
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 订单素材的本地只读预览页;分页与缩放不会改变素材选择、下载或拍摄任务。
|
||||
@MainActor
|
||||
final class DroneMaterialPreviewViewController: UIViewController {
|
||||
/// 本地预览列表只有一个媒体分区。
|
||||
private enum Section {
|
||||
case materials
|
||||
}
|
||||
|
||||
private let items: [DroneMaterial]
|
||||
private var currentIndex: Int
|
||||
private var lastCollectionSize = CGSize.zero
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, String>!
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeCollectionLayout())
|
||||
private let closeButton = UIButton(type: .system)
|
||||
private let counterLabel = UILabel()
|
||||
private let emptyLabel = UILabel()
|
||||
private let instructionLabel = UILabel()
|
||||
private weak var videoController: AVPlayerViewController?
|
||||
private var playbackTask: Task<Void, Never>?
|
||||
|
||||
/// 以当前素材为起点预览已就绪素材;未就绪项不会被带入预览列表。
|
||||
init(items: [DroneMaterial], initialMaterialID: String) {
|
||||
var identifiers = Set<String>()
|
||||
self.items = items.filter { $0.canPreview && identifiers.insert($0.id).inserted }
|
||||
currentIndex = self.items.firstIndex { $0.id == initialMaterialID } ?? 0
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .fullScreen
|
||||
modalTransitionStyle = .crossDissolve
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
setupUI()
|
||||
setupConstraints()
|
||||
setupDataSource()
|
||||
applySnapshot()
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
guard collectionView.bounds.width > 0, collectionView.bounds.size != lastCollectionSize else { return }
|
||||
lastCollectionSize = collectionView.bounds.size
|
||||
collectionView.collectionViewLayout.invalidateLayout()
|
||||
collectionView.setContentOffset(CGPoint(x: CGFloat(currentIndex) * collectionView.bounds.width, y: 0), animated: false)
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
if isBeingDismissed || navigationController?.isBeingDismissed == true {
|
||||
playbackTask?.cancel()
|
||||
videoController?.player?.pause()
|
||||
}
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
view.backgroundColor = UIColor(hex: 0x141820)
|
||||
view.accessibilityIdentifier = "drone.material.preview"
|
||||
collectionView.backgroundColor = .clear
|
||||
collectionView.isPagingEnabled = true
|
||||
collectionView.showsHorizontalScrollIndicator = false
|
||||
collectionView.alwaysBounceHorizontal = items.count > 1
|
||||
collectionView.contentInsetAdjustmentBehavior = .never
|
||||
collectionView.accessibilityIdentifier = "drone.material.preview.pages"
|
||||
collectionView.delegate = self
|
||||
collectionView.register(DroneMaterialPreviewCell.self, forCellWithReuseIdentifier: DroneMaterialPreviewCell.reuseIdentifier)
|
||||
|
||||
closeButton.setImage(UIImage(systemName: "xmark", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular)), for: .normal)
|
||||
closeButton.tintColor = .white
|
||||
closeButton.accessibilityLabel = "关闭素材预览"
|
||||
closeButton.accessibilityIdentifier = "drone.material.preview.close"
|
||||
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
||||
|
||||
counterLabel.textColor = UIColor.white.withAlphaComponent(0.75)
|
||||
counterLabel.font = .monospacedDigitSystemFont(ofSize: 13, weight: .medium)
|
||||
counterLabel.textAlignment = .center
|
||||
counterLabel.accessibilityIdentifier = "drone.material.preview.counter"
|
||||
updateCounter()
|
||||
|
||||
emptyLabel.text = "暂无可预览的就绪素材"
|
||||
emptyLabel.textColor = UIColor.white.withAlphaComponent(0.7)
|
||||
emptyLabel.font = .systemFont(ofSize: 15)
|
||||
emptyLabel.textAlignment = .center
|
||||
emptyLabel.numberOfLines = 0
|
||||
emptyLabel.isHidden = !items.isEmpty
|
||||
|
||||
instructionLabel.text = items.count > 1 ? "双指或双击缩放 · 左右滑动切换" : "双指或双击缩放"
|
||||
instructionLabel.textColor = UIColor.white.withAlphaComponent(0.4)
|
||||
instructionLabel.font = .systemFont(ofSize: 11)
|
||||
instructionLabel.textAlignment = .center
|
||||
instructionLabel.isHidden = items.isEmpty
|
||||
|
||||
view.addSubview(collectionView)
|
||||
view.addSubview(emptyLabel)
|
||||
view.addSubview(closeButton)
|
||||
view.addSubview(counterLabel)
|
||||
view.addSubview(instructionLabel)
|
||||
}
|
||||
|
||||
private func setupConstraints() {
|
||||
collectionView.snp.makeConstraints { make in
|
||||
make.edges.equalToSuperview()
|
||||
}
|
||||
closeButton.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide).offset(4)
|
||||
make.trailing.equalToSuperview().inset(10)
|
||||
make.size.equalTo(44)
|
||||
}
|
||||
counterLabel.snp.makeConstraints { make in
|
||||
make.centerY.equalTo(closeButton)
|
||||
make.centerX.equalToSuperview()
|
||||
make.leading.greaterThanOrEqualToSuperview().offset(64)
|
||||
make.trailing.lessThanOrEqualTo(closeButton.snp.leading).offset(-8)
|
||||
}
|
||||
emptyLabel.snp.makeConstraints { make in
|
||||
make.center.equalToSuperview()
|
||||
make.leading.trailing.equalToSuperview().inset(32)
|
||||
}
|
||||
instructionLabel.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview().inset(24)
|
||||
make.bottom.equalTo(view.safeAreaLayoutGuide).inset(16)
|
||||
}
|
||||
}
|
||||
|
||||
private func setupDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Section, String>(collectionView: collectionView) { [weak self] collectionView, indexPath, identifier in
|
||||
guard let self, let material = self.items.first(where: { $0.id == identifier }),
|
||||
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DroneMaterialPreviewCell.reuseIdentifier, for: indexPath) as? DroneMaterialPreviewCell else {
|
||||
return UICollectionViewCell()
|
||||
}
|
||||
cell.configure(material: material)
|
||||
cell.onPlayLocalVideo = { [weak self, weak cell] in
|
||||
self?.playLocalVideo(material, sourceCell: cell)
|
||||
}
|
||||
return cell
|
||||
}
|
||||
}
|
||||
|
||||
private func applySnapshot() {
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
|
||||
snapshot.appendSections([.materials])
|
||||
snapshot.appendItems(items.map(\.id))
|
||||
dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in
|
||||
guard let self, self.collectionView.bounds.width > 0 else { return }
|
||||
self.collectionView.layoutIfNeeded()
|
||||
self.collectionView.setContentOffset(CGPoint(x: CGFloat(self.currentIndex) * self.collectionView.bounds.width, y: 0), animated: false)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeCollectionLayout() -> UICollectionViewLayout {
|
||||
let layout = UICollectionViewFlowLayout()
|
||||
layout.scrollDirection = .horizontal
|
||||
layout.minimumLineSpacing = 0
|
||||
layout.minimumInteritemSpacing = 0
|
||||
return layout
|
||||
}
|
||||
|
||||
private func updateCounter() {
|
||||
counterLabel.text = items.isEmpty ? "0 / 0" : "\(currentIndex + 1) / \(items.count)"
|
||||
counterLabel.accessibilityLabel = items.isEmpty ? "没有可预览素材" : "第 \(currentIndex + 1) 项,共 \(items.count) 项"
|
||||
}
|
||||
|
||||
private func updateCurrentIndex() {
|
||||
guard collectionView.bounds.width > 0, !items.isEmpty else { return }
|
||||
currentIndex = min(max(Int(round(collectionView.contentOffset.x / collectionView.bounds.width)), 0), items.count - 1)
|
||||
updateCounter()
|
||||
}
|
||||
|
||||
private func playLocalVideo(_ material: DroneMaterial, sourceCell: DroneMaterialPreviewCell?) {
|
||||
guard playbackTask == nil, let url = DroneMaterialPreviewCell.localVideoURL(for: material) else { return }
|
||||
sourceCell?.setVideoValidationInProgress(true)
|
||||
playbackTask = Task { @MainActor [weak self, weak sourceCell] in
|
||||
let playable = (try? await AVURLAsset(url: url).load(.isPlayable)) == true
|
||||
guard let self else { return }
|
||||
self.playbackTask = nil
|
||||
sourceCell?.setVideoValidationInProgress(false)
|
||||
guard !Task.isCancelled, self.view.window != nil, self.presentedViewController == nil,
|
||||
self.items.indices.contains(self.currentIndex), self.items[self.currentIndex].id == material.id else { return }
|
||||
guard playable else {
|
||||
sourceCell?.showUnavailableVideo()
|
||||
return
|
||||
}
|
||||
let controller = AVPlayerViewController()
|
||||
let player = AVPlayer(url: url)
|
||||
controller.player = player
|
||||
self.videoController = controller
|
||||
self.present(controller, animated: true) { player.play() }
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func closeTapped() {
|
||||
playbackTask?.cancel()
|
||||
playbackTask = nil
|
||||
videoController?.player?.pause()
|
||||
dismiss(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneMaterialPreviewViewController: UICollectionViewDelegateFlowLayout {
|
||||
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
|
||||
collectionView.bounds.size
|
||||
}
|
||||
|
||||
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { updateCurrentIndex() }
|
||||
|
||||
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { updateCurrentIndex() }
|
||||
}
|
||||
|
||||
/// 单项本地素材预览,完整呈现图片并提供独立缩放,不触发远程请求。
|
||||
@MainActor
|
||||
private final class DroneMaterialPreviewCell: UICollectionViewCell, UIScrollViewDelegate {
|
||||
static let reuseIdentifier = "DroneMaterialPreviewCell"
|
||||
|
||||
/// 用户明确点击本地可播放视频后通知预览页。
|
||||
var onPlayLocalVideo: (() -> Void)?
|
||||
|
||||
private let scrollView = DroneMaterialPreviewZoomView()
|
||||
private var imageView: UIImageView { scrollView.imageView }
|
||||
private let titleLabel = UILabel()
|
||||
private let typeLabel = UILabel()
|
||||
private let zoomLabel = UILabel()
|
||||
private let unavailableImageLabel = UILabel()
|
||||
private let playButton = UIButton(type: .system)
|
||||
private var imageAspectRatio: CGFloat = 9 / 16
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
setupUI()
|
||||
setupConstraints()
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() {
|
||||
super.prepareForReuse()
|
||||
onPlayLocalVideo = nil
|
||||
scrollView.setZoomScale(1, animated: false)
|
||||
imageView.image = nil
|
||||
playButton.isEnabled = true
|
||||
}
|
||||
|
||||
/// 只读取本地图片资源;视频无本地片源时明确显示静帧说明。
|
||||
func configure(material: DroneMaterial) {
|
||||
scrollView.setZoomScale(1, animated: false)
|
||||
scrollView.setContentOffset(.zero, animated: false)
|
||||
let image: UIImage?
|
||||
if material.kind == .photo, let url = material.previewURL, url.isFileURL {
|
||||
image = UIImage(contentsOfFile: url.path) ?? UIImage(named: material.previewAssetName)
|
||||
} else {
|
||||
image = UIImage(named: material.previewAssetName)
|
||||
}
|
||||
imageView.image = image
|
||||
imageView.accessibilityLabel = material.title
|
||||
titleLabel.text = "\(material.title) · 演示素材"
|
||||
imageAspectRatio = image.map { $0.size.height / max($0.size.width, 1) } ?? 9 / 16
|
||||
unavailableImageLabel.isHidden = image != nil
|
||||
playButton.isHidden = Self.localVideoURL(for: material) == nil
|
||||
switch material.kind {
|
||||
case .photo:
|
||||
typeLabel.text = "照片 · 本地演示图片"
|
||||
case .video:
|
||||
typeLabel.text = playButton.isHidden ? "视频 · 本地演示静帧 · 暂无演示视频" : "视频 · 本地演示视频"
|
||||
}
|
||||
zoomLabel.text = "100%"
|
||||
updateMediaConstraints()
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
/// 只接受实际存在的本地文件,远程地址不会被交给播放器。
|
||||
static func localVideoURL(for material: DroneMaterial) -> URL? {
|
||||
guard material.kind == .video, let url = material.previewURL, url.isFileURL,
|
||||
FileManager.default.fileExists(atPath: url.path),
|
||||
["mp4", "mov", "m4v"].contains(url.pathExtension.lowercased()) else { return nil }
|
||||
return url
|
||||
}
|
||||
|
||||
/// 校验本地视频期间锁定播放按钮,避免重复创建播放器。
|
||||
func setVideoValidationInProgress(_ inProgress: Bool) {
|
||||
playButton.isEnabled = !inProgress
|
||||
playButton.accessibilityLabel = inProgress ? "正在检查本地视频" : "播放本地演示视频"
|
||||
}
|
||||
|
||||
/// 本地文件无法播放时保留真实静帧,不展示虚假的进度。
|
||||
func showUnavailableVideo() {
|
||||
playButton.isHidden = true
|
||||
typeLabel.text = "视频 · 本地演示静帧 · 暂无可播放演示视频"
|
||||
}
|
||||
|
||||
func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView }
|
||||
|
||||
func scrollViewDidZoom(_ scrollView: UIScrollView) {
|
||||
zoomLabel.text = "\(Int((scrollView.zoomScale * 100).rounded()))%"
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
scrollView.minimumZoomScale = 1
|
||||
scrollView.maximumZoomScale = 3
|
||||
scrollView.delegate = self
|
||||
scrollView.showsHorizontalScrollIndicator = false
|
||||
scrollView.showsVerticalScrollIndicator = false
|
||||
scrollView.contentInsetAdjustmentBehavior = .never
|
||||
scrollView.bouncesZoom = true
|
||||
scrollView.accessibilityIdentifier = "drone.material.preview.zoomSurface"
|
||||
imageView.contentMode = .scaleAspectFit
|
||||
imageView.isAccessibilityElement = true
|
||||
imageView.accessibilityIdentifier = "drone.material.preview.image"
|
||||
|
||||
titleLabel.font = .systemFont(ofSize: 13, weight: .medium)
|
||||
titleLabel.textColor = UIColor.white.withAlphaComponent(0.75)
|
||||
titleLabel.textAlignment = .center
|
||||
titleLabel.numberOfLines = 2
|
||||
titleLabel.accessibilityIdentifier = "drone.material.preview.title"
|
||||
typeLabel.font = .systemFont(ofSize: 11)
|
||||
typeLabel.textColor = UIColor.white.withAlphaComponent(0.5)
|
||||
typeLabel.textAlignment = .center
|
||||
typeLabel.numberOfLines = 2
|
||||
typeLabel.accessibilityIdentifier = "drone.material.preview.type"
|
||||
zoomLabel.font = .monospacedDigitSystemFont(ofSize: 11, weight: .regular)
|
||||
zoomLabel.textColor = UIColor.white.withAlphaComponent(0.4)
|
||||
zoomLabel.textAlignment = .center
|
||||
zoomLabel.accessibilityIdentifier = "drone.material.preview.zoom"
|
||||
|
||||
unavailableImageLabel.text = "暂无本地演示图片"
|
||||
unavailableImageLabel.font = .systemFont(ofSize: 14)
|
||||
unavailableImageLabel.textColor = UIColor.white.withAlphaComponent(0.65)
|
||||
unavailableImageLabel.textAlignment = .center
|
||||
unavailableImageLabel.numberOfLines = 0
|
||||
playButton.setImage(UIImage(systemName: "play.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 58, weight: .regular)), for: .normal)
|
||||
playButton.tintColor = .white
|
||||
playButton.accessibilityLabel = "播放本地演示视频"
|
||||
playButton.accessibilityIdentifier = "drone.material.preview.play"
|
||||
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
|
||||
|
||||
contentView.addSubview(scrollView)
|
||||
contentView.addSubview(unavailableImageLabel)
|
||||
contentView.addSubview(titleLabel)
|
||||
contentView.addSubview(typeLabel)
|
||||
contentView.addSubview(zoomLabel)
|
||||
contentView.addSubview(playButton)
|
||||
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped(_:)))
|
||||
doubleTap.numberOfTapsRequired = 2
|
||||
scrollView.addGestureRecognizer(doubleTap)
|
||||
}
|
||||
|
||||
private func setupConstraints() {
|
||||
updateMediaConstraints()
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(scrollView.snp.bottom).offset(16)
|
||||
make.leading.trailing.equalToSuperview().inset(24)
|
||||
}
|
||||
typeLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(titleLabel.snp.bottom).offset(6)
|
||||
make.leading.trailing.equalTo(titleLabel)
|
||||
}
|
||||
zoomLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(typeLabel.snp.bottom).offset(6)
|
||||
make.leading.trailing.equalTo(titleLabel)
|
||||
}
|
||||
unavailableImageLabel.snp.makeConstraints { make in
|
||||
make.center.equalTo(scrollView)
|
||||
make.leading.trailing.equalToSuperview().inset(32)
|
||||
}
|
||||
playButton.snp.makeConstraints { make in
|
||||
make.center.equalTo(scrollView)
|
||||
make.size.equalTo(72)
|
||||
}
|
||||
}
|
||||
|
||||
private func updateMediaConstraints() {
|
||||
scrollView.snp.remakeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.centerY.equalToSuperview().offset(-28)
|
||||
make.height.equalTo(scrollView.snp.width).multipliedBy(imageAspectRatio).priority(999)
|
||||
make.height.lessThanOrEqualToSuperview().multipliedBy(0.6)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func playTapped() { onPlayLocalVideo?() }
|
||||
|
||||
@objc private func doubleTapped(_ gesture: UITapGestureRecognizer) {
|
||||
guard imageView.image != nil else { return }
|
||||
if scrollView.zoomScale > 1 {
|
||||
scrollView.setZoomScale(1, animated: true)
|
||||
return
|
||||
}
|
||||
let point = gesture.location(in: imageView)
|
||||
let targetScale: CGFloat = 3
|
||||
let size = CGSize(width: scrollView.bounds.width / targetScale, height: scrollView.bounds.height / targetScale)
|
||||
scrollView.zoom(to: CGRect(x: point.x - size.width / 2, y: point.y - size.height / 2, width: size.width, height: size.height), animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 在自身视口完成布局后设置图片尺寸,避免依赖集合单元与约束子树的布局先后顺序。
|
||||
@MainActor
|
||||
private final class DroneMaterialPreviewZoomView: UIScrollView {
|
||||
/// 由素材单元配置的图片,也是 UIScrollView 的缩放目标。
|
||||
let imageView = UIImageView()
|
||||
private var lastViewportSize = CGSize.zero
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
imageView.isUserInteractionEnabled = true
|
||||
addSubview(imageView)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func layoutSubviews() {
|
||||
super.layoutSubviews()
|
||||
let viewportSize = bounds.size
|
||||
guard viewportSize.width > 0, viewportSize.height > 0, viewportSize != lastViewportSize else { return }
|
||||
lastViewportSize = viewportSize
|
||||
setZoomScale(1, animated: false)
|
||||
imageView.frame = CGRect(origin: .zero, size: viewportSize)
|
||||
contentSize = viewportSize
|
||||
setContentOffset(.zero, animated: false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 素材库只提出导航请求,由机巢入口协调预览与尚未实现的交付流程。
|
||||
@MainActor
|
||||
protocol DroneMaterialsViewControllerDelegate: AnyObject {
|
||||
/// 预览单项素材,保持素材库现有选择与下载批次。
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestPreview material: DroneMaterial)
|
||||
/// 请求当前拍摄记录的交付占位入口。
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord)
|
||||
}
|
||||
|
||||
/// 订单素材库:按拍摄记录分组,支持点位筛选、独立预览选择与前台演示下载。
|
||||
@MainActor
|
||||
final class DroneMaterialsViewController: BaseViewController {
|
||||
/// 素材展示、选择与批次状态的来源。
|
||||
let viewModel: DroneMaterialsViewModel
|
||||
/// 将跨页面操作交给机巢导航入口。
|
||||
weak var delegate: DroneMaterialsViewControllerDelegate?
|
||||
|
||||
/// 订单、筛选和拍摄记录采用稳定分区标识,刷新时保留当前滚动位置。
|
||||
private enum Section: Hashable {
|
||||
case order, filters, summary, record(String), message
|
||||
}
|
||||
|
||||
/// 网格和辅助单元的稳定身份,不将可变选择状态纳入 Diffable 标识。
|
||||
private enum Item: Hashable {
|
||||
case order, filter(String?), context, summary, material(String), message
|
||||
}
|
||||
|
||||
/// 底部主按钮当前对应的操作;启用规则由 ViewModel 提供。
|
||||
private enum FooterAction {
|
||||
case download, resume, retry, selectMore, permission, none
|
||||
}
|
||||
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||||
private let footerView = DroneMaterialsFooterView()
|
||||
private let refreshControl = UIRefreshControl()
|
||||
private let transferDriver = DroneMaterialDemoTransferDriver()
|
||||
private var footerAction: FooterAction = .download
|
||||
private var recordsByID: [String: DroneMaterialRecord] = [:]
|
||||
private var materialsByID: [String: DroneMaterial] = [:]
|
||||
private var originalInteractivePopEnabled: Bool?
|
||||
|
||||
private var hasRunningDownload: Bool {
|
||||
switch viewModel.downloadPhase {
|
||||
case .downloading, .awaitingSave, .saving: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
|
||||
/// 使用入口共享的素材状态,支持订单全量入口与当前任务点位入口。
|
||||
init(viewModel: DroneMaterialsViewModel) {
|
||||
self.viewModel = viewModel
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 返回素材页只刷新快照,不自动继续已暂停的批次。
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
viewModel.refresh()
|
||||
if dataSource != nil { applySnapshot(animated: false) }
|
||||
}
|
||||
|
||||
/// 真正返回上层页面时停止未完成项;全屏预览覆盖素材页不触发离页处理。
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
if isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true {
|
||||
transferDriver.stop()
|
||||
viewModel.leavePage()
|
||||
restoreInteractivePopGesture()
|
||||
}
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "订单素材库"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain,
|
||||
target: self, action: #selector(backTapped))
|
||||
back.accessibilityIdentifier = "drone.materials.back"
|
||||
back.accessibilityLabel = "返回"
|
||||
navigationItem.leftBarButtonItem = back
|
||||
let refresh = UIBarButtonItem(title: "刷新", style: .plain,
|
||||
target: self, action: #selector(refreshTapped))
|
||||
refresh.accessibilityIdentifier = "drone.materials.refresh"
|
||||
refresh.accessibilityLabel = "刷新素材状态"
|
||||
#if DEBUG
|
||||
let scenarios = DroneMaterialsScenario.allCases.map { scenario in
|
||||
UIAction(title: scenario.title) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.transferDriver.stop()
|
||||
self.viewModel.applyScenario(scenario)
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
let advance = UIAction(title: "模拟下一项下载回执", image: UIImage(systemName: "arrow.forward.circle")) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.transferDriver.stop()
|
||||
self.viewModel.advanceDemoDownload()
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
let allowPermission = UIAction(title: "模拟相册权限恢复", image: UIImage(systemName: "lock.open")) { [weak self] _ in
|
||||
guard let self, self.viewModel.photoPermission != .allowed else { return }
|
||||
self.transferDriver.stop()
|
||||
self.viewModel.setPhotoPermission(.allowed)
|
||||
self.applySnapshot(animated: true)
|
||||
self.showToast("演示权限已恢复,请手动继续下载")
|
||||
}
|
||||
let menu = UIMenu(title: "素材库本地演示状态", children: [
|
||||
UIMenu(options: .displayInline, children: scenarios),
|
||||
UIMenu(options: .displayInline, children: [advance, allowPermission])
|
||||
])
|
||||
let debug = UIBarButtonItem(image: UIImage(systemName: "slider.horizontal.3"), menu: menu)
|
||||
debug.accessibilityIdentifier = "drone.materials.scenarios"
|
||||
debug.accessibilityLabel = "素材库演示状态"
|
||||
navigationItem.rightBarButtonItems = [refresh, debug]
|
||||
#else
|
||||
navigationItem.rightBarButtonItem = refresh
|
||||
#endif
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
collectionView.backgroundColor = .white
|
||||
collectionView.alwaysBounceVertical = true
|
||||
collectionView.showsVerticalScrollIndicator = false
|
||||
collectionView.accessibilityIdentifier = "drone.materials.list"
|
||||
collectionView.delegate = self
|
||||
collectionView.register(DroneMaterialOrderCell.self, forCellWithReuseIdentifier: "order")
|
||||
collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "filter")
|
||||
collectionView.register(DroneMaterialPointContextCell.self, forCellWithReuseIdentifier: "context")
|
||||
collectionView.register(DroneMaterialSelectionCell.self, forCellWithReuseIdentifier: "summary")
|
||||
collectionView.register(DroneMaterialCell.self, forCellWithReuseIdentifier: "material")
|
||||
collectionView.register(DroneMaterialMessageCell.self, forCellWithReuseIdentifier: "message")
|
||||
collectionView.register(DroneMaterialRecordHeaderView.self,
|
||||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
||||
withReuseIdentifier: "recordHeader")
|
||||
collectionView.register(DroneMaterialSeparatorView.self,
|
||||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
|
||||
withReuseIdentifier: "separator")
|
||||
refreshControl.tintColor = DroneDockStyle.primary
|
||||
collectionView.refreshControl = refreshControl
|
||||
view.addSubview(collectionView)
|
||||
view.addSubview(footerView)
|
||||
configureDataSource()
|
||||
applySnapshot(animated: false)
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
collectionView.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide)
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.bottom.equalTo(footerView.snp.top)
|
||||
}
|
||||
footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
refreshControl.addTarget(self, action: #selector(refreshTapped), for: .valueChanged)
|
||||
footerView.onPrimaryTap = { [weak self] in self?.performFooterAction() }
|
||||
footerView.onSecondaryTap = { [weak self] in
|
||||
guard let self else { return }
|
||||
self.viewModel.clearBatch()
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
|
||||
name: UIApplication.willResignActiveNotification, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
|
||||
name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { [weak self] sectionIndex, environment in
|
||||
guard let self, let dataSource = self.dataSource else { return nil }
|
||||
let sections = dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(sectionIndex) else { return nil }
|
||||
let section = sections[sectionIndex]
|
||||
switch section {
|
||||
case .record:
|
||||
let width = (environment.container.effectiveContentSize.width - 44) / 2
|
||||
let height = width * 0.57 + 51
|
||||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
|
||||
widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1)
|
||||
))
|
||||
let group = NSCollectionLayoutGroup.horizontal(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)),
|
||||
repeatingSubitem: item, count: 2
|
||||
)
|
||||
group.interItemSpacing = .fixed(12)
|
||||
let layoutSection = NSCollectionLayoutSection(group: group)
|
||||
layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 20, trailing: 16)
|
||||
layoutSection.interGroupSpacing = 12
|
||||
layoutSection.boundarySupplementaryItems = [
|
||||
NSCollectionLayoutBoundarySupplementaryItem(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(80)),
|
||||
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top
|
||||
),
|
||||
NSCollectionLayoutBoundarySupplementaryItem(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(1)),
|
||||
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom
|
||||
)
|
||||
]
|
||||
return layoutSection
|
||||
case .order:
|
||||
return self.singleColumnSection(height: .estimated(116))
|
||||
case .filters:
|
||||
if self.viewModel.pointID != nil { return self.singleColumnSection(height: .absolute(46)) }
|
||||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
|
||||
widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)
|
||||
))
|
||||
let group = NSCollectionLayoutGroup.horizontal(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .absolute(90), heightDimension: .absolute(36)),
|
||||
subitems: [item]
|
||||
)
|
||||
let layoutSection = NSCollectionLayoutSection(group: group)
|
||||
layoutSection.orthogonalScrollingBehavior = .continuous
|
||||
layoutSection.interGroupSpacing = 9
|
||||
layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 16, bottom: 8, trailing: 16)
|
||||
return layoutSection
|
||||
case .summary:
|
||||
return self.singleColumnSection(height: .absolute(46))
|
||||
case .message:
|
||||
return self.singleColumnSection(height: .absolute(250))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func singleColumnSection(height: NSCollectionLayoutDimension) -> NSCollectionLayoutSection {
|
||||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
|
||||
widthDimension: .fractionalWidth(1), heightDimension: height
|
||||
))
|
||||
let group = NSCollectionLayoutGroup.vertical(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height), subitems: [item]
|
||||
)
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
|
||||
return section
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, indexPath, item in
|
||||
guard let self else { return nil }
|
||||
switch item {
|
||||
case .order:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: indexPath) as! DroneMaterialOrderCell
|
||||
cell.apply(order: self.viewModel.order)
|
||||
return cell
|
||||
case .filter(let id):
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "filter", for: indexPath) as! DroneMaterialFilterCell
|
||||
if let filter = self.viewModel.filters.first(where: { $0.id == id }) {
|
||||
cell.apply(title: filter.title, id: filter.id,
|
||||
selected: filter.id == self.viewModel.selectedFilterID, locked: self.viewModel.isSelectionLocked)
|
||||
}
|
||||
return cell
|
||||
case .context:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "context", for: indexPath) as! DroneMaterialPointContextCell
|
||||
let title = self.viewModel.filters.first(where: { $0.id == self.viewModel.pointID })?.title
|
||||
?? self.viewModel.sections.first?.pointName ?? "当前拍摄点"
|
||||
cell.apply(title: title)
|
||||
return cell
|
||||
case .summary:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "summary", for: indexPath) as! DroneMaterialSelectionCell
|
||||
cell.apply(recordCount: self.viewModel.sections.count, allSelected: self.viewModel.isAllSelected,
|
||||
enabled: !self.viewModel.isSelectionLocked && !self.viewModel.downloadableIDs.isEmpty)
|
||||
cell.onSelectAllTap = { [weak self] in
|
||||
guard let self else { return }
|
||||
self.viewModel.selectAll()
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
return cell
|
||||
case .material(let id):
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "material", for: indexPath) as! DroneMaterialCell
|
||||
if let material = self.materialsByID[id] {
|
||||
let completed: Bool
|
||||
if case .completed = material.downloadState { completed = true } else { completed = false }
|
||||
cell.apply(material: material, selected: self.viewModel.selectedIDs.contains(id),
|
||||
selectionEnabled: !self.viewModel.isSelectionLocked && self.viewModel.downloadableIDs.contains(id),
|
||||
completed: completed)
|
||||
cell.onPreviewTap = { [weak self] in
|
||||
guard let self, let current = self.viewModel.material(id: id), current.canPreview else { return }
|
||||
self.delegate?.materialsViewController(self, didRequestPreview: current)
|
||||
}
|
||||
cell.onSelectionTap = { [weak self] in
|
||||
guard let self else { return }
|
||||
self.viewModel.toggleSelection(id: id)
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
return cell
|
||||
case .message:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: indexPath) as! DroneMaterialMessageCell
|
||||
switch self.viewModel.listState {
|
||||
case .loading:
|
||||
cell.apply(title: "正在获取素材", detail: "请稍候", symbol: "arrow.triangle.2.circlepath")
|
||||
case .failed(let message):
|
||||
cell.apply(title: "素材加载失败", detail: "\(message)\n请下拉或点击右上角刷新", symbol: "wifi.exclamationmark")
|
||||
case .loaded:
|
||||
cell.apply(title: "暂无拍摄素材", detail: "拍摄完成后的素材会显示在这里", symbol: "photo.on.rectangle.angled")
|
||||
}
|
||||
return cell
|
||||
}
|
||||
}
|
||||
dataSource.supplementaryViewProvider = { [weak self] list, kind, indexPath in
|
||||
guard let self else { return nil }
|
||||
if kind == UICollectionView.elementKindSectionFooter {
|
||||
return list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "separator", for: indexPath)
|
||||
}
|
||||
let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "recordHeader", for: indexPath) as! DroneMaterialRecordHeaderView
|
||||
self.applyHeader(header, sectionIndex: indexPath.section)
|
||||
return header
|
||||
}
|
||||
}
|
||||
|
||||
private func applySnapshot(animated: Bool) {
|
||||
guard isViewLoaded, dataSource != nil else { return }
|
||||
let records = viewModel.sections
|
||||
recordsByID = Dictionary(uniqueKeysWithValues: records.map { ($0.id, $0) })
|
||||
materialsByID = Dictionary(uniqueKeysWithValues: records.flatMap(\.materials).map { ($0.id, $0) })
|
||||
let previous = dataSource.snapshot()
|
||||
let existing = Set(previous.itemIdentifiers)
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
||||
snapshot.appendSections([.order, .filters, .summary])
|
||||
snapshot.appendItems([.order], toSection: .order)
|
||||
snapshot.appendItems(viewModel.pointID == nil ? viewModel.filters.map { .filter($0.id) } : [.context], toSection: .filters)
|
||||
snapshot.appendItems([.summary], toSection: .summary)
|
||||
switch viewModel.listState {
|
||||
case .loaded where !records.isEmpty:
|
||||
for record in records {
|
||||
let section = Section.record(record.id)
|
||||
snapshot.appendSections([section])
|
||||
snapshot.appendItems(record.materials.map { .material($0.id) }, toSection: section)
|
||||
}
|
||||
default:
|
||||
snapshot.appendSections([.message])
|
||||
snapshot.appendItems([.message], toSection: .message)
|
||||
}
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
|
||||
applyFooter()
|
||||
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
|
||||
guard let self else { return }
|
||||
let kind = UICollectionView.elementKindSectionHeader
|
||||
for path in self.collectionView.indexPathsForVisibleSupplementaryElements(ofKind: kind) {
|
||||
guard let header = self.collectionView.supplementaryView(forElementKind: kind, at: path) as? DroneMaterialRecordHeaderView else { continue }
|
||||
self.applyHeader(header, sectionIndex: path.section)
|
||||
}
|
||||
}
|
||||
if previous.sectionIdentifiers != snapshot.sectionIdentifiers { collectionView.collectionViewLayout.invalidateLayout() }
|
||||
updateInteractivePopGesture()
|
||||
}
|
||||
|
||||
private func applyHeader(_ header: DroneMaterialRecordHeaderView, sectionIndex: Int) {
|
||||
let sections = dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(sectionIndex), case .record(let id) = sections[sectionIndex], let record = recordsByID[id] else { return }
|
||||
header.apply(record: record)
|
||||
header.onDeliveryTap = { [weak self] in
|
||||
guard let self, let current = self.recordsByID[id] else { return }
|
||||
self.delegate?.materialsViewController(self, didRequestDelivery: current)
|
||||
}
|
||||
}
|
||||
|
||||
private func applyFooter() {
|
||||
if viewModel.photoPermission != .allowed {
|
||||
footerAction = .permission
|
||||
footerView.apply(title: "无法保存到手机相册", detail: "演示相册权限未开启,恢复后请手动继续。",
|
||||
primaryTitle: "检查相册权限", primarySymbol: "lock", enabled: true,
|
||||
identifier: "drone.materials.permission", progress: nil, tone: .orange)
|
||||
return
|
||||
}
|
||||
switch viewModel.downloadPhase {
|
||||
case .idle:
|
||||
footerAction = .download
|
||||
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "仅可选择已上传素材 · 本次为本地演示",
|
||||
primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line", enabled: viewModel.canStartDownload,
|
||||
identifier: "drone.materials.download", progress: nil)
|
||||
case .downloading, .awaitingSave, .saving:
|
||||
footerAction = .none
|
||||
footerView.apply(title: "本次下载\(viewModel.batchTotalCount)项 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
|
||||
detail: "请保持本页开启,下载期间不可更改选择",
|
||||
primaryTitle: viewModel.downloadButtonTitle, primarySymbol: "arrow.triangle.2.circlepath", enabled: false,
|
||||
identifier: "drone.materials.download", progress: viewModel.batchProgress, tone: .blue)
|
||||
case .paused:
|
||||
footerAction = .resume
|
||||
footerView.apply(title: "下载已暂停 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
|
||||
detail: "已完成项会保留;继续时仅处理未完成文件。",
|
||||
primaryTitle: "继续下载", primarySymbol: "play.fill", enabled: true,
|
||||
identifier: "drone.materials.continue", progress: viewModel.batchProgress, tone: .orange)
|
||||
case .partialFailure:
|
||||
footerAction = .retry
|
||||
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)
|
||||
case .completed:
|
||||
footerAction = .selectMore
|
||||
footerView.apply(title: "本次素材演示完成", detail: "\(viewModel.completedCount)项演示完成,未写入系统相册",
|
||||
primaryTitle: "继续选择素材", primarySymbol: "checkmark.circle", enabled: true,
|
||||
identifier: "drone.materials.continueSelecting", progress: nil, tone: .green)
|
||||
}
|
||||
}
|
||||
|
||||
private func performFooterAction() {
|
||||
var shouldStartDriver = false
|
||||
switch footerAction {
|
||||
case .download:
|
||||
shouldStartDriver = viewModel.startDownload()
|
||||
case .resume:
|
||||
shouldStartDriver = viewModel.continueDownload()
|
||||
case .retry:
|
||||
shouldStartDriver = viewModel.retryFailed()
|
||||
case .selectMore:
|
||||
viewModel.clearBatch()
|
||||
case .permission:
|
||||
showAlert(title: "相册权限演示", message: "当前为本地演示,不读取或修改系统相册权限。可在右上角演示状态中选择“模拟相册权限恢复”,再手动继续下载。")
|
||||
case .none:
|
||||
return
|
||||
}
|
||||
applySnapshot(animated: true)
|
||||
if shouldStartDriver { startDemoTransfer() }
|
||||
}
|
||||
|
||||
private func startDemoTransfer() {
|
||||
guard let batch = viewModel.batch, !batch.isPaused else { return }
|
||||
transferDriver.start(viewModel: viewModel) { [weak self] in self?.applySnapshot(animated: true) }
|
||||
}
|
||||
|
||||
private func updateInteractivePopGesture() {
|
||||
guard let gesture = navigationController?.interactivePopGestureRecognizer else { return }
|
||||
if hasRunningDownload {
|
||||
if originalInteractivePopEnabled == nil { originalInteractivePopEnabled = gesture.isEnabled }
|
||||
gesture.isEnabled = false
|
||||
} else {
|
||||
restoreInteractivePopGesture()
|
||||
}
|
||||
}
|
||||
|
||||
private func restoreInteractivePopGesture() {
|
||||
guard let originalInteractivePopEnabled else { return }
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = originalInteractivePopEnabled
|
||||
self.originalInteractivePopEnabled = nil
|
||||
}
|
||||
|
||||
private func leaveMaterialsPage() {
|
||||
transferDriver.stop()
|
||||
viewModel.leavePage()
|
||||
restoreInteractivePopGesture()
|
||||
if let navigationController, navigationController.viewControllers.first !== self {
|
||||
navigationController.popViewController(animated: true)
|
||||
} else {
|
||||
dismiss(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func backTapped() {
|
||||
guard hasRunningDownload else { leaveMaterialsPage(); return }
|
||||
let alert = UIAlertController(title: "素材仍在下载",
|
||||
message: "离开将暂停未完成的下载,已完成项会保留。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续下载", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "离开并暂停", style: .default) { [weak self] _ in self?.leaveMaterialsPage() })
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
@objc private func refreshTapped() {
|
||||
viewModel.refresh()
|
||||
applySnapshot(animated: true)
|
||||
refreshControl.endRefreshing()
|
||||
}
|
||||
|
||||
@objc private func applicationWillResignActive() {
|
||||
transferDriver.stop()
|
||||
viewModel.pauseDownloads(reason: .background)
|
||||
if isViewLoaded { applySnapshot(animated: false) }
|
||||
}
|
||||
|
||||
@objc private func applicationDidBecomeActive() {
|
||||
viewModel.refresh()
|
||||
if isViewLoaded { applySnapshot(animated: false) }
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneMaterialsViewController: UICollectionViewDelegate {
|
||||
/// 点位标签整项可点,素材的预览与选择交由各自按钮处理。
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath), case .filter(let id) = item else { return }
|
||||
viewModel.selectFilter(id: id)
|
||||
applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user