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 }