diff --git a/docs/9.9.1/materials-ui-2026-10-23/download-completed.png b/docs/9.9.1/materials-ui-2026-10-23/download-completed.png new file mode 100644 index 0000000..2994ff0 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-23/download-completed.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-23/download-partial-failure.png b/docs/9.9.1/materials-ui-2026-10-23/download-partial-failure.png new file mode 100644 index 0000000..b0b84b8 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-23/download-partial-failure.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-23/download-paused.png b/docs/9.9.1/materials-ui-2026-10-23/download-paused.png new file mode 100644 index 0000000..7bafd94 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-23/download-paused.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-23/download-running.png b/docs/9.9.1/materials-ui-2026-10-23/download-running.png new file mode 100644 index 0000000..0de2b20 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-23/download-running.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-23/library-mixed.png b/docs/9.9.1/materials-ui-2026-10-23/library-mixed.png new file mode 100644 index 0000000..8602ee3 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-23/library-mixed.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-23/library-selected.png b/docs/9.9.1/materials-ui-2026-10-23/library-selected.png new file mode 100644 index 0000000..df1062c Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-23/library-selected.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-23/preview-photo.png b/docs/9.9.1/materials-ui-2026-10-23/preview-photo.png new file mode 100644 index 0000000..b174273 Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-23/preview-photo.png differ diff --git a/docs/9.9.1/materials-ui-2026-10-23/preview-video-unavailable.png b/docs/9.9.1/materials-ui-2026-10-23/preview-video-unavailable.png new file mode 100644 index 0000000..1aee84a Binary files /dev/null and b/docs/9.9.1/materials-ui-2026-10-23/preview-video-unavailable.png differ diff --git a/docs/9.9.1/拍摄流程UI实现说明.md b/docs/9.9.1/拍摄流程UI实现说明.md index 859b6ce..0d5f2ae 100644 --- a/docs/9.9.1/拍摄流程UI实现说明.md +++ b/docs/9.9.1/拍摄流程UI实现说明.md @@ -2,6 +2,8 @@ 实现日期:2026-10-23。分支:`dev_9_9_1`。 +后续更新:素材入口已在下一轮接通,见[素材库 UI 实现说明](素材库UI实现说明.md);下文保留本轮拍摄页面交付时的范围记录。 + ## 本轮范围 已从工作台和“我的拍摄订单”的拍摄按钮接通以下本地页面: diff --git a/docs/9.9.1/机巢UI首轮实现说明.md b/docs/9.9.1/机巢UI首轮实现说明.md index f64f614..a33a67a 100644 --- a/docs/9.9.1/机巢UI首轮实现说明.md +++ b/docs/9.9.1/机巢UI首轮实现说明.md @@ -4,6 +4,8 @@ 后续更新:拍摄准备与当前任务已在第二轮补齐,参见[拍摄流程 UI 实现说明](拍摄流程UI实现说明.md)。本文记录首轮交付范围。 +素材入口后续已接通,参见[素材库 UI 实现说明](素材库UI实现说明.md)。 + ## 范围 - 机巢工作台:景区与工作人员、无人机遥测卡、设备横向翻页、余次订单、素材摘要、查看全部、今日统计。 diff --git a/docs/9.9.1/素材库UI实现说明.md b/docs/9.9.1/素材库UI实现说明.md new file mode 100644 index 0000000..10cc9da --- /dev/null +++ b/docs/9.9.1/素材库UI实现说明.md @@ -0,0 +1,75 @@ +# 9.9.1 素材库 UI 实现说明 + +实现日期:2026-10-23。分支:`dev_9_9_1`。 + +## 本轮范围 + +接通工作台、我的拍摄订单和当前任务的素材入口,实现本地订单素材库、照片/视频预览、多选及下载演示。布局按[新版原型复核](UI更新复核-2026-10-23.md)中的素材页面:订单摘要、点位标签、拍摄记录分组、两列缩略图、固定下载底栏。 + +使用现有本地演示图片,另将游客示例图编码为一个 3 秒静态画面视频,供播放器交互验收。没有真实游客媒体或远程视频请求。 + +## 已保留的交互规则 + +| 场景 | 实现行为 | +| --- | --- | +| 订单入口 | 展示整单素材,支持横向点位筛选,拍摄记录按时间从新到旧排列。 | +| 当前任务入口 | 只显示当前任务点位的素材,不提供切换到全部点位的入口。 | +| 预览与勾选 | 缩略图打开预览;右上角圆圈独立勾选;关闭预览保留选择及下载批次。 | +| 照片预览 | 黑底全屏、页码、左右翻页、双指/双击缩放和关闭。 | +| 视频预览 | 明确点击播放才打开本地播放器;无可播放文件时显示静帧及说明。 | +| 素材未全部上传 | 已就绪的文件可预览和下载;上传中、上传失败及不可用文件不可选择。 | +| 全选与筛选 | 全选仅覆盖当前范围可下载文件,排除已完成项;切换点位清空勾选。 | +| 下载执行 | 开始时冻结批次文件;下载与保存分别建模;执行期间禁止改变选择和筛选,重复点击不会新增批次。 | +| 返回/离页 | 下载进行中点击返回先提示,确认离开后暂停未完成项,保留已完成项;查看预览不会触发离页暂停。 | +| 后台/锁屏 | 停止本地驱动并暂停;返回前台不自动恢复,必须手动点“继续下载”。 | +| 继续/重试 | 继续跳过成功和明确失败项;失败后仅重试失败项;保存失败只重试保存。未完成文件重新下载,不实现字节续传。 | +| 跨入口 | 整单下载暂停后进入当前任务,只继续该点位;其他点位未完成文件保留暂停状态,之后可在整单入口重新选择。 | +| 完成与履约 | 演示完成不改变订单拍摄次数、当前任务或游客交付状态。已完成项在本次运行内保留,不重复选择。 | + +规则依据:[当前方案基线 C13/C14/R06](review/product-comparison/current-baseline.md)。素材页的下载离页确认与拍摄任务页返回规则分别处理。 + +## 状态覆盖 + +列表有加载中、加载失败、空列表和正常列表;文件区分上传中、上传完成、上传失败及不可用。下载阶段覆盖未选择、已选择、下载中、待保存、保存中、暂停、部分失败、完成;另有演示相册权限受限和保存失败。 + +文件身份、订单/景区上下文和批次令牌分开校验,暂停、继续及重试使旧回执失效。素材状态存放于共享内存数据源,同一订单从不同页面进入可恢复;应用重启后演示数据重置。 + +## 演示入口与限制 + +Debug 版“全部功能 → 机巢预览”,点击订单的“查看素材”;任务成功后的素材入口只显示当前点位。 + +素材页右上角菜单可切换就绪、混合上传、下载中、暂停、部分失败、保存失败、相册权限受限、完成、空列表及加载异常等验收场景。正常点击下载后,本地驱动自动演示逐项进度;也可使用菜单注入明确回执。菜单恢复权限后仍需手动继续。 + +可选启动参数: + +| 参数 | 用途 | +| --- | --- | +| `--dock-ui-materials-preview` | 直达素材库,默认混合上传场景 | +| `--dock-materials-scenario=paused` | 进入暂停场景;亦可选 `ready`、`partialFailure`、`completed` 等枚举值 | +| `--dock-materials-point=point-shaoshi` | 只显示指定演示点位 | + +本轮暂不接真实接口,不请求 Photos 权限,不下载远程文件,不写系统相册。完成文案明确为“演示完成,未写入系统相册”。相册拒权只是本地场景;交付成片保留占位提示,收款继续暂缓。 + +## 验证与截图 + +- iOS 真机目标编译通过;模拟器仅用于页面视觉检查,未运行模拟器单元测试。 +- iPhone 11 真机复测 **74 项、0 失败**:本轮素材规则 21 项、预览 3 项、素材联动 5 项,以及之前机巢与拍摄流程 45 项。 +- 覆盖真实入口导航、点位范围、勾选与预览互不影响、本地视频随包可播放、下载自动演示、后台暂停与手动继续、失败重试、保存阶段、旧回执隔离、订单额度不变及页面可见约束。 +- 首轮真机检查发现的预览图片零尺寸问题已修复,复测增加图片实际尺寸和图片/关闭/播放控件点击可达检查。 +- 未接真实网络/Photos,未进行全工程回归。截图由真机 XCTest 隔离窗口渲染,系统状态栏不在截图中。 + +| 混合上传状态 | 全选可下载 | +| --- | --- | +| ![混合上传](materials-ui-2026-10-23/library-mixed.png) | ![选择](materials-ui-2026-10-23/library-selected.png) | + +| 下载演示中 | 后台暂停 | +| --- | --- | +| ![下载中](materials-ui-2026-10-23/download-running.png) | ![暂停](materials-ui-2026-10-23/download-paused.png) | + +| 部分失败 | 演示完成 | +| --- | --- | +| ![部分失败](materials-ui-2026-10-23/download-partial-failure.png) | ![演示完成](materials-ui-2026-10-23/download-completed.png) | + +| 照片预览 | 无本地片源的视频说明 | +| --- | --- | +| ![照片预览](materials-ui-2026-10-23/preview-photo.png) | ![无片源](materials-ui-2026-10-23/preview-video-unavailable.png) | diff --git a/suixinkan/Features/DroneDock/Models/DroneMaterialModels.swift b/suixinkan/Features/DroneDock/Models/DroneMaterialModels.swift new file mode 100644 index 0000000..ca1a347 --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneMaterialModels.swift @@ -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 diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockViewModels.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockViewModels.swift index dfc7634..a65428c 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockViewModels.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockViewModels.swift @@ -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 { diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneMaterialsViewModel.swift b/suixinkan/Features/DroneDock/ViewModels/DroneMaterialsViewModel.swift new file mode 100644 index 0000000..ebf9ff3 --- /dev/null +++ b/suixinkan/Features/DroneDock/ViewModels/DroneMaterialsViewModel.swift @@ -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 = [] + 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 = [] + 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 { 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, 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 +} diff --git a/suixinkan/Resources/DroneDock/drone_material_demo.mp4 b/suixinkan/Resources/DroneDock/drone_material_demo.mp4 new file mode 100644 index 0000000..d59de20 Binary files /dev/null and b/suixinkan/Resources/DroneDock/drone_material_demo.mp4 differ diff --git a/suixinkan/UI/DroneDock/DroneDockPreview.swift b/suixinkan/UI/DroneDock/DroneDockPreview.swift index 015535b..8199f11 100644 --- a/suixinkan/UI/DroneDock/DroneDockPreview.swift +++ b/suixinkan/UI/DroneDock/DroneDockPreview.swift @@ -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 } } diff --git a/suixinkan/UI/DroneDock/DroneDockWorkbenchViewController.swift b/suixinkan/UI/DroneDock/DroneDockWorkbenchViewController.swift index 8c8764f..c720c97 100644 --- a/suixinkan/UI/DroneDock/DroneDockWorkbenchViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockWorkbenchViewController.swift @@ -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) } } diff --git a/suixinkan/UI/DroneDock/DroneMaterialComponents.swift b/suixinkan/UI/DroneDock/DroneMaterialComponents.swift new file mode 100644 index 0000000..0c7eb51 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneMaterialComponents.swift @@ -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?() } +} diff --git a/suixinkan/UI/DroneDock/DroneMaterialDemoTransferDriver.swift b/suixinkan/UI/DroneDock/DroneMaterialDemoTransferDriver.swift new file mode 100644 index 0000000..8fc9620 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneMaterialDemoTransferDriver.swift @@ -0,0 +1,65 @@ +import Foundation + +/// 本地 UI 演示的下载回执驱动,不连接网络、不写文件或系统相册。 +@MainActor +final class DroneMaterialDemoTransferDriver { + private var task: Task? + 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) + } +} diff --git a/suixinkan/UI/DroneDock/DroneMaterialPreviewViewController.swift b/suixinkan/UI/DroneDock/DroneMaterialPreviewViewController.swift new file mode 100644 index 0000000..8fc7bec --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneMaterialPreviewViewController.swift @@ -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! + 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? + + /// 以当前素材为起点预览已就绪素材;未就绪项不会被带入预览列表。 + init(items: [DroneMaterial], initialMaterialID: String) { + var identifiers = Set() + 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(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() + 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) + } +} diff --git a/suixinkan/UI/DroneDock/DroneMaterialsViewController.swift b/suixinkan/UI/DroneDock/DroneMaterialsViewController.swift new file mode 100644 index 0000000..af8764e --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneMaterialsViewController.swift @@ -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! + 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(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() + 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) + } +} diff --git a/suixinkanTests/DroneMaterialPreviewViewTests.swift b/suixinkanTests/DroneMaterialPreviewViewTests.swift new file mode 100644 index 0000000..3c1e022 --- /dev/null +++ b/suixinkanTests/DroneMaterialPreviewViewTests.swift @@ -0,0 +1,192 @@ +import AVFoundation +import AVKit +import UIKit +import XCTest +@testable import suixinkan + +/// 在真机窗口验证素材预览的就绪过滤、初始页、静帧说明和关闭路径。 +@MainActor +final class DroneMaterialPreviewViewTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 本地演示视频随应用打包,点击播放才呈现播放器,不访问远程媒体。 + func testBundledDemoVideoIsPlayableAndOpensOnlyAfterTap() async throws { + let url = try XCTUnwrap(Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")) + XCTAssertTrue(url.isFileURL) + let playable = try await AVURLAsset(url: url).load(.isPlayable) + XCTAssertTrue(playable) + let material = DroneMaterial(id: "local-video", title: "演示视频", kind: .video, + previewURL: url, durationText: "00:03") + let controller = DroneMaterialPreviewViewController(items: [material], initialMaterialID: material.id) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window: window) { + self.find(in: controller.view, identifier: "drone.material.preview.play") != nil + } + XCTAssertNil(controller.presentedViewController) + let play = try XCTUnwrap(find(in: controller.view, identifier: "drone.material.preview.play") as? UIButton) + assertHitTestReaches(play, in: window) + play.sendActions(for: .touchUpInside) + try await settle(window: window) { controller.presentedViewController is AVPlayerViewController } + let player = try XCTUnwrap(controller.presentedViewController as? AVPlayerViewController) + XCTAssertEqual((player.player?.currentItem?.asset as? AVURLAsset)?.url, url) + player.player?.pause() + player.dismiss(animated: false) + } + + /// 指定素材从过滤后的正确页打开,真实本地图可见并保留预览截图。 + func testReadyMaterialsOpenAtRequestedPageAndRenderLocalImage() async throws { + let items = [ + DroneMaterial(id: "photo-01", title: "素材01", previewAssetName: "drone_demo_mountain"), + DroneMaterial(id: "failed-02", title: "素材02", uploadState: .failed), + DroneMaterial(id: "photo-03", title: "素材03", previewAssetName: "drone_demo_pagoda") + ] + let controller = DroneMaterialPreviewViewController(items: items, initialMaterialID: "photo-03") + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window: window) { + self.previewImage(in: controller.view, title: "素材03", window: window) != nil + } + + let labels = visibleViews(in: controller.view).compactMap { $0 as? UILabel } + XCTAssertTrue(labels.contains { $0.text == "2 / 2" }) + XCTAssertTrue(labels.contains { $0.text == "照片 · 本地演示图片" }) + XCTAssertFalse(labels.contains { $0.text?.contains("素材02") == true }) + let image = try XCTUnwrap(previewImage(in: controller.view, title: "素材03", window: window)) + XCTAssertNotNil(image.image) + XCTAssertEqual(image.accessibilityLabel, "素材03") + XCTAssertGreaterThan(image.bounds.width, 100) + XCTAssertGreaterThan(image.bounds.height, 100) + assertHitTestReaches(image, in: window) + let close = try XCTUnwrap(find(in: controller.view, identifier: "drone.material.preview.close") as? UIButton) + assertVisible(close, in: window) + XCTAssertFalse(visibleViews(in: controller.view).contains { + !$0.translatesAutoresizingMaskIntoConstraints && !String(describing: type(of: $0)).hasPrefix("_") && $0.hasAmbiguousLayout + }) + capture(window, named: "机巢-素材预览-就绪图片与页码") + } + + /// 无本地片源的视频明确标识为静帧,关闭后回到原页面而不触发播放或其他操作。 + func testVideoWithoutLocalClipShowsHonestStillFrameAndCloses() async throws { + let material = DroneMaterial(id: "video-01", title: "素材视频01", kind: .video, + previewAssetName: "drone_demo_mountain", previewURL: nil) + let host = UIViewController() + host.view.backgroundColor = .systemBackground + host.view.accessibilityIdentifier = "drone.material.preview.testHost" + let window = makeWindow(root: host) + defer { close(window) } + let controller = DroneMaterialPreviewViewController(items: [material], initialMaterialID: material.id) + host.present(controller, animated: false) + try await settle(window: window) { + controller.view.window != nil && controller.presentingViewController === host + && self.previewImage(in: controller.view, title: material.title, window: window) != nil + } + + let labels = visibleViews(in: controller.view).compactMap { $0 as? UILabel } + XCTAssertTrue(labels.contains { $0.text == "视频 · 本地演示静帧 · 暂无演示视频" }) + XCTAssertFalse(visibleViews(in: controller.view).contains { $0.accessibilityIdentifier == "drone.material.preview.play" }) + XCTAssertNil(controller.presentedViewController) + capture(window, named: "机巢-素材预览-视频静帧明确说明") + let close = try XCTUnwrap(find(in: controller.view, identifier: "drone.material.preview.close") as? UIButton) + assertHitTestReaches(close, in: window) + close.sendActions(for: .touchUpInside) + try await settle(window: window) { host.presentedViewController == nil } + XCTAssertTrue(window.rootViewController === host) + XCTAssertNotNil(host.view.window) + } + + /// 使用真机当前场景创建隔离窗口,保持测试前的主窗口可恢复。 + private func makeWindow(root controller: UIViewController) -> UIWindow { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first + previousKeyWindow = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.frame = scene?.coordinateSpace.bounds ?? UIScreen.main.bounds + window.rootViewController = controller + window.makeKeyAndVisible() + window.layoutIfNeeded() + return window + } + + private func close(_ window: UIWindow) { + window.rootViewController?.dismiss(animated: false) + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + + /// 等待分页快照和关闭转场完成后验证实际可见内容。 + private func settle(window: UIWindow, until condition: () -> Bool) async throws { + for _ in 0..<150 { + window.layoutIfNeeded() + window.rootViewController?.view.layoutIfNeeded() + if condition() { + try await Task.sleep(nanoseconds: 250_000_000) + window.layoutIfNeeded() + return + } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTFail("素材预览未在预期时间内完成布局或关闭") + throw NSError(domain: "DroneMaterialPreviewViewTests", code: 1) + } + + private func allViews(in view: UIView) -> [UIView] { + [view] + view.subviews.flatMap { allViews(in: $0) } + } + + private func visibleViews(in view: UIView) -> [UIView] { + allViews(in: view).filter { + !isHiddenByAncestor($0) && !$0.bounds.isEmpty && $0.convert($0.bounds, to: view).intersects(view.bounds) + } + } + + private func find(in view: UIView, identifier: String) -> UIView? { + allViews(in: view).first { $0.accessibilityIdentifier == identifier } + } + + /// 等待有真实图像尺寸且中心触摸可达的当前页,不能仅以标题出现判定预览完成。 + private func previewImage(in view: UIView, title: String, window: UIWindow) -> UIImageView? { + visibleViews(in: view).compactMap { $0 as? UIImageView }.first { + $0.accessibilityIdentifier == "drone.material.preview.image" && $0.accessibilityLabel == title + && $0.image != nil && $0.bounds.width > 100 && $0.bounds.height > 100 + && isHitTestReachable($0, in: window) + } + } + + private func isHitTestReachable(_ view: UIView, in window: UIWindow) -> Bool { + let center = view.convert(CGPoint(x: view.bounds.midX, y: view.bounds.midY), to: window) + guard window.bounds.contains(center), let hit = window.hitTest(center, with: nil) else { return false } + return hit === view || hit.isDescendant(of: view) + } + + /// 验证实际触摸命中目标或其子视图,捕获空尺寸、裁切或透明覆盖导致的假可见内容。 + private func assertHitTestReaches(_ view: UIView, in window: UIWindow, file: StaticString = #filePath, line: UInt = #line) { + XCTAssertTrue(isHitTestReachable(view, in: window), "触摸无法到达 \(view.accessibilityIdentifier ?? String(describing: type(of: view)))", file: file, line: line) + } + + private func isHiddenByAncestor(_ view: UIView) -> Bool { + if view.isHidden || view.alpha < 0.01 { return true } + return view.superview.map { isHiddenByAncestor($0) } ?? false + } + + private func assertVisible(_ button: UIButton, in window: UIWindow, file: StaticString = #filePath, line: UInt = #line) { + XCTAssertTrue(button.isEnabled, file: file, line: line) + let frame = button.convert(button.bounds, to: window) + XCTAssertGreaterThanOrEqual(frame.height, 44, file: file, line: line) + XCTAssertGreaterThanOrEqual(frame.width, 44, file: file, line: line) + XCTAssertTrue(window.bounds.contains(frame), file: file, line: line) + assertHitTestReaches(button, in: window, file: file, line: line) + } + + /// 把预览的静态画面保留到真机测试 xcresult 中,供按原型复核。 + private func capture(_ window: UIWindow, named name: String) { + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let attachment = XCTAttachment(image: image) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } +} diff --git a/suixinkanTests/DroneMaterialsFlowViewTests.swift b/suixinkanTests/DroneMaterialsFlowViewTests.swift new file mode 100644 index 0000000..d97d14a --- /dev/null +++ b/suixinkanTests/DroneMaterialsFlowViewTests.swift @@ -0,0 +1,362 @@ +import UIKit +import XCTest +@testable import suixinkan + +#if DEBUG +/// 在已连接 iPhone 的隔离窗口中验证素材入口、选择、演示下载与生命周期联动。 +@MainActor +final class DroneMaterialsFlowViewTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 工作台真实素材按钮进入整单素材库;预览打开和关闭不改变选择或批次。 + func testWorkbenchMaterialsSelectAllAndPreviewKeepSelectionAndBatch() async throws { + let store = makeStore() + let order = try XCTUnwrap(store.orders.first) + let seed = DroneMaterialsViewModel(store: store, orderID: order.id) + seed.applyScenario(.mixed) + let workbench = DroneDockWorkbenchViewController(viewModel: DroneDockWorkbenchViewModel(store: store)) + let window = makeWindow(root: workbench) + defer { close(window) } + let navigation = try XCTUnwrap(workbench.navigationController) + let list = try collection(in: workbench.view, identifier: "drone.workbench.list") + try await settle(window) { list.numberOfSections > 2 && list.numberOfItems(inSection: 2) == 1 } + list.scrollToItem(at: IndexPath(item: 0, section: 2), at: .centeredVertically, animated: false) + try await settle(window) { self.find(in: workbench.view, identifier: "drone.home.\(order.id)") != nil } + let card = try XCTUnwrap(find(in: workbench.view, identifier: "drone.home.\(order.id)")) + let materialEntry = try XCTUnwrap(allViews(in: card).compactMap { $0 as? UIButton }.first { + $0.accessibilityLabel?.hasPrefix("查看素材,") == true + }) + materialEntry.sendActions(for: .touchUpInside) + try await settle(window) { navigation.topViewController is DroneMaterialsViewController && navigation.transitionCoordinator == nil } + let controller = try XCTUnwrap(navigation.topViewController as? DroneMaterialsViewController) + let viewModel = controller.viewModel + XCTAssertNil(viewModel.pointID) + try await waitForLibrary(controller, window: window) + assertLayout(in: controller.view) + capture(window, named: "素材流程-混合上传状态") + + let selectAll = try button(in: controller.view, identifier: "drone.materials.selectAll") + selectAll.sendActions(for: .touchUpInside) + try await settle(window) { viewModel.selectedCount == viewModel.downloadableIDs.count && viewModel.selectedCount > 0 } + XCTAssertEqual(viewModel.selectedIDs, viewModel.downloadableIDs) + XCTAssertTrue(selectAll.accessibilityTraits.contains(.selected)) + capture(window, named: "素材流程-全选可下载素材") + let originalSelection = viewModel.selectedIDs + let originalBatch = viewModel.batch + let previewMaterial = try XCTUnwrap(viewModel.sections.first?.materials.first { $0.canPreview }) + let preview = try button(in: controller.view, identifier: "drone.materials.preview.\(previewMaterial.id)") + preview.sendActions(for: .touchUpInside) + try await settle(window) { controller.presentedViewController is DroneMaterialPreviewViewController } + let previewController = try XCTUnwrap(controller.presentedViewController as? DroneMaterialPreviewViewController) + XCTAssertEqual(viewModel.selectedIDs, originalSelection) + XCTAssertEqual(viewModel.batch, originalBatch) + try button(in: previewController.view, identifier: "drone.material.preview.close").sendActions(for: .touchUpInside) + try await settle(window) { controller.presentedViewController == nil } + XCTAssertTrue(navigation.topViewController === controller) + XCTAssertEqual(viewModel.selectedIDs, originalSelection) + XCTAssertEqual(viewModel.batch, originalBatch) + XCTAssertEqual(store.shootingOrder(id: order.id), order) + } + + /// 整单入口可通过芯片筛选;任务成功后的真实入口只显示会话点位且不能扩大范围。 + func testWholeOrderFilterAndTaskEntryKeepDifferentPointScopes() async throws { + let store = makeStore() + let order = try XCTUnwrap(store.orders.first) + let wholeModel = DroneMaterialsViewModel(store: store, orderID: order.id) + wholeModel.applyScenario(.ready) + let whole = DroneMaterialsViewController(viewModel: wholeModel) + let window = makeWindow(root: whole) + defer { close(window) } + try await waitForLibrary(whole, window: window) + let allRecordCount = wholeModel.sections.count + XCTAssertGreaterThan(wholeModel.filters.count, 2) + let filter = try XCTUnwrap(wholeModel.filters.first { $0.id != nil }) + let filterID = try XCTUnwrap(filter.id) + let list = try collection(in: whole.view, identifier: "drone.materials.list") + let filterIndex = try XCTUnwrap(wholeModel.filters.firstIndex { $0.id == filterID }) + select(list, item: filterIndex, section: 1) + try await settle(window) { wholeModel.selectedFilterID == filterID && wholeModel.sections.allSatisfy { $0.pointID == filterID } } + XCTAssertLessThan(wholeModel.sections.count, allRecordCount) + let selectedChip = try XCTUnwrap(find(in: whole.view, identifier: "drone.materials.filter.\(filterID)")) + XCTAssertTrue(selectedChip.accessibilityTraits.contains(.selected)) + assertLayout(in: whole.view) + + let preparation = DroneShootingPreparationViewModel(store: store, orderID: order.id) + XCTAssertEqual(preparation.admission, .ready) + XCTAssertFalse(preparation.summon()) + XCTAssertTrue(preparation.confirmSummon()) + let taskModel = DroneShootingTaskViewModel(store: store, orderID: order.id) + taskModel.applyScenario(.succeededReturning) + let pointID = try XCTUnwrap(taskModel.session?.point.id) + let unchangedOrder = taskModel.order + let unchangedTask = taskModel.session + let workbench = DroneDockWorkbenchViewController(viewModel: DroneDockWorkbenchViewModel(store: store)) + let navigation = try XCTUnwrap(whole.navigationController) + navigation.setViewControllers([workbench], animated: false) + let homeList = try collection(in: workbench.view, identifier: "drone.workbench.list") + try await settle(window) { homeList.numberOfSections > 2 && homeList.numberOfItems(inSection: 2) == 1 } + homeList.scrollToItem(at: IndexPath(item: 0, section: 2), at: .centeredVertically, animated: false) + try await settle(window) { self.find(in: workbench.view, identifier: "drone.home.\(order.id).primary") != nil } + try button(in: workbench.view, identifier: "drone.home.\(order.id).primary").sendActions(for: .touchUpInside) + try await settle(window) { navigation.topViewController is DroneShootingTaskViewController && navigation.transitionCoordinator == nil } + let task = try XCTUnwrap(navigation.topViewController as? DroneShootingTaskViewController) + try button(in: task.view, identifier: "drone.task.primary").sendActions(for: .touchUpInside) + try await settle(window) { navigation.topViewController is DroneMaterialsViewController && navigation.transitionCoordinator == nil } + let scoped = try XCTUnwrap(navigation.topViewController as? DroneMaterialsViewController) + try await waitForLibrary(scoped, window: window) + XCTAssertEqual(scoped.viewModel.pointID, pointID) + XCTAssertEqual(scoped.viewModel.selectedFilterID, pointID) + XCTAssertEqual(scoped.viewModel.filters.count, 1) + XCTAssertTrue(scoped.viewModel.sections.allSatisfy { $0.pointID == pointID }) + XCTAssertNil(find(in: scoped.view, identifier: "drone.materials.filter.all")) + XCTAssertTrue(visibleViews(in: scoped.view).contains { $0.accessibilityLabel?.contains("仅显示当前打卡点素材") == true }) + scoped.viewModel.selectFilter(id: nil) + XCTAssertEqual(scoped.viewModel.selectedFilterID, pointID) + XCTAssertEqual(store.shootingOrder(id: order.id), unchangedOrder) + XCTAssertEqual(store.shootingSession(orderID: order.id), unchangedTask) + assertLayout(in: scoped.view) + } + + /// 点击下载启动本地驱动并自动完成单文件,结果明确为演示且订单履约不变。 + func testDownloadButtonRunsLocalDemoDriverToSimulationCompletion() async throws { + let store = makeStore() + let order = try XCTUnwrap(store.orders.first) + let viewModel = DroneMaterialsViewModel(store: store, orderID: order.id) + viewModel.applyScenario(.ready) + let materialID = try XCTUnwrap(viewModel.previewMaterials.first?.id) + viewModel.toggleSelection(id: materialID) + let controller = DroneMaterialsViewController(viewModel: viewModel) + let window = makeWindow(root: controller) + defer { close(window) } + try await waitForLibrary(controller, window: window) + let download = try button(in: controller.view, identifier: "drone.materials.download") + XCTAssertTrue(download.isEnabled) + download.sendActions(for: .touchUpInside) + XCTAssertEqual(viewModel.batch?.itemIDs, [materialID]) + XCTAssertEqual(viewModel.downloadPhase, .downloading) + XCTAssertTrue(viewModel.isSelectionLocked) + assertLayout(in: controller.view) + capture(window, named: "素材流程-下载演示进行中") + + try await settle(window, timeout: 6) { viewModel.downloadPhase == .completed } + XCTAssertEqual(viewModel.material(id: materialID)?.downloadState, .completed(isSimulation: true)) + XCTAssertEqual(viewModel.completedCount, 1) + XCTAssertTrue(visibleViews(in: controller.view).compactMap { $0 as? UILabel }.contains { + $0.text?.contains("未写入系统相册") == true + }) + let selectMore = try button(in: controller.view, identifier: "drone.materials.continueSelecting") + XCTAssertTrue(selectMore.isEnabled) + XCTAssertEqual(store.shootingOrder(id: order.id), order) + assertLayout(in: controller.view) + capture(window, named: "素材流程-演示完成未写入相册") + } + + /// 后台立即停止驱动并作废旧令牌;前台保持暂停,手动继续只处理未完成项。 + func testBackgroundPausesAndForegroundRequiresManualContinueKeepingCompletedItems() async throws { + let store = makeStore() + let order = try XCTUnwrap(store.orders.first) + let viewModel = DroneMaterialsViewModel(store: store, orderID: order.id) + viewModel.applyScenario(.paused) + let completed = viewModel.sections.flatMap(\.materials).filter { $0.downloadState.isCompleted } + XCTAssertEqual(completed.count, 1) + let controller = DroneMaterialsViewController(viewModel: viewModel) + let window = makeWindow(root: controller) + defer { close(window) } + try await waitForLibrary(controller, window: window) + try button(in: controller.view, identifier: "drone.materials.continue").sendActions(for: .touchUpInside) + let oldBatch = try XCTUnwrap(viewModel.batch) + let pendingID = try XCTUnwrap(oldBatch.itemIDs.first { viewModel.material(id: $0)?.downloadState.isCompleted == false }) + NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) + let pausedBatch = try XCTUnwrap(viewModel.batch) + let pausedMaterials = viewModel.sections.flatMap(\.materials) + XCTAssertTrue(pausedBatch.isPaused) + XCTAssertEqual(pausedBatch.pauseReason, .background) + XCTAssertNotEqual(pausedBatch.id, oldBatch.id) + XCTAssertEqual(viewModel.downloadPhase, .paused) + viewModel.receive(.downloadCompleted, materialID: pendingID, batchID: oldBatch.id) + XCTAssertEqual(viewModel.sections.flatMap(\.materials), pausedMaterials) + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + try await Task.sleep(nanoseconds: 450_000_000) + XCTAssertEqual(viewModel.batch, pausedBatch) + XCTAssertEqual(viewModel.sections.flatMap(\.materials), pausedMaterials) + assertLayout(in: controller.view) + capture(window, named: "素材流程-后台暂停待手动继续") + + try button(in: controller.view, identifier: "drone.materials.continue").sendActions(for: .touchUpInside) + let continuedBatch = try XCTUnwrap(viewModel.batch) + XCTAssertFalse(continuedBatch.isPaused) + XCTAssertNotEqual(continuedBatch.id, pausedBatch.id) + XCTAssertEqual(continuedBatch.itemIDs, pausedBatch.itemIDs) + for material in completed { XCTAssertEqual(viewModel.material(id: material.id), material) } + XCTAssertEqual(viewModel.completedCount, completed.count) + XCTAssertEqual(viewModel.material(id: pendingID)?.downloadState, .downloading(progress: 0)) + NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) + XCTAssertEqual(store.shootingOrder(id: order.id), order) + } + + /// 重试仅重做失败项,执行时锁定选择;权限按钮只展示本地演示说明且恢复后不自动开始。 + func testRetryOnlyFailedItemsLocksSelectionAndPermissionRemainsDemoOnly() async throws { + let store = makeStore() + let order = try XCTUnwrap(store.orders.first) + let viewModel = DroneMaterialsViewModel(store: store, orderID: order.id) + viewModel.applyScenario(.partialFailure) + let completed = viewModel.sections.flatMap(\.materials).filter { $0.downloadState.isCompleted } + let failedIDs = Set(viewModel.sections.flatMap(\.materials).filter { $0.downloadState.isFailed }.map(\.id)) + let controller = DroneMaterialsViewController(viewModel: viewModel) + let window = makeWindow(root: controller) + defer { close(window) } + try await waitForLibrary(controller, window: window) + assertLayout(in: controller.view) + capture(window, named: "素材流程-部分失败仅重试失败项") + try button(in: controller.view, identifier: "drone.materials.retry").sendActions(for: .touchUpInside) + XCTAssertEqual(viewModel.failedCount, 0) + for material in completed { XCTAssertEqual(viewModel.material(id: material.id), material) } + XCTAssertEqual(Set(viewModel.sections.flatMap(\.materials).filter { $0.downloadState.isRunning }.map(\.id)), failedIDs) + let selectionBefore = viewModel.selectedIDs + let filterBefore = viewModel.selectedFilterID + let libraryList = try collection(in: controller.view, identifier: "drone.materials.list") + try await settle(window) { self.find(in: controller.view, identifier: "drone.materials.selectAll") != nil } + let selectAll = try button(in: controller.view, identifier: "drone.materials.selectAll") + XCTAssertFalse(selectAll.isEnabled) + selectAll.sendActions(for: .touchUpInside) + select(libraryList, item: 1, section: 1) + XCTAssertEqual(viewModel.selectedIDs, selectionBefore) + XCTAssertEqual(viewModel.selectedFilterID, filterBefore) + XCTAssertTrue(viewModel.isSelectionLocked) + NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) + + viewModel.applyScenario(.permissionDenied) + viewModel.selectAll() + let denied = DroneMaterialsViewController(viewModel: viewModel) + let navigation = try XCTUnwrap(controller.navigationController) + navigation.setViewControllers([denied], animated: false) + try await waitForLibrary(denied, window: window) + let deniedSelection = viewModel.selectedIDs + try button(in: denied.view, identifier: "drone.materials.permission").sendActions(for: .touchUpInside) + try await settle(window) { denied.presentedViewController is UIAlertController } + let alert = try XCTUnwrap(denied.presentedViewController as? UIAlertController) + XCTAssertEqual(alert.title, "相册权限演示") + XCTAssertTrue(alert.message?.contains("不读取或修改系统相册权限") == true) + XCTAssertEqual(viewModel.photoPermission, .denied) + XCTAssertEqual(viewModel.selectedIDs, deniedSelection) + XCTAssertNil(viewModel.batch) + alert.dismiss(animated: false) + viewModel.setPhotoPermission(.allowed) + let refresh = try XCTUnwrap(denied.navigationItem.rightBarButtonItems?.first) + let refreshAction = try XCTUnwrap(refresh.action) + XCTAssertTrue(UIApplication.shared.sendAction(refreshAction, to: refresh.target, from: refresh, for: nil)) + try await settle(window) { self.find(in: denied.view, identifier: "drone.materials.download") != nil } + XCTAssertNil(viewModel.batch) + XCTAssertEqual(viewModel.downloadPhase, .idle) + XCTAssertEqual(viewModel.selectedIDs, deniedSelection) + XCTAssertTrue(try button(in: denied.view, identifier: "drone.materials.download").isEnabled) + XCTAssertEqual(store.shootingOrder(id: order.id), order) + assertLayout(in: denied.view) + } + + /// 保留三条成功记录和一台设备,覆盖多点位素材且令工作台入口稳定可见。 + private func makeStore() -> DroneDockDemoStore { + let demo = DroneDockDemoStore() + return DroneDockDemoStore(context: .demo, orders: [demo.orders[0]], devices: Array(demo.devices.prefix(1))) + } + + private func makeWindow(root controller: UIViewController) -> UIWindow { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first + previousKeyWindow = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.frame = scene?.coordinateSpace.bounds ?? UIScreen.main.bounds + window.overrideUserInterfaceStyle = .light + window.rootViewController = UINavigationController(rootViewController: controller) + window.makeKeyAndVisible() + window.layoutIfNeeded() + return window + } + + private func close(_ window: UIWindow) { + NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil) + window.endEditing(true) + window.rootViewController?.dismiss(animated: false) + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + + /// 等待快照、导航和布局稳定;只在完成测试中允许较长的明确驱动等待。 + private func settle(_ window: UIWindow, timeout: TimeInterval = 4, until condition: () -> Bool) async throws { + let deadline = Date().addingTimeInterval(timeout) + while Date() < deadline { + window.layoutIfNeeded() + window.rootViewController?.view.layoutIfNeeded() + if condition() { + try await Task.sleep(nanoseconds: 250_000_000) + window.layoutIfNeeded() + return + } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTFail("素材流程未在预期时间内完成快照、导航或驱动回执") + throw NSError(domain: "DroneMaterialsFlowViewTests", code: 1) + } + + private func waitForLibrary(_ controller: DroneMaterialsViewController, window: UIWindow) async throws { + let list = try collection(in: controller.view, identifier: "drone.materials.list") + try await settle(window) { list.numberOfSections >= 4 && self.find(in: controller.view, identifier: "drone.materials.selectAll") != nil } + } + + /// 通过真实集合代理发送点位芯片选择,业务许可仍由页面与 ViewModel 执行。 + private func select(_ list: UICollectionView, item: Int, section: Int) { + let path = IndexPath(item: item, section: section) + guard section < list.numberOfSections, item < list.numberOfItems(inSection: section) else { + XCTFail("预期点位筛选不存在") + return + } + list.delegate?.collectionView?(list, didSelectItemAt: path) + } + + private func allViews(in root: UIView) -> [UIView] { [root] + root.subviews.flatMap { allViews(in: $0) } } + + private func visibleViews(in root: UIView) -> [UIView] { + allViews(in: root).filter { + !isHiddenByAncestor($0) && !$0.bounds.isEmpty && $0.convert($0.bounds, to: root).intersects(root.bounds) + } + } + + private func isHiddenByAncestor(_ view: UIView) -> Bool { + if view.isHidden || view.alpha < 0.01 { return true } + return view.superview.map { isHiddenByAncestor($0) } ?? false + } + + private func find(in root: UIView, identifier: String) -> UIView? { + allViews(in: root).first { $0.accessibilityIdentifier == identifier } + } + + private func button(in root: UIView, identifier: String) throws -> UIButton { + try XCTUnwrap(find(in: root, identifier: identifier) as? UIButton, "缺少按钮 \(identifier)") + } + + private func collection(in root: UIView, identifier: String) throws -> UICollectionView { + try XCTUnwrap(find(in: root, identifier: identifier) as? UICollectionView, "缺少列表 \(identifier)") + } + + /// 仅检查应用的可见约束视图,避免把 UIKit 私有子视图计为业务布局错误。 + private func assertLayout(in root: UIView, file: StaticString = #filePath, line: UInt = #line) { + let ambiguous = visibleViews(in: root).filter { + !$0.translatesAutoresizingMaskIntoConstraints && !String(describing: type(of: $0)).hasPrefix("_") && $0.hasAmbiguousLayout + } + XCTAssertTrue(ambiguous.isEmpty, "布局歧义:\(ambiguous.map { String(describing: type(of: $0)) + " " + ($0.accessibilityIdentifier ?? "") })", file: file, line: line) + } + + /// 所有关键状态画面始终保留在真机 xcresult 中。 + private func capture(_ window: UIWindow, named name: String) { + window.layoutIfNeeded() + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let attachment = XCTAttachment(image: image) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } +} +#endif diff --git a/suixinkanTests/DroneMaterialsViewModelTests.swift b/suixinkanTests/DroneMaterialsViewModelTests.swift new file mode 100644 index 0000000..a41e435 --- /dev/null +++ b/suixinkanTests/DroneMaterialsViewModelTests.swift @@ -0,0 +1,453 @@ +import XCTest +@testable import suixinkan + +/// 验证原素材分组、点位选择、前台下载与演示保存的独立状态规则。 +final class DroneMaterialsViewModelTests: XCTestCase { + func testRecordsAreNewestFirstAndUnshotOrderDoesNotInventMaterials() { + let store = makeStore(successful: 3) + let viewModel = DroneMaterialsViewModel(store: store, orderID: "order-a") + XCTAssertEqual(viewModel.sections.map(\.sequenceNumber), [3, 2, 1]) + XCTAssertEqual(viewModel.filters.first?.title, "全部点位") + XCTAssertEqual(viewModel.previewMaterials.count, 6) + + let unshot = DroneMaterialsViewModel(store: makeStore(successful: 0, materialState: .none), orderID: "order-a") + XCTAssertTrue(unshot.sections.isEmpty) + XCTAssertFalse(unshot.canStartDownload) + } + + func testRefreshingPreviouslyEmptyLibraryAppendsNewSuccessOnceWithoutConsumingQuota() { + let store = makeStore(successful: 0, materialState: .none) + let viewModel = DroneMaterialsViewModel(store: store, orderID: "order-a") + store.replaceShootingOrder(order(successful: 1, materialState: .uploading)) + viewModel.refresh() + viewModel.refresh() + XCTAssertEqual(viewModel.sections.count, 1) + XCTAssertTrue(viewModel.sections[0].materials.allSatisfy { $0.uploadState == .uploading }) + XCTAssertEqual(store.shootingOrder(id: "order-a")?.successfulShootingCount, 1) + XCTAssertEqual(store.shootingOrder(id: "order-a")?.remainingShootingCount, 4) + } + + func testPartiallyReadyAllowsOnlyReadyPreviewAndSelectAllUsesCurrentDownloadableItems() throws { + let store = makeStore(successful: 2, materialState: .partiallyReady) + let viewModel = DroneMaterialsViewModel(store: store, orderID: "order-a") + let uploading = try XCTUnwrap(viewModel.sections.flatMap(\.materials).first { $0.uploadState == .uploading }) + XCTAssertFalse(uploading.canPreview) + viewModel.toggleSelection(id: uploading.id) + XCTAssertEqual(viewModel.selectedCount, 0) + viewModel.selectAll() + XCTAssertEqual(viewModel.selectedIDs, viewModel.downloadableIDs) + XCTAssertEqual(viewModel.selectedCount, 3) + XCTAssertTrue(viewModel.isAllSelected) + XCTAssertEqual(viewModel.previewMaterials.count, 3) + viewModel.selectAll() + XCTAssertEqual(viewModel.selectedCount, 0) + XCTAssertFalse(viewModel.isAllSelected) + } + + func testUploadFailureAndUnavailableCannotPreviewOrSelect() { + let store = makeStore(successful: 1) + let viewModel = DroneMaterialsViewModel(store: store, orderID: "order-a") + mutateLibrary(store) { state in + state.records[0].materials[0].uploadState = .failed + state.records[0].materials[1].uploadState = .unavailable + } + viewModel.selectAll() + XCTAssertEqual(viewModel.selectedCount, 0) + XCTAssertTrue(viewModel.previewMaterials.isEmpty) + XCTAssertFalse(viewModel.isAllSelected) + } + + func testChangingPointFilterClearsSelectionAndFixedTaskScopeCannotExpand() throws { + let store = makeStore(successful: 3) + let wholeOrder = DroneMaterialsViewModel(store: store, orderID: "order-a") + wholeOrder.selectAll() + let pointID = try XCTUnwrap(wholeOrder.filters.dropFirst().first?.id) + wholeOrder.selectFilter(id: pointID) + XCTAssertEqual(wholeOrder.selectedCount, 0) + XCTAssertTrue(wholeOrder.sections.allSatisfy { $0.pointID == pointID }) + wholeOrder.selectAll() + XCTAssertEqual(wholeOrder.selectedCount, wholeOrder.sections.flatMap(\.materials).count) + + let taskScope = DroneMaterialsViewModel(store: store, orderID: "order-a", pointID: pointID) + XCTAssertEqual(taskScope.filters.count, 1) + taskScope.selectFilter(id: nil) + XCTAssertEqual(taskScope.selectedFilterID, pointID) + XCTAssertTrue(taskScope.sections.allSatisfy { $0.pointID == pointID }) + let other = try XCTUnwrap(wholeOrder.filters.first { $0.id != nil && $0.id != pointID }?.id) + taskScope.selectFilter(id: other) + XCTAssertEqual(taskScope.selectedFilterID, pointID) + } + + func testStartedBatchLocksSelectionAndPreviewRefreshPreservesSelectedItems() throws { + let viewModel = makeViewModel() + viewModel.selectAll() + let originalSelection = viewModel.selectedIDs + let originalFilter = viewModel.selectedFilterID + XCTAssertTrue(viewModel.startDownload()) + let batchID = try XCTUnwrap(viewModel.batch?.id) + viewModel.toggleSelection(id: try XCTUnwrap(originalSelection.first)) + viewModel.selectAll() + viewModel.selectFilter(id: "point-sanhuang") + viewModel.refresh() // Closing a preview returns through viewWillAppear. + XCTAssertTrue(viewModel.isSelectionLocked) + XCTAssertEqual(viewModel.selectedIDs, originalSelection) + XCTAssertEqual(viewModel.selectedCount, originalSelection.count) + XCTAssertEqual(viewModel.selectedFilterID, originalFilter) + XCTAssertEqual(viewModel.batch?.id, batchID) + XCTAssertFalse(viewModel.startDownload()) + XCTAssertEqual(viewModel.previewMaterials.count, 4) + } + + func testDownloadCompletionAndAlbumSaveAreSeparateAndDuplicateSuccessIsIgnored() throws { + let viewModel = makeViewModel(successful: 1) + let id = try XCTUnwrap(viewModel.downloadableIDs.first) + viewModel.toggleSelection(id: id) + XCTAssertTrue(viewModel.startDownload()) + let batchID = try XCTUnwrap(viewModel.batch?.id) + viewModel.receive(.saveSucceeded, materialID: id, batchID: batchID) + XCTAssertEqual(viewModel.completedCount, 0) + viewModel.receive(.downloadCompleted, materialID: id, batchID: batchID) + XCTAssertEqual(viewModel.material(id: id)?.downloadState, .awaitingSave) + XCTAssertEqual(viewModel.completedCount, 0) + viewModel.receive(.saveSucceeded, materialID: id, batchID: batchID) + XCTAssertEqual(viewModel.completedCount, 0) + viewModel.receive(.saveStarted, materialID: id, batchID: batchID) + viewModel.receive(.saveSucceeded, materialID: id, batchID: batchID) + viewModel.receive(.saveSucceeded, materialID: id, batchID: batchID) + viewModel.receive(.downloadFailed(message: "迟到失败"), materialID: id, batchID: batchID) + XCTAssertEqual(viewModel.material(id: id)?.downloadState, .completed(isSimulation: true)) + XCTAssertEqual(viewModel.material(id: id)?.statusTitle, "演示完成 · 未写入相册") + XCTAssertEqual(viewModel.completedCount, 1) + XCTAssertEqual(viewModel.batchProgress, 1) + XCTAssertEqual(viewModel.downloadPhase, .completed) + } + + func testProgressIsMonotonicClampedAndRejectsNonfiniteValues() throws { + let viewModel = makeViewModel(successful: 1) + viewModel.selectAll() + viewModel.startDownload() + let batch = try XCTUnwrap(viewModel.batch) + let id = try XCTUnwrap(batch.itemIDs.first) + viewModel.receive(.progress(0.6), materialID: id, batchID: batch.id) + viewModel.receive(.progress(0.1), materialID: id, batchID: batch.id) + viewModel.receive(.progress(.nan), materialID: id, batchID: batch.id) + XCTAssertEqual(viewModel.material(id: id)?.downloadState, .downloading(progress: 0.6)) + viewModel.receive(.progress(20), materialID: id, batchID: batch.id) + XCTAssertEqual(viewModel.material(id: id)?.downloadState, .downloading(progress: 1)) + XCTAssertEqual(viewModel.completedCount, 0) + } + + func testPauseInvalidatesOldCallbacksAndResumeRestartsOnlyUnfinishedFiles() throws { + let viewModel = makeViewModel(successful: 1) + viewModel.selectAll() + viewModel.startDownload() + let original = try XCTUnwrap(viewModel.batch) + let saved = original.itemIDs[0] + let unfinished = original.itemIDs[1] + finish(viewModel, id: saved, batchID: original.id) + viewModel.receive(.progress(0.7), materialID: unfinished, batchID: original.id) + viewModel.pauseDownloads(reason: .background) + let pausedID = try XCTUnwrap(viewModel.batch?.id) + XCTAssertNotEqual(pausedID, original.id) + XCTAssertEqual(viewModel.downloadPhase, .paused) + XCTAssertEqual(viewModel.material(id: unfinished)?.downloadState, .paused) + viewModel.receive(.downloadCompleted, materialID: unfinished, batchID: original.id) + viewModel.refresh() + XCTAssertEqual(viewModel.material(id: unfinished)?.downloadState, .paused) + XCTAssertEqual(viewModel.batch?.isPaused, true) + XCTAssertTrue(viewModel.continueDownload()) + let resumedID = try XCTUnwrap(viewModel.batch?.id) + XCTAssertNotEqual(resumedID, pausedID) + XCTAssertEqual(viewModel.material(id: unfinished)?.downloadState, .downloading(progress: 0)) + XCTAssertEqual(viewModel.material(id: saved)?.downloadState, .completed(isSimulation: true)) + viewModel.receive(.downloadCompleted, materialID: unfinished, batchID: original.id) + XCTAssertEqual(viewModel.material(id: unfinished)?.downloadState, .downloading(progress: 0)) + finish(viewModel, id: unfinished, batchID: resumedID) + XCTAssertEqual(viewModel.completedCount, 2) + } + + func testLockAndLeavingPageKeepCompletedFilesAndRequireManualContinue() throws { + for reason in [DroneMaterialPauseReason.locked, .leavingPage] { + let viewModel = makeViewModel(successful: 1) + viewModel.selectAll() + viewModel.startDownload() + let batch = try XCTUnwrap(viewModel.batch) + finish(viewModel, id: batch.itemIDs[0], batchID: batch.id) + if reason == .leavingPage { viewModel.leavePage() } else { viewModel.pauseDownloads(reason: reason) } + viewModel.refresh() + XCTAssertEqual(viewModel.batch?.pauseReason, reason) + XCTAssertEqual(viewModel.completedCount, 1) + XCTAssertEqual(viewModel.pendingCount, 1) + XCTAssertEqual(viewModel.downloadPhase, .paused) + XCTAssertTrue(viewModel.continueDownload()) + } + } + + func testPauseWhileSavingKeepsDownloadedFileAndResumeDoesNotDownloadAgain() throws { + let viewModel = makeViewModel(successful: 1) + let id = try XCTUnwrap(viewModel.downloadableIDs.first) + viewModel.toggleSelection(id: id) + viewModel.startDownload() + let batch = try XCTUnwrap(viewModel.batch) + viewModel.receive(.downloadCompleted, materialID: id, batchID: batch.id) + viewModel.receive(.saveStarted, materialID: id, batchID: batch.id) + viewModel.pauseDownloads(reason: .locked) + XCTAssertEqual(viewModel.material(id: id)?.downloadState, .awaitingSave) + XCTAssertTrue(viewModel.continueDownload()) + XCTAssertEqual(viewModel.material(id: id)?.downloadState, .awaitingSave) + let resumed = try XCTUnwrap(viewModel.batch?.id) + viewModel.receive(.saveStarted, materialID: id, batchID: resumed) + viewModel.receive(.saveSucceeded, materialID: id, batchID: resumed) + XCTAssertEqual(viewModel.completedCount, 1) + } + + func testRetryOnlyFailedItemsPreservesSuccessAndRejectsOldAttemptReceipt() throws { + let viewModel = makeViewModel(successful: 1) + viewModel.selectAll() + viewModel.startDownload() + let original = try XCTUnwrap(viewModel.batch) + let success = original.itemIDs[0] + let failure = original.itemIDs[1] + finish(viewModel, id: success, batchID: original.id) + viewModel.receive(.downloadFailed(message: "演示传输失败"), materialID: failure, batchID: original.id) + XCTAssertEqual(viewModel.downloadPhase, .partialFailure) + XCTAssertFalse(viewModel.startDownload()) + XCTAssertFalse(viewModel.continueDownload()) + XCTAssertTrue(viewModel.retryFailed()) + let retriedID = try XCTUnwrap(viewModel.batch?.id) + XCTAssertNotEqual(retriedID, original.id) + XCTAssertEqual(viewModel.material(id: success)?.downloadState, .completed(isSimulation: true)) + XCTAssertEqual(viewModel.material(id: failure)?.downloadState, .downloading(progress: 0)) + viewModel.receive(.downloadFailed(message: "旧批次失败"), materialID: failure, batchID: original.id) + XCTAssertEqual(viewModel.failedCount, 0) + finish(viewModel, id: failure, batchID: retriedID) + XCTAssertEqual(viewModel.completedCount, 2) + } + + func testContinueLeavesFailedItemsUntouchedUntilSeparateRetry() throws { + let viewModel = makeViewModel(successful: 1) + viewModel.selectAll() + viewModel.startDownload() + let original = try XCTUnwrap(viewModel.batch) + let failure = original.itemIDs[0] + let pending = original.itemIDs[1] + viewModel.receive(.downloadFailed(message: "演示失败"), materialID: failure, batchID: original.id) + viewModel.pauseDownloads(reason: .background) + XCTAssertFalse(viewModel.retryFailed()) + XCTAssertTrue(viewModel.continueDownload()) + let resumed = try XCTUnwrap(viewModel.batch?.id) + XCTAssertEqual(viewModel.material(id: failure)?.downloadState, .downloadFailed(message: "演示失败")) + finish(viewModel, id: pending, batchID: resumed) + XCTAssertTrue(viewModel.retryFailed()) + XCTAssertEqual(viewModel.material(id: pending)?.downloadState, .completed(isSimulation: true)) + } + + func testSaveFailureRetriesSaveWithoutMarkingSavedOrRedownloading() throws { + let viewModel = makeViewModel(successful: 1) + let id = try XCTUnwrap(viewModel.downloadableIDs.first) + viewModel.toggleSelection(id: id) + viewModel.startDownload() + let batch = try XCTUnwrap(viewModel.batch) + viewModel.receive(.downloadCompleted, materialID: id, batchID: batch.id) + viewModel.receive(.saveStarted, materialID: id, batchID: batch.id) + viewModel.receive(.saveFailed(message: "演示空间不足"), materialID: id, batchID: batch.id) + XCTAssertEqual(viewModel.completedCount, 0) + XCTAssertEqual(viewModel.failedCount, 1) + XCTAssertTrue(viewModel.retryFailed()) + XCTAssertEqual(viewModel.material(id: id)?.downloadState, .awaitingSave) + let retryID = try XCTUnwrap(viewModel.batch?.id) + viewModel.receive(.saveStarted, materialID: id, batchID: retryID) + viewModel.receive(.saveSucceeded, materialID: id, batchID: retryID) + XCTAssertEqual(viewModel.completedCount, 1) + } + + func testPermissionDeniedCreatesNoBatchAndPermissionRestoreDoesNotAutoStart() { + let viewModel = makeViewModel() + viewModel.selectAll() + let selected = viewModel.selectedIDs + viewModel.setPhotoPermission(.denied) + XCTAssertFalse(viewModel.startDownload()) + XCTAssertNil(viewModel.batch) + XCTAssertEqual(viewModel.failedCount, 0) + XCTAssertEqual(viewModel.selectedIDs, selected) + viewModel.setPhotoPermission(.allowed) + XCTAssertNil(viewModel.batch) + XCTAssertTrue(viewModel.startDownload()) + } + + func testPermissionRevokedWhileSavingPausesInsteadOfFakingFailureOrSuccess() throws { + let viewModel = makeViewModel(successful: 1) + let id = try XCTUnwrap(viewModel.downloadableIDs.first) + viewModel.toggleSelection(id: id) + viewModel.startDownload() + let batch = try XCTUnwrap(viewModel.batch) + viewModel.receive(.downloadCompleted, materialID: id, batchID: batch.id) + viewModel.receive(.saveStarted, materialID: id, batchID: batch.id) + viewModel.setPhotoPermission(.restricted) + viewModel.receive(.saveSucceeded, materialID: id, batchID: batch.id) + XCTAssertEqual(viewModel.material(id: id)?.downloadState, .awaitingSave) + XCTAssertEqual(viewModel.completedCount, 0) + XCTAssertEqual(viewModel.failedCount, 0) + XCTAssertEqual(viewModel.batch?.pauseReason, .permissionDenied) + XCTAssertFalse(viewModel.continueDownload()) + viewModel.setPhotoPermission(.allowed) + XCTAssertEqual(viewModel.downloadPhase, .paused) + XCTAssertTrue(viewModel.continueDownload()) + } + + func testCompletedItemsPersistOnReentryCannotBeSelectedAndDoNotImplyVisitorDelivery() throws { + let store = makeStore(successful: 1) + let viewModel = DroneMaterialsViewModel(store: store, orderID: "order-a") + let before = try XCTUnwrap(store.shootingOrder(id: "order-a")) + viewModel.selectAll() + viewModel.startDownload() + let batch = try XCTUnwrap(viewModel.batch) + for id in batch.itemIDs { finish(viewModel, id: id, batchID: batch.id) } + viewModel.clearBatch() + let reopened = DroneMaterialsViewModel(store: store, orderID: "order-a") + reopened.selectAll() + XCTAssertEqual(reopened.selectedCount, 0) + XCTAssertTrue(reopened.downloadableIDs.isEmpty) + XCTAssertEqual(reopened.previewMaterials.count, 2) + XCTAssertEqual(store.shootingOrder(id: "order-a"), before) + } + + func testOrdersAndScenicContextsRejectForeignBatchCallbacksAndKeepSeparateCaches() throws { + let store = makeStore(successful: 1, includeSecondOrder: true) + let first = DroneMaterialsViewModel(store: store, orderID: "order-a") + let second = DroneMaterialsViewModel(store: store, orderID: "order-b") + first.selectAll() + first.startDownload() + second.selectAll() + second.startDownload() + let firstBatch = try XCTUnwrap(first.batch) + let secondBatch = try XCTUnwrap(second.batch) + second.receive(.downloadCompleted, materialID: secondBatch.itemIDs[0], batchID: firstBatch.id) + XCTAssertEqual(second.material(id: secondBatch.itemIDs[0])?.downloadState, .downloading(progress: 0)) + store.switchContext(to: DroneDockContext(scenicID: "other", scenicName: "其他景区", userID: "user", photographerName: "工作人员")) + first.receive(.downloadCompleted, materialID: firstBatch.itemIDs[0], batchID: firstBatch.id) + XCTAssertNil(first.order) + XCTAssertTrue(first.sections.isEmpty) + first.refresh() + store.switchContext(to: context) + first.refresh() + XCTAssertEqual(first.downloadPhase, .paused) + XCTAssertEqual(first.material(id: firstBatch.itemIDs[0])?.downloadState, .paused) + XCTAssertEqual(second.batch?.id, secondBatch.id) + } + + func testFixedPointEntryPausesAndNarrowsRunningWholeOrderBatchPreservingHiddenResults() throws { + let store = makeStore(successful: 2) + let wholeOrder = DroneMaterialsViewModel(store: store, orderID: "order-a") + let target = wholeOrder.sections[0] + let other = wholeOrder.sections[1] + wholeOrder.selectAll() + XCTAssertTrue(wholeOrder.startDownload()) + let original = try XCTUnwrap(wholeOrder.batch) + let hiddenSaved = other.materials[0].id + let hiddenDownloaded = other.materials[1].id + finish(wholeOrder, id: hiddenSaved, batchID: original.id) + wholeOrder.receive(.downloadCompleted, materialID: hiddenDownloaded, batchID: original.id) + wholeOrder.receive(.saveStarted, materialID: hiddenDownloaded, batchID: original.id) + + let fixedPoint = DroneMaterialsViewModel(store: store, orderID: "order-a", pointID: target.pointID) + let narrowed = try XCTUnwrap(fixedPoint.batch) + XCTAssertNotEqual(narrowed.id, original.id) + XCTAssertEqual(Set(narrowed.itemIDs), Set(target.materials.map(\.id))) + XCTAssertEqual(fixedPoint.downloadPhase, .paused) + XCTAssertNil(fixedPoint.material(id: hiddenSaved)) + XCTAssertTrue(fixedPoint.continueDownload()) + let resumedID = try XCTUnwrap(fixedPoint.batch?.id) + for id in narrowed.itemIDs { finish(fixedPoint, id: id, batchID: resumedID) } + fixedPoint.clearBatch() + + wholeOrder.refresh() + XCTAssertEqual(wholeOrder.material(id: hiddenSaved)?.downloadState, .completed(isSimulation: true)) + XCTAssertEqual(wholeOrder.material(id: hiddenDownloaded)?.downloadState, .awaitingSave) + XCTAssertEqual(wholeOrder.downloadableIDs, Set([hiddenDownloaded])) + XCTAssertEqual(wholeOrder.selectedIDs, Set([hiddenDownloaded])) + XCTAssertTrue(wholeOrder.isAllSelected) + XCTAssertTrue(wholeOrder.startDownload()) + XCTAssertEqual(wholeOrder.material(id: hiddenDownloaded)?.downloadState, .awaitingSave) + wholeOrder.receive(.saveSucceeded, materialID: hiddenDownloaded, batchID: original.id) + XCTAssertEqual(wholeOrder.material(id: hiddenDownloaded)?.downloadState, .awaitingSave) + } + + func testFixedPointEntryWithNoBatchIntersectionClearsBatchAndKeepsOtherPointPaused() throws { + let store = makeStore(successful: 2) + let wholeOrder = DroneMaterialsViewModel(store: store, orderID: "order-a") + let other = wholeOrder.sections[0] + let target = wholeOrder.sections[1] + wholeOrder.selectFilter(id: other.pointID) + wholeOrder.selectAll() + XCTAssertTrue(wholeOrder.startDownload()) + let original = try XCTUnwrap(wholeOrder.batch) + wholeOrder.pauseDownloads(reason: .background) + + let fixedPoint = DroneMaterialsViewModel(store: store, orderID: "order-a", pointID: target.pointID) + XCTAssertNil(fixedPoint.batch) + XCTAssertFalse(fixedPoint.continueDownload()) + XCTAssertFalse(fixedPoint.isSelectionLocked) + XCTAssertTrue(fixedPoint.sections.allSatisfy { $0.pointID == target.pointID }) + XCTAssertTrue(original.itemIDs.allSatisfy { wholeOrder.material(id: $0)?.downloadState == .paused }) + fixedPoint.selectAll() + XCTAssertTrue(fixedPoint.startDownload()) + XCTAssertTrue(Set(try XCTUnwrap(fixedPoint.batch?.itemIDs)).isDisjoint(with: Set(original.itemIDs))) + } + + func testFixedPointEntryNarrowsPausedBatchAndKeepsItsAlreadyCompletedFile() throws { + let store = makeStore(successful: 2) + let wholeOrder = DroneMaterialsViewModel(store: store, orderID: "order-a") + let target = wholeOrder.sections[0] + let hidden = wholeOrder.sections[1].materials.map(\.id) + wholeOrder.selectAll() + wholeOrder.startDownload() + let original = try XCTUnwrap(wholeOrder.batch) + finish(wholeOrder, id: target.materials[0].id, batchID: original.id) + wholeOrder.pauseDownloads(reason: .background) + let fixedPoint = DroneMaterialsViewModel(store: store, orderID: "order-a", pointID: target.pointID) + XCTAssertEqual(fixedPoint.completedCount, 1) + XCTAssertEqual(fixedPoint.pendingCount, 1) + XCTAssertEqual(fixedPoint.batchTotalCount, 2) + XCTAssertTrue(fixedPoint.continueDownload()) + XCTAssertEqual(fixedPoint.material(id: target.materials[0].id)?.downloadState, .completed(isSimulation: true)) + XCTAssertEqual(fixedPoint.material(id: target.materials[1].id)?.downloadState, .downloading(progress: 0)) + XCTAssertTrue(hidden.allSatisfy { wholeOrder.material(id: $0)?.downloadState == .paused }) + } + + private var context: DroneDockContext { + DroneDockContext(scenicID: "scenic", scenicName: "测试景区", userID: "user", photographerName: "工作人员") + } + + private func order(id: String = "order-a", successful: Int, materialState: DroneShootingMaterialState = .ready) -> DroneShootingOrder { + DroneShootingOrder(id: id, scenicID: context.scenicID, assignedUserID: context.userID, + customerName: "游客136****2806", orderNumber: "TEST-\(id)", createdAtText: "10-23 09:00", + packageName: "航拍套餐", totalShootingCount: 5, successfulShootingCount: successful, + activeTask: nil, needsRepreparation: false, materialState: materialState, + deliveredVideoCount: 0, visitorConfirmationState: .none) + } + + private func makeStore(successful: Int, materialState: DroneShootingMaterialState = .ready, + includeSecondOrder: Bool = false) -> DroneDockDemoStore { + var orders = [order(successful: successful, materialState: materialState)] + if includeSecondOrder { orders.append(order(id: "order-b", successful: successful, materialState: materialState)) } + return DroneDockDemoStore(context: context, orders: orders, devices: []) + } + + private func makeViewModel(successful: Int = 2) -> DroneMaterialsViewModel { + DroneMaterialsViewModel(store: makeStore(successful: successful), orderID: "order-a") + } + + private func mutateLibrary(_ store: DroneDockDemoStore, update: (inout DroneMaterialLibraryState) -> Void) { + let key = DroneShootingSessionKey(context: context, orderID: "order-a") + guard var state = store.materialLibraries[key] else { return XCTFail("缺少本地素材库") } + update(&state) + store.materialLibraries[key] = state + } + + private func finish(_ viewModel: DroneMaterialsViewModel, id: String, batchID: UUID) { + viewModel.receive(.downloadCompleted, materialID: id, batchID: batchID) + viewModel.receive(.saveStarted, materialID: id, batchID: batchID) + viewModel.receive(.saveSucceeded, materialID: id, batchID: batchID) + } +}