556 lines
27 KiB
Swift
556 lines
27 KiB
Swift
import Foundation
|
||
|
||
/// 独立景区空境库的正式分页、筛选、选择与下载状态,同时支持本地演示;不依赖 UIKit 或机巢业务。
|
||
final class ScenicMaterialsViewModel {
|
||
/// 正式模式使用网络素材与真实相册保存,预览模式使用本地演示。
|
||
let isRemote: Bool
|
||
/// 本次页面的独立账号与景区范围。
|
||
let context: ScenicMaterialContext
|
||
/// 用于筛选的日历及其时区。
|
||
let calendar: Calendar
|
||
/// 默认保留天数,正式模式采用服务端回显的窗口。
|
||
private(set) var retentionDays = 90
|
||
/// 日期筛选首日;正式模式包含后端返回的第 90 天,演示模式包含今天共 90 天。
|
||
private(set) var minimumDate: Date
|
||
/// 可选的最后一天零点,不允许选择未来日期。
|
||
let maximumDate: Date
|
||
/// 当前景区的独立空镜航线,含暂无片段的航线。
|
||
private(set) var routes: [ScenicMaterialRoute]
|
||
/// 当前已加载的批次;正式模式按服务端分页追加。
|
||
private(set) var allGroups: [ScenicMaterialGroup]
|
||
/// 选择的航线标识,nil 代表全部航线。
|
||
private(set) var selectedRouteID: String?
|
||
/// 已应用的日历日筛选范围,nil 代表全部保留期。
|
||
private(set) var dateRange: ScenicMaterialDateRange?
|
||
/// 选择的未完成片段,不包含不可用或已完成文件。
|
||
private(set) var selectedIDs = Set<String>()
|
||
/// 需要展开超过五段的批次标识。
|
||
private(set) var expandedGroupIDs = Set<String>()
|
||
/// 当前下载演示阶段。
|
||
private(set) var phase: ScenicMaterialDownloadPhase = .idle
|
||
/// 当前传输尝试的令牌;暂停、继续和重试会作废旧令牌。
|
||
private(set) var batchID: UUID?
|
||
/// 本次下载完整范围,重试时仍保留已完成项用于展示进度。
|
||
private(set) var batchItemIDs: [String] = []
|
||
/// 当前页面已完成演示的片段;不等于写入系统相册。
|
||
private(set) var completedIDs = Set<String>()
|
||
/// 当前批次明确失败的片段,可单独重试。
|
||
private(set) var failedIDs = Set<String>()
|
||
/// 当前批次的逐项演示进度。
|
||
private(set) var progressByID: [String: Double] = [:]
|
||
|
||
/// 正在刷新第一页及其片段详情。
|
||
private(set) var isLoading = false
|
||
/// 正在读取下一页及其片段详情。
|
||
private(set) var isLoadingMore = false
|
||
/// 下一页加载失败时保留已展示内容,由用户重试。
|
||
private(set) var loadMoreError: String?
|
||
/// 当前筛选在后端的场次总数。
|
||
private(set) var remoteTotalCount = 0
|
||
/// 已加载的去重场次数,不将同页重复项计为新内容。
|
||
var loadedRemoteSessionCount: Int { isRemote ? allGroups.count : 0 }
|
||
/// 首次成功加载后,是否仍有未读取的场次。
|
||
var hasMoreRemoteSessions: Bool {
|
||
isRemote && loadedRemotePage > 0 && loadedRemoteSessionCount < remoteTotalCount
|
||
}
|
||
/// 第一页请求、详情或字段校验失败时的可重试提示。
|
||
private(set) var loadError: String?
|
||
/// 最近收到的完整场次响应,解析失败时仍供诊断,不代表已提交到页面。
|
||
private(set) var remoteSessions: ScenicMaterialsSessionsResponse?
|
||
/// 素材保留说明优先使用后端返回的文案。
|
||
private(set) var retentionTips = "素材保留 90 天,请及时下载"
|
||
private var loadID: UUID?
|
||
private var loadedRemotePage = 0
|
||
private var loadedRemoteQuery: ScenicMaterialsQuery?
|
||
|
||
private let initialGroups: [ScenicMaterialGroup]
|
||
|
||
/// 创建正式或演示库;可注入日历、日期和数据,测试不依赖时间、网络或登录单例。
|
||
init(context: ScenicMaterialContext = .demo, now: Date = Date(), calendar: Calendar = .current,
|
||
routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil, isRemote: Bool = false) {
|
||
self.isRemote = isRemote
|
||
self.context = context
|
||
self.calendar = calendar
|
||
maximumDate = calendar.startOfDay(for: now)
|
||
minimumDate = calendar.date(byAdding: .day, value: isRemote ? -retentionDays : -(retentionDays - 1), to: maximumDate) ?? maximumDate
|
||
let demoRoutes = isRemote ? [] : Self.makeRoutes(context: context)
|
||
self.routes = routes ?? demoRoutes
|
||
let data = groups ?? (isRemote ? [] : Self.makeGroups(context: context, routes: demoRoutes, today: maximumDate, calendar: calendar))
|
||
initialGroups = data
|
||
allGroups = data
|
||
}
|
||
|
||
/// 按航线及拍摄时间排序;正式范围遵守服务端查询,演示数据再按本地保留期筛选。
|
||
var filteredGroups: [ScenicMaterialGroup] {
|
||
let routeOrder = Dictionary(routes.enumerated().map { ($0.element.id, $0.offset) }, uniquingKeysWith: { first, _ in first })
|
||
return allGroups.filter { group in
|
||
guard routeOrder[group.routeID] != nil else { return false }
|
||
let day = calendar.startOfDay(for: group.capturedAt)
|
||
// 正式保留范围由接口执行,避免再次按本地日界限删掉后端已返回的边界场次。
|
||
guard isRemote || (day >= minimumDate && day <= maximumDate) else { return false }
|
||
if let selectedRouteID, group.routeID != selectedRouteID { return false }
|
||
if let dateRange, day < dateRange.start || day > dateRange.end { return false }
|
||
return true
|
||
}.sorted { lhs, rhs in
|
||
let left = routeOrder[lhs.routeID] ?? 0
|
||
let right = routeOrder[rhs.routeID] ?? 0
|
||
if left != right { return left < right }
|
||
if lhs.capturedAt != rhs.capturedAt { return lhs.capturedAt > rhs.capturedAt }
|
||
return lhs.id < rhs.id
|
||
}
|
||
}
|
||
|
||
/// 当前筛选范围内完整片段,包含 UI 折叠的部分。
|
||
var filteredClips: [ScenicMaterialClip] { filteredGroups.flatMap(\.clips) }
|
||
/// 任何批次尚未清理时锁定选择与筛选,避免改变正在展示的批次范围。
|
||
var isSelectionLocked: Bool { batchID != nil }
|
||
/// 尚未开始传输且有可选片段时可以下载。
|
||
var canStartDownload: Bool { !isSelectionLocked && !isLoading && !isLoadingMore && !selectedIDs.isEmpty }
|
||
/// 当前选择数量。
|
||
var selectedCount: Int { selectedIDs.count }
|
||
/// 当前批次总项数。
|
||
var totalCount: Int { batchItemIDs.count }
|
||
/// 当前批次成功演示项数,不混入此前批次结果。
|
||
var completedCount: Int { batchItemIDs.filter { completedIDs.contains($0) }.count }
|
||
/// 当前批次失败项数。
|
||
var failedCount: Int { batchItemIDs.filter { failedIDs.contains($0) }.count }
|
||
/// 当前批次仍待处理的完整片段标识。
|
||
var pendingIDs: [String] { batchItemIDs.filter { !completedIDs.contains($0) && !failedIDs.contains($0) } }
|
||
/// 按文件数量平均的演示进度,成功项始终计为 1。
|
||
var downloadProgress: Double {
|
||
guard !batchItemIDs.isEmpty else { return 0 }
|
||
return batchItemIDs.reduce(0) { sum, id in
|
||
sum + (completedIDs.contains(id) ? 1 : progressByID[id, default: 0])
|
||
} / Double(batchItemIDs.count)
|
||
}
|
||
/// 当前航线筛选标题。
|
||
var routeFilterTitle: String { selectedRouteID.flatMap { route(id: $0)?.name } ?? "全部航线" }
|
||
/// 当前日期筛选标题。
|
||
var dateFilterTitle: String {
|
||
guard let dateRange else { return "全部时间" }
|
||
let start = formatDate(dateRange.start, format: "MM.dd")
|
||
let end = formatDate(dateRange.end, format: "MM.dd")
|
||
return dateRange.start == dateRange.end ? start : "\(start) – \(end)"
|
||
}
|
||
/// 当前景区保留期内是否存在片段,不受用户筛选条件影响。
|
||
var hasAnyMaterials: Bool {
|
||
allGroups.contains { group in
|
||
let day = calendar.startOfDay(for: group.capturedAt)
|
||
return !group.clips.isEmpty && (isRemote || (day >= minimumDate && day <= maximumDate))
|
||
&& routes.contains(where: { $0.id == group.routeID })
|
||
}
|
||
}
|
||
/// 当前空态标题,区分全库为空与有筛选但无结果。
|
||
var emptyTitle: String {
|
||
if isLoading { return "正在加载素材" }
|
||
if loadError != nil { return "素材加载失败" }
|
||
return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "没有符合条件的素材" : "暂无景区素材"
|
||
}
|
||
/// 当前空态说明。
|
||
var emptyMessage: String {
|
||
if isLoading { return "请稍候" }
|
||
if let loadError { return loadError }
|
||
return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里"
|
||
}
|
||
|
||
/// 刷新当前筛选第一页,并读取该页完整片段;详情失败时整页可重试,不混入演示数据。
|
||
func loadRemoteSessions(api: any ScenicMaterialsServing) async {
|
||
guard isRemote, !isSelectionLocked else { return }
|
||
resetRemotePageState()
|
||
let requestID = UUID()
|
||
loadID = requestID
|
||
defer { if loadID == requestID { isLoading = false } }
|
||
isLoading = true
|
||
let query = remoteQuery(page: 1)
|
||
do {
|
||
let response = try await api.sessions(query: query)
|
||
guard loadID == requestID, !Task.isCancelled else { return }
|
||
remoteSessions = response
|
||
let sessions = try ScenicMaterialsRemoteMapper.sessions(from: response, scenicID: query.scenicID, calendar: calendar)
|
||
let mappedRoutes = try ScenicMaterialsRemoteMapper.routes(from: response)
|
||
if response.total > 0 && sessions.isEmpty {
|
||
throw APIError.decodeFailed("场次总数与列表不一致,请刷新重试")
|
||
}
|
||
let groups = try await Self.loadGroups(sessions: sessions, api: api)
|
||
guard loadID == requestID, !Task.isCancelled, remoteQuery(page: 1) == query else { return }
|
||
allGroups = groups
|
||
routes = Self.mergedRoutes(mappedRoutes, sessions: sessions)
|
||
applyRemoteMetadata(response)
|
||
loadedRemotePage = response.page
|
||
loadedRemoteQuery = query
|
||
} catch is CancellationError {
|
||
} catch {
|
||
guard loadID == requestID, !Task.isCancelled else { return }
|
||
loadError = error.localizedDescription
|
||
}
|
||
}
|
||
|
||
/// 使用已成功加载的查询追加下一页,失败不清空已展示页面或选择状态。
|
||
func loadMoreRemoteSessions(api: any ScenicMaterialsServing) async {
|
||
guard isRemote, !isSelectionLocked, !isLoading, !isLoadingMore, hasMoreRemoteSessions,
|
||
loadedRemoteQuery == remoteQuery(page: 1) else { return }
|
||
let requestID = UUID()
|
||
loadID = requestID
|
||
isLoadingMore = true
|
||
loadMoreError = nil
|
||
let query = remoteQuery(page: loadedRemotePage + 1)
|
||
defer { if loadID == requestID { isLoadingMore = false } }
|
||
do {
|
||
let response = try await api.sessions(query: query)
|
||
guard loadID == requestID, !Task.isCancelled else { return }
|
||
remoteSessions = response
|
||
let sessions = try ScenicMaterialsRemoteMapper.sessions(from: response, scenicID: query.scenicID, calendar: calendar)
|
||
let mappedRoutes = try ScenicMaterialsRemoteMapper.routes(from: response)
|
||
let existingIDs = Set(allGroups.map(\.id))
|
||
let newSessions = sessions.filter { !existingIDs.contains(String($0.id)) }
|
||
guard !newSessions.isEmpty || response.total <= loadedRemoteSessionCount else {
|
||
throw APIError.decodeFailed("后续场次为空或重复,请刷新重试")
|
||
}
|
||
let groups = try await Self.loadGroups(sessions: newSessions, api: api)
|
||
guard loadID == requestID, !Task.isCancelled, loadedRemoteQuery == remoteQuery(page: 1) else { return }
|
||
allGroups.append(contentsOf: groups)
|
||
routes = Self.mergedRoutes(routes + mappedRoutes, sessions: sessions)
|
||
applyRemoteMetadata(response)
|
||
loadedRemotePage = response.page
|
||
} catch is CancellationError {
|
||
} catch {
|
||
guard loadID == requestID, !Task.isCancelled else { return }
|
||
loadMoreError = error.localizedDescription
|
||
}
|
||
}
|
||
|
||
/// 同一时刻最多请求四个场次详情,返回顺序始终与列表一致。
|
||
private static func loadGroups(sessions: [ScenicMaterialsRemoteSession], api: any ScenicMaterialsServing) async throws -> [ScenicMaterialGroup] {
|
||
try await withThrowingTaskGroup(of: (Int, ScenicMaterialGroup).self) { tasks in
|
||
var nextIndex = 0
|
||
var groups: [Int: ScenicMaterialGroup] = [:]
|
||
func enqueue(_ index: Int) {
|
||
let session = sessions[index]
|
||
tasks.addTask {
|
||
try Task.checkCancellation()
|
||
let detail = try await api.sessionDetail(scenicMediaID: session.id)
|
||
try Task.checkCancellation()
|
||
return (index, try ScenicMaterialsRemoteMapper.group(session: session, detail: detail))
|
||
}
|
||
}
|
||
while nextIndex < min(4, sessions.count) {
|
||
enqueue(nextIndex)
|
||
nextIndex += 1
|
||
}
|
||
while let (index, group) = try await tasks.next() {
|
||
groups[index] = group
|
||
if nextIndex < sessions.count {
|
||
enqueue(nextIndex)
|
||
nextIndex += 1
|
||
}
|
||
}
|
||
return (0..<sessions.count).compactMap { groups[$0] }
|
||
}
|
||
}
|
||
|
||
/// 航线选项优先使用独立筛选集合,列表中的真实航线可补足集合。
|
||
private static func mergedRoutes(_ routes: [ScenicMaterialRoute], sessions: [ScenicMaterialsRemoteSession]) -> [ScenicMaterialRoute] {
|
||
var seen = Set<String>()
|
||
return (routes + sessions.map { ScenicMaterialRoute(id: $0.routeID, name: $0.routeName) })
|
||
.filter { seen.insert($0.id).inserted }
|
||
}
|
||
|
||
/// 保持页码之外的查询范围一致,翻页时不丢失航线和日期条件。
|
||
private func remoteQuery(page: Int) -> ScenicMaterialsQuery {
|
||
ScenicMaterialsQuery(scenicID: Int(context.scenicID) ?? 0, page: page,
|
||
airLineID: selectedRouteID.flatMap(Int.init),
|
||
dateFrom: dateRange.map { formatDate($0.start, format: "yyyy-MM-dd") },
|
||
dateTo: dateRange.map { formatDate($0.end, format: "yyyy-MM-dd") }, retentionDays: retentionDays)
|
||
}
|
||
|
||
/// 正式日期下界包含后端已实测返回的第 90 天,不改变演示日历窗口。
|
||
private func applyRemoteMetadata(_ response: ScenicMaterialsSessionsResponse) {
|
||
retentionDays = response.retentionDays
|
||
retentionTips = response.retentionTips
|
||
remoteTotalCount = response.total
|
||
minimumDate = calendar.date(byAdding: .day, value: -retentionDays, to: maximumDate) ?? maximumDate
|
||
}
|
||
|
||
/// 刷新或筛选更换后作废旧请求、旧页码及选择,保留航线选项供筛选使用。
|
||
private func resetRemotePageState() {
|
||
cancelRemoteLoad()
|
||
loadedRemotePage = 0
|
||
loadedRemoteQuery = nil
|
||
remoteTotalCount = 0
|
||
remoteSessions = nil
|
||
loadError = nil
|
||
loadMoreError = nil
|
||
allGroups.removeAll()
|
||
selectedIDs.removeAll()
|
||
expandedGroupIDs.removeAll()
|
||
}
|
||
|
||
/// 离页或身份变化后作废尚未返回的列表请求。
|
||
func cancelRemoteLoad() {
|
||
loadID = nil
|
||
isLoading = false
|
||
isLoadingMore = false
|
||
}
|
||
|
||
/// 查找稳定航线,不依赖名称。
|
||
func route(id: String) -> ScenicMaterialRoute? { routes.first { $0.id == id } }
|
||
/// 查找完整批次,不受折叠影响。
|
||
func group(id: String) -> ScenicMaterialGroup? { allGroups.first { $0.id == id } }
|
||
/// 查找当前库片段,不扩大页面上下文。
|
||
func clip(id: String) -> ScenicMaterialClip? { allGroups.lazy.flatMap(\.clips).first { $0.id == id } }
|
||
|
||
/// 返回列表当前应显示的片段;默认显示首五段。
|
||
func visibleClips(in group: ScenicMaterialGroup) -> [ScenicMaterialClip] {
|
||
expandedGroupIDs.contains(group.id) ? group.clips : Array(group.clips.prefix(5))
|
||
}
|
||
|
||
/// 格式化批次拍摄时间,使用同一日历时区。
|
||
func capturedAtText(for group: ScenicMaterialGroup) -> String { formatDate(group.capturedAt, format: "MM-dd HH:mm") }
|
||
|
||
/// 切换航线后移除隐藏选择,传入未知航线不会更改现有状态。
|
||
@discardableResult
|
||
func setRoute(id: String?) -> Bool {
|
||
guard !isSelectionLocked, id == nil || routes.contains(where: { $0.id == id }) else { return false }
|
||
selectedRouteID = id
|
||
if isRemote { resetRemotePageState() }
|
||
pruneSelection()
|
||
return true
|
||
}
|
||
|
||
/// 应用包含首尾两天的范围;两端均 nil 表示全部,非法或越界日期保持原值。
|
||
@discardableResult
|
||
func setDateRange(start: Date?, end: Date?) -> Bool {
|
||
guard !isSelectionLocked else { return false }
|
||
if start == nil && end == nil {
|
||
dateRange = nil
|
||
if isRemote { resetRemotePageState() }
|
||
pruneSelection()
|
||
return true
|
||
}
|
||
guard let start, let end else { return false }
|
||
let first = calendar.startOfDay(for: start)
|
||
let last = calendar.startOfDay(for: end)
|
||
guard first >= minimumDate, last <= maximumDate, first <= last else { return false }
|
||
dateRange = ScenicMaterialDateRange(start: first, end: last)
|
||
if isRemote { resetRemotePageState() }
|
||
pruneSelection()
|
||
return true
|
||
}
|
||
|
||
/// 清除筛选,保留仍有效的已选片段,不改变下载结果。
|
||
func resetFilters() {
|
||
guard !isSelectionLocked else { return }
|
||
selectedRouteID = nil
|
||
dateRange = nil
|
||
if isRemote { resetRemotePageState() }
|
||
pruneSelection()
|
||
}
|
||
|
||
/// 当前可选状态;完成、不可用、隐藏片段或锁定批次均不可新选。
|
||
func canSelect(id: String) -> Bool {
|
||
!isSelectionLocked && filteredClips.contains { $0.id == id && $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains(id) }
|
||
}
|
||
|
||
/// 切换单项选择,不涉及预览或下载。
|
||
func toggleSelection(id: String) {
|
||
guard canSelect(id: id) else { return }
|
||
if !selectedIDs.insert(id).inserted { selectedIDs.remove(id) }
|
||
}
|
||
|
||
/// 完整批次内所有可选片段是否都已选中,不把空组视为全选。
|
||
func isGroupSelected(id: String) -> Bool {
|
||
let ids = selectableIDs(in: id)
|
||
return !ids.isEmpty && ids.isSubset(of: selectedIDs)
|
||
}
|
||
|
||
/// 全选或取消全选本组;包含未展开片段,排除已完成与不可用项。
|
||
func toggleGroup(id: String) {
|
||
guard !isSelectionLocked else { return }
|
||
let ids = selectableIDs(in: id)
|
||
if !ids.isEmpty && ids.isSubset(of: selectedIDs) { selectedIDs.subtract(ids) }
|
||
else { selectedIDs.formUnion(ids) }
|
||
}
|
||
|
||
/// 展开/收起只改变布局,下载过程中也可浏览,不改变选择和批次。
|
||
func toggleExpandedGroup(id: String) {
|
||
guard filteredGroups.contains(where: { $0.id == id }) else { return }
|
||
if !expandedGroupIDs.insert(id).inserted { expandedGroupIDs.remove(id) }
|
||
}
|
||
|
||
/// 获取当前片段的本机展示状态;成功仅表示本地演示完成。
|
||
func downloadState(for id: String) -> ScenicMaterialDownloadState {
|
||
guard let clip = clip(id: id), clip.isAvailable else { return .unavailable }
|
||
if completedIDs.contains(id) { return .completed }
|
||
if failedIDs.contains(id) { return .failed }
|
||
guard batchItemIDs.contains(id) else { return .available }
|
||
if phase == .paused { return .paused }
|
||
if phase == .downloading { return .downloading(progress: progressByID[id, default: 0]) }
|
||
return .available
|
||
}
|
||
|
||
/// 冻结当前可选范围并开启一轮下载演示,返回是否成功建立批次。
|
||
@discardableResult
|
||
func startDownload() -> Bool {
|
||
guard canStartDownload else { return false }
|
||
let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }
|
||
guard !items.isEmpty else { return false }
|
||
batchItemIDs = items.map(\.id)
|
||
selectedIDs = Set(batchItemIDs)
|
||
failedIDs.removeAll()
|
||
progressByID = Dictionary(uniqueKeysWithValues: batchItemIDs.map { ($0, 0) })
|
||
batchID = UUID()
|
||
phase = .downloading
|
||
return true
|
||
}
|
||
|
||
/// 暂停当前演示并作废旧驱动回执,回前台不自动继续。
|
||
func pauseDownload() {
|
||
guard phase == .downloading else { return }
|
||
batchID = UUID()
|
||
phase = .paused
|
||
}
|
||
|
||
/// 手动继续未完成项,允许未完成文件从头演示,已完成项不重复处理。
|
||
@discardableResult
|
||
func continueDownload() -> Bool {
|
||
guard phase == .paused, !pendingIDs.isEmpty else { return false }
|
||
for id in pendingIDs { progressByID[id] = 0 }
|
||
batchID = UUID()
|
||
phase = .downloading
|
||
return true
|
||
}
|
||
|
||
/// 仅重新处理明确失败的项,成功项及原批次范围保留。
|
||
@discardableResult
|
||
func retryFailedDownloads() -> Bool {
|
||
guard phase == .partialFailure, !failedIDs.isEmpty else { return false }
|
||
for id in failedIDs { progressByID[id] = 0 }
|
||
failedIDs.removeAll()
|
||
batchID = UUID()
|
||
phase = .downloading
|
||
return true
|
||
}
|
||
|
||
/// 取消当前批次并清理未完成项;已成功的本机演示标记继续保留。
|
||
func cancelDownload() { clearBatch() }
|
||
|
||
/// 终态后开始重新选择;传输或暂停中的批次需先继续或取消。
|
||
func continueSelecting() {
|
||
guard phase != .downloading, phase != .paused else { return }
|
||
clearBatch()
|
||
}
|
||
|
||
/// 只接收当前传输令牌的未终结项,拒绝旧批次、重复终态及无效进度。
|
||
func receive(_ event: ScenicMaterialTransferEvent, clipID: String, batchID: UUID) {
|
||
guard self.batchID == batchID, phase == .downloading, batchItemIDs.contains(clipID),
|
||
!completedIDs.contains(clipID), !failedIDs.contains(clipID), clip(id: clipID)?.isAvailable == true else { return }
|
||
switch event {
|
||
case .progress(let value):
|
||
guard value.isFinite else { return }
|
||
progressByID[clipID] = max(progressByID[clipID, default: 0], min(max(value, 0), 1))
|
||
case .completed:
|
||
completedIDs.insert(clipID)
|
||
progressByID[clipID] = 1
|
||
case .failed:
|
||
failedIDs.insert(clipID)
|
||
progressByID[clipID] = 0
|
||
}
|
||
guard pendingIDs.isEmpty else { return }
|
||
phase = failedIDs.isEmpty ? .completed : .partialFailure
|
||
selectedIDs = failedIDs
|
||
}
|
||
|
||
/// 切换本地状态预览,不读取真实相册,也不更改登录身份或订单。
|
||
func applyScenario(_ scenario: ScenicMaterialsScenario) {
|
||
guard !isRemote else { return }
|
||
clearBatch()
|
||
completedIDs.removeAll()
|
||
allGroups = initialGroups
|
||
selectedRouteID = nil
|
||
dateRange = nil
|
||
expandedGroupIDs.removeAll()
|
||
switch scenario {
|
||
case .normal: break
|
||
case .empty: allGroups = []
|
||
case .noResults:
|
||
selectedRouteID = routes.first(where: { route in !allGroups.contains(where: { $0.routeID == route.id }) })?.id
|
||
if selectedRouteID == nil {
|
||
dateRange = ScenicMaterialDateRange(start: maximumDate, end: maximumDate)
|
||
}
|
||
case .selected, .downloading, .completed, .partialFailure, .paused:
|
||
let items = Array(filteredClips.filter(\.isAvailable).prefix(2))
|
||
selectedIDs = Set(items.map(\.id))
|
||
guard scenario != .selected, startDownload(), let token = batchID else { return }
|
||
if scenario == .downloading {
|
||
if let item = items.first { receive(.progress(0.35), clipID: item.id, batchID: token) }
|
||
} else if scenario == .completed {
|
||
for item in items { receive(.completed, clipID: item.id, batchID: token) }
|
||
} else if scenario == .partialFailure {
|
||
for (index, item) in items.enumerated() {
|
||
receive(index == 0 ? .completed : .failed, clipID: item.id, batchID: token)
|
||
}
|
||
} else {
|
||
if let item = items.first, items.count > 1 { receive(.completed, clipID: item.id, batchID: token) }
|
||
pauseDownload()
|
||
}
|
||
}
|
||
}
|
||
|
||
private func selectableIDs(in groupID: String) -> Set<String> {
|
||
guard let group = filteredGroups.first(where: { $0.id == groupID }) else { return [] }
|
||
return Set(group.clips.filter { $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }.map(\.id))
|
||
}
|
||
|
||
private func pruneSelection() {
|
||
let valid = Set(filteredClips.filter { $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }.map(\.id))
|
||
selectedIDs.formIntersection(valid)
|
||
}
|
||
|
||
private func clearBatch() {
|
||
batchID = nil
|
||
batchItemIDs = []
|
||
selectedIDs.removeAll()
|
||
failedIDs.removeAll()
|
||
progressByID.removeAll()
|
||
phase = .idle
|
||
}
|
||
|
||
private func formatDate(_ date: Date, format: String) -> String {
|
||
let formatter = DateFormatter()
|
||
formatter.calendar = calendar
|
||
formatter.timeZone = calendar.timeZone
|
||
formatter.locale = Locale(identifier: "zh_CN")
|
||
formatter.dateFormat = format
|
||
return formatter.string(from: date)
|
||
}
|
||
|
||
private static func makeRoutes(context: ScenicMaterialContext) -> [ScenicMaterialRoute] {
|
||
let prefix = "\(context.userID):\(context.scenicID)"
|
||
return [
|
||
ScenicMaterialRoute(id: "\(prefix):route-1", name: "共眠岸 → 三皇寨 → 好汉坡"),
|
||
ScenicMaterialRoute(id: "\(prefix):route-2", name: "少林寺 → 塔林 → 达摩洞"),
|
||
ScenicMaterialRoute(id: "\(prefix):route-3", name: "少室山 → 迎客峰")
|
||
]
|
||
}
|
||
|
||
private static func makeGroups(context: ScenicMaterialContext, routes: [ScenicMaterialRoute], today: Date,
|
||
calendar: Calendar) -> [ScenicMaterialGroup] {
|
||
let prefix = "\(context.userID):\(context.scenicID)"
|
||
let configurations = [(0, 3, 17, 20, 5), (0, 3, 14, 30, 6), (0, 4, 16, 10, 3), (1, 3, 10, 40, 4), (1, 16, 15, 35, 5)]
|
||
let durations = [28, 27, 30, 24, 31, 26]
|
||
let covers = ["drone_demo_mountain", "drone_demo_pagoda", "drone_demo_mountain", "drone_demo_pagoda", "drone_demo_mountain", "drone_demo_pagoda"]
|
||
return configurations.enumerated().map { index, configuration in
|
||
let (routeIndex, daysAgo, hour, minute, count) = configuration
|
||
let day = calendar.date(byAdding: .day, value: -daysAgo, to: today) ?? today
|
||
let capturedAt = calendar.date(bySettingHour: hour, minute: minute, second: 0, of: day) ?? day
|
||
let groupID = "\(prefix):group-\(index + 1)"
|
||
let clips = (0..<count).map { clipIndex in
|
||
ScenicMaterialClip(id: "\(groupID):clip-\(clipIndex + 1)", groupID: groupID, ordinal: clipIndex + 1,
|
||
durationSeconds: durations[clipIndex], fileSizeBytes: Int64(178 + clipIndex * 12) * 1_000_000,
|
||
resolution: "4K", coverAssetName: covers[clipIndex])
|
||
}
|
||
return ScenicMaterialGroup(id: groupID, routeID: routes[routeIndex].id, capturedAt: capturedAt, clips: clips)
|
||
}
|
||
}
|
||
}
|