feat(scenic-materials): 搭建独立景区空镜库UI与下载演示
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
import Foundation
|
||||
|
||||
/// 景区空镜库的独立访问上下文,不依赖拍摄订单、机巢或无人机任务。
|
||||
struct ScenicMaterialContext: Hashable, Sendable {
|
||||
/// 当前账号标识,用于隔离本机演示状态。
|
||||
let userID: String
|
||||
/// 当前景区稳定标识。
|
||||
let scenicID: String
|
||||
/// 当前景区的展示名称。
|
||||
let scenicName: String
|
||||
|
||||
/// 创建空镜库上下文;不会改写 App 的真实登录或景区会话。
|
||||
init(userID: String, scenicID: String, scenicName: String) {
|
||||
self.userID = userID
|
||||
self.scenicID = scenicID
|
||||
self.scenicName = scenicName
|
||||
}
|
||||
|
||||
/// 仅供独立页面预览的演示身份。
|
||||
static let demo = ScenicMaterialContext(userID: "scenic-demo-user", scenicID: "scenic-demo-songshan", scenicName: "嵩山少林景区")
|
||||
}
|
||||
|
||||
/// 景区空镜航线,不以名称匹配游客拍摄航线。
|
||||
struct ScenicMaterialRoute: Hashable, Sendable {
|
||||
/// 航线稳定标识。
|
||||
let id: String
|
||||
/// 航线展示名称。
|
||||
let name: String
|
||||
|
||||
/// 创建可供筛选的独立空镜航线。
|
||||
init(id: String, name: String) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
}
|
||||
}
|
||||
|
||||
/// 一次空镜拍摄批次;完整片段列表独立于 UI 是否折叠。
|
||||
struct ScenicMaterialGroup: Hashable, Sendable {
|
||||
/// 批次稳定标识。
|
||||
let id: String
|
||||
/// 所属空镜航线标识。
|
||||
let routeID: String
|
||||
/// 批次拍摄时间,用于日期筛选和航线内排序。
|
||||
let capturedAt: Date
|
||||
/// 批次完整片段列表,整组选择包含未展开片段。
|
||||
let clips: [ScenicMaterialClip]
|
||||
|
||||
/// 创建一组完整空镜片段。
|
||||
init(id: String, routeID: String, capturedAt: Date, clips: [ScenicMaterialClip]) {
|
||||
self.id = id
|
||||
self.routeID = routeID
|
||||
self.capturedAt = capturedAt
|
||||
self.clips = clips
|
||||
}
|
||||
}
|
||||
|
||||
/// 单个空镜视频片段的内容元数据;下载演示状态另由 ViewModel 管理。
|
||||
struct ScenicMaterialClip: Hashable, Sendable {
|
||||
/// 在当前访问上下文中稳定且唯一的片段标识。
|
||||
let id: String
|
||||
/// 所属拍摄批次标识。
|
||||
let groupID: String
|
||||
/// 组内从 1 开始的片段序号。
|
||||
let ordinal: Int
|
||||
/// 原片段展示时长;本地播放器使用独立演示视频。
|
||||
let durationSeconds: Int
|
||||
/// 原片段展示大小,单位为字节。
|
||||
let fileSizeBytes: Int64
|
||||
/// 原片段分辨率展示值。
|
||||
let resolution: String
|
||||
/// 本地演示封面资源名。
|
||||
let coverAssetName: String
|
||||
/// 文件是否仍可预览和下载;不可用文件仍可展示其元数据。
|
||||
let isAvailable: Bool
|
||||
|
||||
/// 创建片段元数据,不读取本地相册或请求网络。
|
||||
init(id: String, groupID: String, ordinal: Int, durationSeconds: Int, fileSizeBytes: Int64,
|
||||
resolution: String, coverAssetName: String, isAvailable: Bool = true) {
|
||||
self.id = id
|
||||
self.groupID = groupID
|
||||
self.ordinal = ordinal
|
||||
self.durationSeconds = durationSeconds
|
||||
self.fileSizeBytes = fileSizeBytes
|
||||
self.resolution = resolution
|
||||
self.coverAssetName = coverAssetName
|
||||
self.isAvailable = isAvailable
|
||||
}
|
||||
|
||||
/// 用于封面与预览信息的分秒时长。
|
||||
var durationText: String {
|
||||
let value = max(durationSeconds, 0)
|
||||
return String(format: "%02d:%02d", value / 60, value % 60)
|
||||
}
|
||||
|
||||
/// 使用十进制 MB 展示片段大小,避免将原文件与本地示例文件混淆。
|
||||
var sizeText: String {
|
||||
let megabytes = Double(max(fileSizeBytes, 0)) / 1_000_000
|
||||
return megabytes.rounded() == megabytes ? String(format: "%.0fMB", megabytes) : String(format: "%.1fMB", megabytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// 已规范化到日历日的闭区间筛选范围。
|
||||
struct ScenicMaterialDateRange: Hashable, Sendable {
|
||||
/// 起始日的零点,包含该日全部记录。
|
||||
let start: Date
|
||||
/// 结束日的零点,包含该日全部记录。
|
||||
let end: Date
|
||||
|
||||
/// 由 ViewModel 校验并规范化日期后创建。
|
||||
init(start: Date, end: Date) {
|
||||
self.start = start
|
||||
self.end = end
|
||||
}
|
||||
}
|
||||
|
||||
/// 本机批量下载演示的阶段,不代表服务器或系统相册已完成操作。
|
||||
enum ScenicMaterialDownloadPhase: String, Hashable, Sendable {
|
||||
case idle, downloading, paused, partialFailure, completed
|
||||
}
|
||||
|
||||
/// 单个演示片段的本机状态,供列表显示,不写入服务端素材模型。
|
||||
enum ScenicMaterialDownloadState: Hashable, Sendable {
|
||||
case available
|
||||
case downloading(progress: Double)
|
||||
case paused
|
||||
case failed
|
||||
case completed
|
||||
case unavailable
|
||||
}
|
||||
|
||||
/// 演示驱动对当前批次单项的回执;所有成功只表示本地 UI 演示完成。
|
||||
enum ScenicMaterialTransferEvent: Sendable {
|
||||
case progress(Double)
|
||||
case completed
|
||||
case failed
|
||||
}
|
||||
|
||||
/// 独立空镜库的可复现演示场景,不改变真实权限、订单或设备状态。
|
||||
enum ScenicMaterialsScenario: String, CaseIterable, Sendable {
|
||||
case normal, selected, downloading, completed, partialFailure, paused, empty, noResults
|
||||
|
||||
/// Debug 状态菜单的展示名称。
|
||||
var title: String {
|
||||
switch self {
|
||||
case .normal: "正常素材列表"
|
||||
case .selected: "已选两段"
|
||||
case .downloading: "下载中"
|
||||
case .completed: "下载演示完成"
|
||||
case .partialFailure: "部分下载失败"
|
||||
case .paused: "下载已暂停"
|
||||
case .empty: "暂无景区素材"
|
||||
case .noResults: "筛选无结果"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
import Foundation
|
||||
|
||||
/// 独立景区空镜库的筛选、选择和前台下载演示逻辑;不依赖 UIKit 或机巢业务。
|
||||
final class ScenicMaterialsViewModel {
|
||||
/// 本次页面的独立账号与景区范围。
|
||||
let context: ScenicMaterialContext
|
||||
/// 用于筛选的日历及其时区。
|
||||
let calendar: Calendar
|
||||
/// 本地演示保留天数,正式对接后由服务端配置决定。
|
||||
let retentionDays = 90
|
||||
/// 保留期首日零点,包含今天一共 90 个日历日。
|
||||
let 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 let initialGroups: [ScenicMaterialGroup]
|
||||
|
||||
/// 创建演示库;可注入日历、日期和数据,测试不依赖时间、网络或登录单例。
|
||||
init(context: ScenicMaterialContext = .demo, now: Date = Date(), calendar: Calendar = .current,
|
||||
routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil) {
|
||||
self.context = context
|
||||
self.calendar = calendar
|
||||
maximumDate = calendar.startOfDay(for: now)
|
||||
minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate
|
||||
let demoRoutes = Self.makeRoutes(context: context)
|
||||
self.routes = routes ?? demoRoutes
|
||||
let data = groups ?? 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 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 && !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 && day >= minimumDate && day <= maximumDate
|
||||
&& routes.contains(where: { $0.id == group.routeID })
|
||||
}
|
||||
}
|
||||
/// 当前空态标题,区分全库为空与有筛选但无结果。
|
||||
var emptyTitle: String { hasAnyMaterials ? "没有符合条件的素材" : "暂无景区素材" }
|
||||
/// 当前空态说明。
|
||||
var emptyMessage: String {
|
||||
hasAnyMaterials ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里"
|
||||
}
|
||||
|
||||
/// 查找稳定航线,不依赖名称。
|
||||
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
|
||||
pruneSelection()
|
||||
return true
|
||||
}
|
||||
|
||||
/// 应用包含首尾两天的范围;两端均 nil 表示全部,非法或越界日期保持原值。
|
||||
@discardableResult
|
||||
func setDateRange(start: Date?, end: Date?) -> Bool {
|
||||
guard !isSelectionLocked else { return false }
|
||||
if start == nil && end == nil {
|
||||
dateRange = nil
|
||||
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)
|
||||
pruneSelection()
|
||||
return true
|
||||
}
|
||||
|
||||
/// 清除筛选,保留仍有效的已选片段,不改变下载结果。
|
||||
func resetFilters() {
|
||||
guard !isSelectionLocked else { return }
|
||||
selectedRouteID = nil
|
||||
dateRange = nil
|
||||
pruneSelection()
|
||||
}
|
||||
|
||||
/// 当前可选状态;完成、不可用、隐藏片段或锁定批次均不可新选。
|
||||
func canSelect(id: String) -> Bool {
|
||||
!isSelectionLocked && filteredClips.contains { $0.id == id && $0.isAvailable && !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 !isSelectionLocked else { return false }
|
||||
let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && !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) {
|
||||
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 && !completedIDs.contains($0.id) }.map(\.id))
|
||||
}
|
||||
|
||||
private func pruneSelection() {
|
||||
let valid = Set(filteredClips.filter { $0.isAvailable && !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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,8 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
|
||||
self.window = window
|
||||
(UIApplication.shared.delegate as? AppDelegate)?.window = window
|
||||
#if DEBUG
|
||||
if let preview = DroneDockPreview.navigationController(arguments: ProcessInfo.processInfo.arguments) {
|
||||
if let preview = ScenicMaterialsPreview.navigationController(arguments: ProcessInfo.processInfo.arguments)
|
||||
?? DroneDockPreview.navigationController(arguments: ProcessInfo.processInfo.arguments) {
|
||||
window.rootViewController = preview
|
||||
window.makeKeyAndVisible()
|
||||
return
|
||||
|
||||
@@ -59,9 +59,10 @@ final class AllFunctionsViewController: BaseViewController {
|
||||
override func setupNavigationBar() {
|
||||
title = "全部功能"
|
||||
#if DEBUG
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "机巢预览", style: .plain, target: self, action: #selector(openDroneDockPreview)
|
||||
)
|
||||
navigationItem.rightBarButtonItems = [
|
||||
UIBarButtonItem(title: "空镜预览", style: .plain, target: self, action: #selector(openScenicMaterialsPreview)),
|
||||
UIBarButtonItem(title: "机巢预览", style: .plain, target: self, action: #selector(openDroneDockPreview))
|
||||
]
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -69,6 +70,11 @@ final class AllFunctionsViewController: BaseViewController {
|
||||
@objc private func openDroneDockPreview() {
|
||||
navigationController?.pushViewController(DroneDockWorkbenchViewController(), animated: true)
|
||||
}
|
||||
|
||||
/// 空镜库作为独立模块预览,不经机巢工作台导航或业务状态。
|
||||
@objc private func openScenicMaterialsPreview() {
|
||||
navigationController?.pushViewController(ScenicMaterialsViewController(), animated: true)
|
||||
}
|
||||
#endif
|
||||
|
||||
override func setupUI() {
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 景区素材模块的局部样式,可独立于机巢业务使用。
|
||||
@MainActor
|
||||
enum ScenicMaterialsStyle {
|
||||
static let primary = UIColor(hex: 0x3164FF)
|
||||
static let background = UIColor.white
|
||||
static let text = UIColor(hex: 0x20242C)
|
||||
static let secondary = UIColor(hex: 0x9297A1)
|
||||
static let border = UIColor(hex: 0xECEEF2)
|
||||
static let success = UIColor(hex: 0x17986A)
|
||||
static let warning = UIColor(hex: 0xD98926)
|
||||
|
||||
/// 创建模块内使用的系统字体标签。
|
||||
static func label(_ text: String? = nil, size: CGFloat = 14, weight: UIFont.Weight = .regular,
|
||||
color: UIColor? = nil) -> UILabel {
|
||||
let label = UILabel()
|
||||
label.text = text
|
||||
label.font = .systemFont(ofSize: size, weight: weight)
|
||||
label.textColor = color ?? ScenicMaterialsStyle.text
|
||||
return label
|
||||
}
|
||||
}
|
||||
|
||||
/// 视频封面底部渐变,只用于保证白色元信息在照片上的对比度。
|
||||
@MainActor
|
||||
private final class ScenicMaterialGradientView: UIView {
|
||||
override class var layerClass: AnyClass { CAGradientLayer.self }
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
isUserInteractionEnabled = false
|
||||
if let gradient = layer as? CAGradientLayer {
|
||||
gradient.colors = [UIColor.clear.cgColor, UIColor.black.withAlphaComponent(0.68).cgColor]
|
||||
gradient.locations = [0, 1]
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
}
|
||||
|
||||
/// 景区空镜片段卡,预览和选择分别命中,下载期间仍可预览。
|
||||
@MainActor
|
||||
final class ScenicMaterialClipCell: UICollectionViewCell {
|
||||
/// 请求预览当前片段,不改变选择状态。
|
||||
var onPreview: (() -> Void)?
|
||||
/// 请求切换当前片段的勾选状态。
|
||||
var onToggleSelection: (() -> Void)?
|
||||
|
||||
private let cover = UIImageView()
|
||||
private let previewButton = UIButton(type: .custom)
|
||||
private let selectionButton = UIButton(type: .custom)
|
||||
private let ordinalLabel = ScenicMaterialsStyle.label(size: 11, color: .white)
|
||||
private let metadataLabel = ScenicMaterialsStyle.label(size: 11, color: .white)
|
||||
private let statusLabel = ScenicMaterialsStyle.label(size: 10, weight: .medium, color: .white)
|
||||
private let progressView = UIProgressView(progressViewStyle: .bar)
|
||||
|
||||
/// 创建圆角图片卡和独立的四十四点选择命中区。
|
||||
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()
|
||||
onPreview = nil
|
||||
onToggleSelection = nil
|
||||
cover.image = nil
|
||||
progressView.isHidden = true
|
||||
statusLabel.isHidden = true
|
||||
}
|
||||
|
||||
/// 显示片段及本机演示传输状态;首段大图额外显示分辨率和体积。
|
||||
func configure(clip: ScenicMaterialClip, selected: Bool, isSelectionEnabled: Bool,
|
||||
statusText: String? = nil, progress: Double? = nil, isHero: Bool = false) {
|
||||
cover.image = UIImage(named: clip.coverAssetName)
|
||||
ordinalLabel.text = String(format: "片段 %02d", clip.ordinal)
|
||||
metadataLabel.text = isHero ? "\(clip.durationText) · \(clip.resolution) · \(clip.sizeText)" : clip.durationText
|
||||
metadataLabel.font = .monospacedDigitSystemFont(ofSize: isHero ? 11 : 10, weight: .regular)
|
||||
selectionButton.setImage(UIImage(systemName: selected ? "checkmark.circle.fill" : "circle",
|
||||
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22, weight: .regular)), for: .normal)
|
||||
selectionButton.tintColor = selected ? ScenicMaterialsStyle.primary : .white
|
||||
selectionButton.isEnabled = isSelectionEnabled
|
||||
selectionButton.alpha = isSelectionEnabled ? 1 : 0.45
|
||||
selectionButton.accessibilityIdentifier = "scenic.materials.select.\(clip.id)"
|
||||
selectionButton.accessibilityLabel = "\(selected ? "取消选择" : "选择")片段\(clip.ordinal)"
|
||||
selectionButton.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
if !isSelectionEnabled { selectionButton.accessibilityTraits.insert(.notEnabled) }
|
||||
previewButton.accessibilityIdentifier = "scenic.materials.preview.\(clip.id)"
|
||||
previewButton.accessibilityLabel = "预览片段\(clip.ordinal),\(clip.durationText)"
|
||||
previewButton.isEnabled = clip.isAvailable
|
||||
statusLabel.text = statusText.map { " \($0) " }
|
||||
statusLabel.isHidden = statusText == nil
|
||||
statusLabel.backgroundColor = statusText?.contains("失败") == true
|
||||
? ScenicMaterialsStyle.warning.withAlphaComponent(0.95)
|
||||
: ScenicMaterialsStyle.primary.withAlphaComponent(0.88)
|
||||
progressView.isHidden = progress == nil
|
||||
progressView.progress = Float(min(max(progress ?? 0, 0), 1))
|
||||
accessibilityIdentifier = "scenic.materials.clip.\(clip.id)"
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
contentView.backgroundColor = UIColor(hex: 0xE9EDF4)
|
||||
contentView.layer.cornerRadius = 10
|
||||
contentView.layer.cornerCurve = .continuous
|
||||
contentView.clipsToBounds = true
|
||||
cover.contentMode = .scaleAspectFill
|
||||
cover.clipsToBounds = true
|
||||
previewButton.setImage(UIImage(systemName: "play.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 24)), for: .normal)
|
||||
previewButton.tintColor = .white
|
||||
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
|
||||
selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
|
||||
statusLabel.layer.cornerRadius = 5
|
||||
statusLabel.clipsToBounds = true
|
||||
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
ordinalLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
metadataLabel.textAlignment = .right
|
||||
metadataLabel.minimumScaleFactor = 0.85
|
||||
metadataLabel.adjustsFontSizeToFitWidth = true
|
||||
progressView.progressTintColor = ScenicMaterialsStyle.primary
|
||||
progressView.trackTintColor = .white.withAlphaComponent(0.4)
|
||||
let gradient = ScenicMaterialGradientView()
|
||||
gradient.tag = 701
|
||||
[cover, previewButton, gradient, ordinalLabel, metadataLabel, statusLabel, selectionButton, progressView].forEach(contentView.addSubview)
|
||||
}
|
||||
|
||||
private func setupConstraints() {
|
||||
cover.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
previewButton.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
contentView.viewWithTag(701)?.snp.makeConstraints {
|
||||
$0.leading.trailing.bottom.equalToSuperview()
|
||||
$0.height.equalTo(55)
|
||||
}
|
||||
selectionButton.snp.makeConstraints { $0.top.leading.equalToSuperview(); $0.size.equalTo(44) }
|
||||
statusLabel.snp.makeConstraints {
|
||||
$0.top.trailing.equalToSuperview().inset(9)
|
||||
$0.leading.greaterThanOrEqualTo(selectionButton.snp.trailing).offset(2)
|
||||
$0.height.equalTo(22)
|
||||
}
|
||||
ordinalLabel.snp.makeConstraints { $0.leading.bottom.equalToSuperview().inset(9) }
|
||||
metadataLabel.snp.makeConstraints {
|
||||
$0.trailing.bottom.equalToSuperview().inset(9)
|
||||
$0.leading.greaterThanOrEqualTo(ordinalLabel.snp.trailing).offset(5)
|
||||
}
|
||||
progressView.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview(); $0.height.equalTo(3) }
|
||||
}
|
||||
|
||||
@objc private func previewTapped() { onPreview?() }
|
||||
@objc private func selectionTapped() { onToggleSelection?() }
|
||||
}
|
||||
|
||||
/// 航线与拍摄批次标题,整组勾选由 ViewModel 决定完整片段范围。
|
||||
@MainActor
|
||||
final class ScenicMaterialGroupHeaderView: UICollectionReusableView {
|
||||
/// 请求勾选或取消本组全部可选片段。
|
||||
var onToggleGroup: (() -> Void)?
|
||||
private let routeLabel = ScenicMaterialsStyle.label(size: 17, weight: .semibold)
|
||||
private let timeLabel = ScenicMaterialsStyle.label(size: 11, color: ScenicMaterialsStyle.secondary)
|
||||
private let groupButton = UIButton(type: .system)
|
||||
|
||||
/// 创建可复用的航线标题和批次选择行。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
routeLabel.numberOfLines = 2
|
||||
routeLabel.accessibilityTraits = .header
|
||||
timeLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
|
||||
groupButton.addTarget(self, action: #selector(groupTapped), for: .touchUpInside)
|
||||
addSubview(routeLabel)
|
||||
addSubview(timeLabel)
|
||||
addSubview(groupButton)
|
||||
routeLabel.snp.makeConstraints {
|
||||
$0.leading.trailing.equalToSuperview()
|
||||
$0.top.equalToSuperview().offset(10)
|
||||
$0.bottom.lessThanOrEqualTo(groupButton.snp.top).offset(-4)
|
||||
}
|
||||
timeLabel.snp.makeConstraints {
|
||||
$0.leading.equalToSuperview()
|
||||
$0.centerY.equalTo(groupButton)
|
||||
$0.trailing.lessThanOrEqualTo(groupButton.snp.leading).offset(-6)
|
||||
}
|
||||
groupButton.snp.makeConstraints {
|
||||
$0.trailing.equalToSuperview()
|
||||
$0.bottom.equalToSuperview()
|
||||
$0.height.equalTo(44)
|
||||
$0.width.greaterThanOrEqualTo(88)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() { super.prepareForReuse(); onToggleGroup = nil }
|
||||
|
||||
/// 首组显示航线标题,后续同航线批次仅显示时间和数量。
|
||||
func configure(groupID: String, routeName: String?, timeTitle: String, count: Int,
|
||||
isSelected: Bool, canSelect: Bool) {
|
||||
routeLabel.text = routeName
|
||||
routeLabel.isHidden = routeName == nil
|
||||
routeLabel.snp.remakeConstraints {
|
||||
$0.leading.trailing.equalToSuperview()
|
||||
if routeName == nil {
|
||||
$0.top.equalToSuperview()
|
||||
$0.height.equalTo(0)
|
||||
} else {
|
||||
$0.top.equalToSuperview().offset(10)
|
||||
$0.bottom.lessThanOrEqualTo(groupButton.snp.top).offset(-4)
|
||||
}
|
||||
}
|
||||
timeLabel.text = "\(timeTitle) · \(count) 段素材"
|
||||
var configuration = UIButton.Configuration.plain()
|
||||
configuration.title = "选择本组"
|
||||
configuration.image = UIImage(systemName: isSelected ? "checkmark.circle.fill" : "circle")
|
||||
configuration.imagePadding = 5
|
||||
configuration.contentInsets = .zero
|
||||
configuration.baseForegroundColor = isSelected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
|
||||
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
|
||||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { input in
|
||||
var output = input
|
||||
output.font = .systemFont(ofSize: 11)
|
||||
return output
|
||||
}
|
||||
groupButton.configuration = configuration
|
||||
groupButton.isEnabled = canSelect
|
||||
groupButton.accessibilityIdentifier = "scenic.materials.group.\(groupID)"
|
||||
groupButton.accessibilityLabel = "\(isSelected ? "取消选择本组" : "选择本组"),\(timeTitle),\(count)段"
|
||||
groupButton.accessibilityTraits = isSelected ? [.button, .selected] : .button
|
||||
if !canSelect { groupButton.accessibilityTraits.insert(.notEnabled) }
|
||||
}
|
||||
|
||||
@objc private func groupTapped() { onToggleGroup?() }
|
||||
}
|
||||
|
||||
/// 展开或收起同一拍摄批次中默认折叠的片段。
|
||||
@MainActor
|
||||
final class ScenicMaterialExpandCell: UICollectionViewCell {
|
||||
/// 切换本组片段展示范围,选择范围不随折叠改变。
|
||||
var onToggleExpanded: (() -> Void)?
|
||||
private let button = UIButton(type: .system)
|
||||
|
||||
/// 创建居中的轻量展开按钮。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
button.tintColor = ScenicMaterialsStyle.secondary
|
||||
button.titleLabel?.font = .systemFont(ofSize: 12)
|
||||
button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
|
||||
contentView.addSubview(button)
|
||||
button.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() { super.prepareForReuse(); onToggleExpanded = nil }
|
||||
|
||||
/// 显示展开余量或收起文案。
|
||||
func configure(groupID: String, title: String) {
|
||||
button.setTitle(title, for: .normal)
|
||||
button.setImage(UIImage(systemName: title.contains("收起") ? "chevron.up" : "chevron.down"), for: .normal)
|
||||
button.semanticContentAttribute = .forceRightToLeft
|
||||
button.accessibilityIdentifier = "scenic.materials.expand.\(groupID)"
|
||||
}
|
||||
|
||||
@objc private func tapped() { onToggleExpanded?() }
|
||||
}
|
||||
|
||||
/// 固定底部的选择/下载摘要,不直接持有 ViewModel 或执行文件操作。
|
||||
@MainActor
|
||||
final class ScenicMaterialsFooterView: UIView {
|
||||
/// 当前阶段的主要操作,例如下载、继续或重试。
|
||||
var onPrimaryTap: (() -> Void)?
|
||||
/// 当前阶段的次要操作,例如取消或继续选择。
|
||||
var onSecondaryTap: (() -> Void)?
|
||||
private let titleLabel = ScenicMaterialsStyle.label(size: 14, weight: .medium)
|
||||
private let detailLabel = ScenicMaterialsStyle.label(size: 10, color: ScenicMaterialsStyle.secondary)
|
||||
private let primaryButton = UIButton(type: .custom)
|
||||
private let secondaryButton = UIButton(type: .custom)
|
||||
private let progressView = UIProgressView(progressViewStyle: .bar)
|
||||
|
||||
/// 创建随安全区延伸的白色底栏。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
backgroundColor = .white
|
||||
titleLabel.numberOfLines = 2
|
||||
detailLabel.numberOfLines = 2
|
||||
primaryButton.titleLabel?.font = .systemFont(ofSize: 14, weight: .semibold)
|
||||
primaryButton.titleLabel?.numberOfLines = 2
|
||||
primaryButton.titleLabel?.textAlignment = .center
|
||||
primaryButton.setTitleColor(.white, for: .normal)
|
||||
primaryButton.setTitleColor(.white, for: .disabled)
|
||||
primaryButton.layer.cornerRadius = 10
|
||||
primaryButton.clipsToBounds = true
|
||||
primaryButton.accessibilityIdentifier = "scenic.materials.primary"
|
||||
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
|
||||
secondaryButton.tintColor = ScenicMaterialsStyle.primary
|
||||
secondaryButton.setTitleColor(ScenicMaterialsStyle.primary, for: .normal)
|
||||
secondaryButton.titleLabel?.font = .systemFont(ofSize: 13)
|
||||
secondaryButton.accessibilityIdentifier = "scenic.materials.secondary"
|
||||
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
|
||||
progressView.progressTintColor = ScenicMaterialsStyle.primary
|
||||
progressView.trackTintColor = ScenicMaterialsStyle.border
|
||||
let labels = UIStackView(arrangedSubviews: [titleLabel, detailLabel])
|
||||
labels.axis = .vertical
|
||||
labels.spacing = 5
|
||||
let row = UIStackView(arrangedSubviews: [labels, primaryButton])
|
||||
row.axis = .horizontal
|
||||
row.spacing = 12
|
||||
row.alignment = .center
|
||||
let stack = UIStackView(arrangedSubviews: [row, progressView, secondaryButton])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 10
|
||||
let separator = UIView()
|
||||
separator.backgroundColor = ScenicMaterialsStyle.border
|
||||
addSubview(separator)
|
||||
addSubview(stack)
|
||||
separator.snp.makeConstraints { $0.top.leading.trailing.equalToSuperview(); $0.height.equalTo(0.5) }
|
||||
stack.snp.makeConstraints {
|
||||
$0.top.equalToSuperview().offset(14)
|
||||
$0.leading.trailing.equalToSuperview().inset(20)
|
||||
$0.bottom.equalTo(safeAreaLayoutGuide).inset(12)
|
||||
}
|
||||
primaryButton.snp.makeConstraints { $0.width.equalTo(158); $0.height.equalTo(46) }
|
||||
progressView.snp.makeConstraints { $0.height.equalTo(3).priority(999) }
|
||||
secondaryButton.snp.makeConstraints { $0.height.equalTo(32).priority(999) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 由当前页面状态显式刷新底栏,始终保留禁用按钮的可读标题。
|
||||
func configure(title: String, detail: String?, primaryTitle: String, primaryEnabled: Bool,
|
||||
secondaryTitle: String? = nil, progress: Float? = nil) {
|
||||
UIView.performWithoutAnimation {
|
||||
titleLabel.text = title
|
||||
detailLabel.text = detail
|
||||
detailLabel.isHidden = detail == nil
|
||||
if primaryButton.title(for: .normal) != primaryTitle {
|
||||
primaryButton.setTitle(primaryTitle, for: .normal)
|
||||
primaryButton.setTitle(primaryTitle, for: .disabled)
|
||||
}
|
||||
primaryButton.backgroundColor = primaryEnabled ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.primary.withAlphaComponent(0.25)
|
||||
primaryButton.isEnabled = primaryEnabled
|
||||
if secondaryButton.title(for: .normal) != secondaryTitle {
|
||||
secondaryButton.setTitle(secondaryTitle, for: .normal)
|
||||
}
|
||||
secondaryButton.isHidden = secondaryTitle == nil
|
||||
progressView.isHidden = progress == nil
|
||||
progressView.progress = min(max(progress ?? 0, 0), 1)
|
||||
layoutIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func primaryTapped() { onPrimaryTap?() }
|
||||
@objc private func secondaryTapped() { onSecondaryTap?() }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import Foundation
|
||||
|
||||
/// 推进空镜库本地下载演示,不发起网络请求,也不写入文件或系统相册。
|
||||
@MainActor
|
||||
final class ScenicMaterialDemoDownloadDriver {
|
||||
private var task: Task<Void, Never>?
|
||||
private var activeBatchID: UUID?
|
||||
|
||||
/// 只推进当前批次的未完成项,旧批次回执由 ViewModel 再次校验。
|
||||
func start(viewModel: ScenicMaterialsViewModel, onProgress: @escaping () -> Void) {
|
||||
guard viewModel.phase == .downloading, let batchID = viewModel.batchID else { return }
|
||||
guard activeBatchID != batchID || task == nil else { return }
|
||||
stop()
|
||||
activeBatchID = batchID
|
||||
let itemIDs = viewModel.pendingIDs
|
||||
task = Task { @MainActor [weak self, weak viewModel] in
|
||||
guard let self, let viewModel else { return }
|
||||
defer {
|
||||
if self.activeBatchID == batchID {
|
||||
self.task = nil
|
||||
self.activeBatchID = nil
|
||||
}
|
||||
}
|
||||
for id in itemIDs where !viewModel.completedIDs.contains(id) {
|
||||
for progress in [0.2, 0.45, 0.7, 0.95] {
|
||||
do { try await Task.sleep(nanoseconds: 200_000_000) } catch { return }
|
||||
guard !Task.isCancelled, self.activeBatchID == batchID,
|
||||
viewModel.batchID == batchID, viewModel.phase == .downloading else { return }
|
||||
viewModel.receive(.progress(progress), clipID: id, batchID: batchID)
|
||||
onProgress()
|
||||
}
|
||||
viewModel.receive(.completed, clipID: id, batchID: batchID)
|
||||
onProgress()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 停止演示计时;调用方另行暂停或取消批次,避免把取消计时视为下载成功。
|
||||
func stop() {
|
||||
task?.cancel()
|
||||
task = nil
|
||||
activeBatchID = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 独立景区素材航线筛选 Sheet,选择即应用,不要求加载工作台。
|
||||
@MainActor
|
||||
final class ScenicMaterialRouteFilterViewController: UIViewController, UITableViewDelegate {
|
||||
/// 选择全部传 nil,选择具体航线传稳定 ID。
|
||||
var onSelectRoute: ((String?) -> Void)?
|
||||
|
||||
/// 筛选行使用明确身份,避免“全部”与业务航线 ID 冲突。
|
||||
private enum Row: Hashable { case all, route(String) }
|
||||
private let routes: [ScenicMaterialRoute]
|
||||
private let selectedRouteID: String?
|
||||
private let tableView = UITableView(frame: .zero, style: .plain)
|
||||
private var dataSource: UITableViewDiffableDataSource<Int, Row>!
|
||||
|
||||
/// 使用当前筛选快照创建独立选择面板。
|
||||
init(routes: [ScenicMaterialRoute], selectedRouteID: String?) {
|
||||
var identifiers = Set<String>()
|
||||
self.routes = routes.filter { identifiers.insert($0.id).inserted }
|
||||
self.selectedRouteID = selectedRouteID
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .pageSheet
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
setupUI()
|
||||
let desiredHeight = min(CGFloat(routes.count + 1) * 58 + 90, 460)
|
||||
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, desiredHeight) }]
|
||||
sheetPresentationController?.prefersGrabberVisible = true
|
||||
sheetPresentationController?.preferredCornerRadius = 24
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
view.accessibilityIdentifier = "scenic.materials.route.sheet"
|
||||
let title = ScenicMaterialsStyle.label("选择航线", size: 19, weight: .semibold)
|
||||
let close = UIButton(type: .system)
|
||||
close.setImage(UIImage(systemName: "xmark"), for: .normal)
|
||||
close.tintColor = ScenicMaterialsStyle.secondary
|
||||
close.accessibilityLabel = "关闭航线筛选"
|
||||
close.accessibilityIdentifier = "scenic.materials.route.close"
|
||||
close.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
||||
tableView.backgroundColor = .white
|
||||
tableView.separatorStyle = .none
|
||||
tableView.rowHeight = 58
|
||||
tableView.delegate = self
|
||||
tableView.accessibilityIdentifier = "scenic.materials.route.list"
|
||||
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "route")
|
||||
[title, close, tableView].forEach(view.addSubview)
|
||||
title.snp.makeConstraints { $0.top.equalTo(view.safeAreaLayoutGuide).offset(20); $0.leading.equalToSuperview().offset(22) }
|
||||
close.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) }
|
||||
tableView.snp.makeConstraints {
|
||||
$0.top.equalTo(title.snp.bottom).offset(14)
|
||||
$0.leading.trailing.equalToSuperview().inset(8)
|
||||
$0.bottom.equalTo(view.safeAreaLayoutGuide)
|
||||
}
|
||||
dataSource = UITableViewDiffableDataSource<Int, Row>(tableView: tableView) { [weak self] table, indexPath, row in
|
||||
guard let self else { return nil }
|
||||
let cell = table.dequeueReusableCell(withIdentifier: "route", for: indexPath)
|
||||
let id: String?
|
||||
let name: String
|
||||
switch row {
|
||||
case .all: id = nil; name = "全部航线"
|
||||
case let .route(routeID):
|
||||
id = routeID
|
||||
name = self.routes.first { $0.id == routeID }?.name ?? "航线暂不可用"
|
||||
}
|
||||
let selected = id == self.selectedRouteID
|
||||
cell.textLabel?.text = name
|
||||
cell.textLabel?.font = .systemFont(ofSize: 15, weight: selected ? .medium : .regular)
|
||||
cell.textLabel?.textColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
|
||||
cell.backgroundColor = .white
|
||||
let image = UIImageView(image: UIImage(systemName: selected ? "checkmark.circle.fill" : "circle",
|
||||
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22)))
|
||||
image.tintColor = selected ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border
|
||||
image.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
|
||||
cell.accessoryView = image
|
||||
cell.accessibilityIdentifier = "scenic.materials.route.\(id ?? "all")"
|
||||
cell.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
return cell
|
||||
}
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Row>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems([.all] + routes.map { .route($0.id) })
|
||||
dataSource.apply(snapshot, animatingDifferences: false)
|
||||
}
|
||||
|
||||
/// 将选中航线提交给调用页,再关闭筛选面板。
|
||||
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||
let id: String?
|
||||
switch item { case .all: id = nil; case let .route(routeID): id = routeID }
|
||||
let completion = onSelectRoute
|
||||
dismiss(animated: true) { completion?(id) }
|
||||
}
|
||||
|
||||
@objc private func closeTapped() { dismiss(animated: true) }
|
||||
}
|
||||
|
||||
/// 景区素材起止日期筛选 Sheet,临时选择只在点击确定后应用。
|
||||
@MainActor
|
||||
final class ScenicMaterialDateFilterViewController: UIViewController {
|
||||
/// nil/nil 表示保留期内的全部时间,其他值为按日包含端点的区间。
|
||||
var onSelectRange: ((Date?, Date?) -> Void)?
|
||||
|
||||
/// 当前正在编辑的日期端点。
|
||||
private enum Endpoint: Equatable { case start, end }
|
||||
private let minimumDate: Date
|
||||
private let maximumDate: Date
|
||||
private let calendar: Calendar
|
||||
private var startDate: Date
|
||||
private var endDate: Date
|
||||
private var usesAllDates: Bool
|
||||
private var endpoint: Endpoint = .start
|
||||
private let allButton = UIButton(type: .system)
|
||||
private let startButton = UIButton(type: .custom)
|
||||
private let endButton = UIButton(type: .custom)
|
||||
private let picker = UIDatePicker()
|
||||
|
||||
/// 约束到服务端约定或演示给定的保留区间,不提供未来日期。
|
||||
init(start: Date?, end: Date?, minimumDate: Date, maximumDate: Date, calendar: Calendar = .current) {
|
||||
self.calendar = calendar
|
||||
self.minimumDate = calendar.startOfDay(for: minimumDate)
|
||||
self.maximumDate = max(calendar.startOfDay(for: minimumDate), calendar.startOfDay(for: maximumDate))
|
||||
let clampedStart = min(max(calendar.startOfDay(for: start ?? maximumDate), self.minimumDate), self.maximumDate)
|
||||
let clampedEnd = min(max(calendar.startOfDay(for: end ?? maximumDate), self.minimumDate), self.maximumDate)
|
||||
self.startDate = min(clampedStart, clampedEnd)
|
||||
self.endDate = max(clampedStart, clampedEnd)
|
||||
usesAllDates = start == nil && end == nil
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .pageSheet
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
setupUI()
|
||||
updateUI()
|
||||
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 530) }]
|
||||
sheetPresentationController?.prefersGrabberVisible = true
|
||||
sheetPresentationController?.preferredCornerRadius = 24
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
view.accessibilityIdentifier = "scenic.materials.date.sheet"
|
||||
let title = ScenicMaterialsStyle.label("选择时间", size: 19, weight: .semibold)
|
||||
let hint = ScenicMaterialsStyle.label("选择起止日期", size: 13, color: ScenicMaterialsStyle.secondary)
|
||||
allButton.addTarget(self, action: #selector(allTapped), for: .touchUpInside)
|
||||
allButton.accessibilityIdentifier = "scenic.materials.date.all"
|
||||
startButton.addTarget(self, action: #selector(startTapped), for: .touchUpInside)
|
||||
startButton.accessibilityIdentifier = "scenic.materials.date.start"
|
||||
endButton.addTarget(self, action: #selector(endTapped), for: .touchUpInside)
|
||||
endButton.accessibilityIdentifier = "scenic.materials.date.end"
|
||||
[startButton, endButton].forEach {
|
||||
$0.layer.cornerRadius = 10
|
||||
$0.layer.borderWidth = 1
|
||||
}
|
||||
let dateRow = UIStackView(arrangedSubviews: [startButton, endButton])
|
||||
dateRow.distribution = .fillEqually
|
||||
dateRow.spacing = 12
|
||||
picker.datePickerMode = .date
|
||||
picker.preferredDatePickerStyle = .wheels
|
||||
picker.locale = Locale(identifier: "zh_CN")
|
||||
picker.calendar = calendar
|
||||
picker.timeZone = calendar.timeZone
|
||||
picker.minimumDate = minimumDate
|
||||
picker.maximumDate = maximumDate
|
||||
picker.accessibilityIdentifier = "scenic.materials.date.picker"
|
||||
picker.addTarget(self, action: #selector(dateChanged), for: .valueChanged)
|
||||
let retention = ScenicMaterialsStyle.label("仅显示保留期内已到来的日期", size: 11, color: ScenicMaterialsStyle.secondary)
|
||||
retention.textAlignment = .center
|
||||
let cancel = UIButton(type: .system)
|
||||
cancel.setTitle("取消", for: .normal)
|
||||
cancel.tintColor = ScenicMaterialsStyle.secondary
|
||||
cancel.backgroundColor = UIColor(hex: 0xF5F6F8)
|
||||
cancel.layer.cornerRadius = 10
|
||||
cancel.accessibilityIdentifier = "scenic.materials.date.cancel"
|
||||
cancel.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
|
||||
let confirm = UIButton(type: .system)
|
||||
confirm.setTitle("确定", for: .normal)
|
||||
confirm.setTitleColor(.white, for: .normal)
|
||||
confirm.backgroundColor = ScenicMaterialsStyle.primary
|
||||
confirm.layer.cornerRadius = 10
|
||||
confirm.accessibilityIdentifier = "scenic.materials.date.confirm"
|
||||
confirm.addTarget(self, action: #selector(confirmTapped), for: .touchUpInside)
|
||||
let actions = UIStackView(arrangedSubviews: [cancel, confirm])
|
||||
actions.distribution = .fillEqually
|
||||
actions.spacing = 12
|
||||
let scrollView = UIScrollView()
|
||||
let content = UIView()
|
||||
view.addSubview(scrollView)
|
||||
view.addSubview(actions)
|
||||
scrollView.addSubview(content)
|
||||
[title, hint, allButton, dateRow, picker, retention].forEach(content.addSubview)
|
||||
actions.snp.makeConstraints {
|
||||
$0.leading.trailing.equalToSuperview().inset(22)
|
||||
$0.bottom.equalTo(view.safeAreaLayoutGuide).inset(12)
|
||||
$0.height.equalTo(46)
|
||||
}
|
||||
scrollView.snp.makeConstraints {
|
||||
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
|
||||
$0.bottom.equalTo(actions.snp.top).offset(-12)
|
||||
}
|
||||
content.snp.makeConstraints { $0.edges.equalTo(scrollView.contentLayoutGuide); $0.width.equalTo(scrollView.frameLayoutGuide) }
|
||||
title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) }
|
||||
hint.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(12); $0.leading.equalTo(title) }
|
||||
allButton.snp.makeConstraints { $0.centerY.equalTo(hint); $0.trailing.equalToSuperview().inset(22); $0.height.equalTo(44) }
|
||||
dateRow.snp.makeConstraints { $0.top.equalTo(hint.snp.bottom).offset(16); $0.leading.trailing.equalToSuperview().inset(22); $0.height.equalTo(65) }
|
||||
picker.snp.makeConstraints { $0.top.equalTo(dateRow.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(12); $0.height.equalTo(210) }
|
||||
retention.snp.makeConstraints { $0.top.equalTo(picker.snp.bottom).offset(4); $0.leading.trailing.equalToSuperview().inset(20); $0.bottom.equalToSuperview().inset(4) }
|
||||
}
|
||||
|
||||
private func updateUI() {
|
||||
var allConfiguration = UIButton.Configuration.plain()
|
||||
allConfiguration.title = "全部时间"
|
||||
allConfiguration.image = UIImage(systemName: usesAllDates ? "checkmark.circle.fill" : "circle")
|
||||
allConfiguration.imagePadding = 5
|
||||
allConfiguration.baseForegroundColor = usesAllDates ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
|
||||
allConfiguration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
|
||||
allConfiguration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { input in
|
||||
var output = input; output.font = .systemFont(ofSize: 12); return output
|
||||
}
|
||||
allButton.configuration = allConfiguration
|
||||
allButton.accessibilityTraits = usesAllDates ? [.button, .selected] : .button
|
||||
let formatter = DateFormatter()
|
||||
formatter.calendar = calendar
|
||||
formatter.timeZone = calendar.timeZone
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.dateFormat = "M 月 d 日"
|
||||
for (button, value, name, candidate) in [(startButton, startDate, "开始日期", Endpoint.start), (endButton, endDate, "结束日期", Endpoint.end)] {
|
||||
let active = endpoint == candidate && !usesAllDates
|
||||
let foreground = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.text
|
||||
let titleColor = active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.secondary
|
||||
var configuration = UIButton.Configuration.plain()
|
||||
configuration.title = name
|
||||
configuration.subtitle = formatter.string(from: value)
|
||||
configuration.titleAlignment = .center
|
||||
configuration.titlePadding = 4
|
||||
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)
|
||||
configuration.baseForegroundColor = foreground
|
||||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
|
||||
var result = attributes
|
||||
result.font = .systemFont(ofSize: 12, weight: .regular)
|
||||
result.foregroundColor = titleColor
|
||||
return result
|
||||
}
|
||||
configuration.subtitleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
|
||||
var result = attributes
|
||||
result.font = .systemFont(ofSize: 14, weight: active ? .medium : .regular)
|
||||
result.foregroundColor = foreground
|
||||
return result
|
||||
}
|
||||
UIView.performWithoutAnimation {
|
||||
button.configuration = configuration
|
||||
button.layoutIfNeeded()
|
||||
}
|
||||
button.backgroundColor = active ? ScenicMaterialsStyle.primary.withAlphaComponent(0.06) : UIColor(hex: 0xF7F8FA)
|
||||
button.layer.borderColor = (active ? ScenicMaterialsStyle.primary : ScenicMaterialsStyle.border).cgColor
|
||||
button.accessibilityTraits = active ? [.button, .selected] : .button
|
||||
button.accessibilityLabel = "\(name),\(formatter.string(from: value))"
|
||||
}
|
||||
picker.setDate(endpoint == .start ? startDate : endDate, animated: false)
|
||||
picker.alpha = usesAllDates ? 0.4 : 1
|
||||
picker.isUserInteractionEnabled = !usesAllDates
|
||||
}
|
||||
|
||||
@objc private func allTapped() { usesAllDates.toggle(); updateUI() }
|
||||
@objc private func startTapped() { endpoint = .start; usesAllDates = false; updateUI() }
|
||||
@objc private func endTapped() { endpoint = .end; usesAllDates = false; updateUI() }
|
||||
|
||||
@objc private func dateChanged() {
|
||||
let value = min(max(calendar.startOfDay(for: picker.date), minimumDate), maximumDate)
|
||||
if endpoint == .start {
|
||||
startDate = value
|
||||
if endDate < value { endDate = value }
|
||||
} else {
|
||||
endDate = value
|
||||
if startDate > value { startDate = value }
|
||||
}
|
||||
updateUI()
|
||||
}
|
||||
|
||||
@objc private func cancelTapped() { dismiss(animated: true) }
|
||||
|
||||
@objc private func confirmTapped() {
|
||||
let start: Date? = usesAllDates ? nil : startDate
|
||||
let end: Date? = usesAllDates ? nil : endDate
|
||||
let completion = onSelectRange
|
||||
dismiss(animated: true) { completion?(start, end) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import AVFoundation
|
||||
import AVKit
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 景区空镜独立预览面板,仅播放应用内演示短片,不接入订单或网络素材。
|
||||
@MainActor
|
||||
final class ScenicMaterialPreviewViewController: UIViewController {
|
||||
private let clip: ScenicMaterialClip
|
||||
private let routeName: String
|
||||
private let capturedAt: Date
|
||||
private let calendar: Calendar
|
||||
private let playerController = AVPlayerViewController()
|
||||
private let coverView = UIImageView()
|
||||
private let playButton = UIButton(type: .system)
|
||||
private let playbackStatus = ScenicMaterialsStyle.label("本地演示短片 · 非真实景区视频", size: 11, color: ScenicMaterialsStyle.secondary)
|
||||
private var playbackTask: Task<Void, Never>?
|
||||
|
||||
/// 预览指定片段,原片元信息与本地演示视频时长明确区分。
|
||||
init(clip: ScenicMaterialClip, routeName: String, capturedAt: Date, calendar: Calendar = .current) {
|
||||
self.clip = clip
|
||||
self.routeName = routeName
|
||||
self.capturedAt = capturedAt
|
||||
self.calendar = calendar
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .pageSheet
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
setupUI()
|
||||
sheetPresentationController?.detents = [.custom { min($0.maximumDetentValue, 510) }]
|
||||
sheetPresentationController?.prefersGrabberVisible = true
|
||||
sheetPresentationController?.preferredCornerRadius = 24
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(pausePlayback),
|
||||
name: UIApplication.willResignActiveNotification, object: nil)
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
pausePlayback()
|
||||
playbackTask?.cancel()
|
||||
playbackTask = nil
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
view.accessibilityIdentifier = "scenic.materials.preview.sheet"
|
||||
let title = ScenicMaterialsStyle.label("视频预览", size: 19, weight: .semibold)
|
||||
let closeButton = UIButton(type: .system)
|
||||
closeButton.setImage(UIImage(systemName: "xmark"), for: .normal)
|
||||
closeButton.tintColor = ScenicMaterialsStyle.secondary
|
||||
closeButton.accessibilityLabel = "关闭景区视频预览"
|
||||
closeButton.accessibilityIdentifier = "scenic.materials.preview.close"
|
||||
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
||||
let mediaContainer = UIView()
|
||||
mediaContainer.backgroundColor = .black
|
||||
mediaContainer.layer.cornerRadius = 12
|
||||
mediaContainer.clipsToBounds = true
|
||||
coverView.image = UIImage(named: clip.coverAssetName)
|
||||
coverView.contentMode = .scaleAspectFill
|
||||
coverView.clipsToBounds = true
|
||||
playButton.setImage(UIImage(systemName: "play.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 48)), for: .normal)
|
||||
playButton.tintColor = .white
|
||||
playButton.accessibilityLabel = "播放本地演示视频"
|
||||
playButton.accessibilityIdentifier = "scenic.materials.preview.play"
|
||||
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
|
||||
playbackStatus.numberOfLines = 2
|
||||
let metadata = ScenicMaterialsStyle.label("片段 \(String(format: "%02d", clip.ordinal)) · 原片 \(clip.durationText) · \(clip.resolution) · \(clip.sizeText)", size: 12, color: ScenicMaterialsStyle.secondary)
|
||||
metadata.numberOfLines = 2
|
||||
metadata.accessibilityIdentifier = "scenic.materials.preview.metadata"
|
||||
let route = ScenicMaterialsStyle.label(routeName, size: 17, weight: .semibold)
|
||||
route.numberOfLines = 2
|
||||
route.accessibilityIdentifier = "scenic.materials.preview.route"
|
||||
let formatter = DateFormatter()
|
||||
formatter.calendar = calendar
|
||||
formatter.timeZone = calendar.timeZone
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.dateFormat = "MM-dd HH:mm"
|
||||
let time = ScenicMaterialsStyle.label(formatter.string(from: capturedAt), size: 12, color: ScenicMaterialsStyle.secondary)
|
||||
let done = UIButton(type: .system)
|
||||
done.setTitle("返回素材列表", for: .normal)
|
||||
done.setTitleColor(ScenicMaterialsStyle.primary, for: .normal)
|
||||
done.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
|
||||
done.backgroundColor = ScenicMaterialsStyle.primary.withAlphaComponent(0.07)
|
||||
done.layer.cornerRadius = 10
|
||||
done.accessibilityIdentifier = "scenic.materials.preview.done"
|
||||
done.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
||||
let scroll = UIScrollView()
|
||||
let content = UIView()
|
||||
view.addSubview(scroll)
|
||||
scroll.addSubview(content)
|
||||
[title, closeButton, playbackStatus, mediaContainer, metadata, route, time, done].forEach(content.addSubview)
|
||||
addChild(playerController)
|
||||
playerController.view.backgroundColor = .black
|
||||
playerController.view.isHidden = true
|
||||
playerController.allowsPictureInPicturePlayback = false
|
||||
playerController.exitsFullScreenWhenPlaybackEnds = true
|
||||
mediaContainer.addSubview(playerController.view)
|
||||
playerController.didMove(toParent: self)
|
||||
mediaContainer.addSubview(coverView)
|
||||
mediaContainer.addSubview(playButton)
|
||||
scroll.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
|
||||
content.snp.makeConstraints { $0.edges.equalTo(scroll.contentLayoutGuide); $0.width.equalTo(scroll.frameLayoutGuide) }
|
||||
title.snp.makeConstraints { $0.top.equalToSuperview().offset(20); $0.leading.equalToSuperview().offset(22) }
|
||||
closeButton.snp.makeConstraints { $0.trailing.equalToSuperview().inset(10); $0.centerY.equalTo(title); $0.size.equalTo(44) }
|
||||
playbackStatus.snp.makeConstraints { $0.top.equalTo(title.snp.bottom).offset(10); $0.leading.trailing.equalToSuperview().inset(22) }
|
||||
mediaContainer.snp.makeConstraints {
|
||||
$0.top.equalTo(playbackStatus.snp.bottom).offset(14)
|
||||
$0.leading.trailing.equalToSuperview().inset(22)
|
||||
$0.height.equalTo(mediaContainer.snp.width).multipliedBy(9.0 / 16.0)
|
||||
}
|
||||
playerController.view.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
coverView.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
playButton.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
metadata.snp.makeConstraints { $0.top.equalTo(mediaContainer.snp.bottom).offset(10); $0.leading.trailing.equalTo(mediaContainer) }
|
||||
route.snp.makeConstraints { $0.top.equalTo(metadata.snp.bottom).offset(17); $0.leading.trailing.equalTo(mediaContainer) }
|
||||
time.snp.makeConstraints { $0.top.equalTo(route.snp.bottom).offset(8); $0.leading.trailing.equalTo(mediaContainer) }
|
||||
done.snp.makeConstraints {
|
||||
$0.top.equalTo(time.snp.bottom).offset(18)
|
||||
$0.leading.trailing.equalTo(mediaContainer)
|
||||
$0.height.equalTo(44)
|
||||
$0.bottom.equalToSuperview().inset(14)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func playTapped() {
|
||||
guard playbackTask == nil, clip.isAvailable else { return }
|
||||
guard let url = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
|
||||
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock") else {
|
||||
playbackStatus.text = "本地演示视频暂不可用"
|
||||
return
|
||||
}
|
||||
playButton.isEnabled = false
|
||||
playbackTask = Task { @MainActor [weak self] in
|
||||
let playable = (try? await AVURLAsset(url: url).load(.isPlayable)) == true
|
||||
guard let self else { return }
|
||||
self.playbackTask = nil
|
||||
self.playButton.isEnabled = true
|
||||
guard !Task.isCancelled, self.view.window != nil else { return }
|
||||
guard playable else {
|
||||
self.playbackStatus.text = "本地演示视频暂不可播放"
|
||||
return
|
||||
}
|
||||
self.playerController.player = AVPlayer(url: url)
|
||||
self.playerController.view.isHidden = false
|
||||
self.coverView.isHidden = true
|
||||
self.playButton.isHidden = true
|
||||
self.playbackStatus.text = "正在播放 3 秒本地演示 · 原片时长见下方"
|
||||
self.playerController.player?.play()
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func pausePlayback() { playerController.player?.pause() }
|
||||
@objc private func closeTapped() { pausePlayback(); dismiss(animated: true) }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import UIKit
|
||||
|
||||
#if DEBUG
|
||||
/// 空镜库独立调试入口,不伪造正式首页权限,也不创建机巢工作台或订单。
|
||||
@MainActor
|
||||
enum ScenicMaterialsPreview {
|
||||
/// 指定启动参数时展示独立素材库;正式首页入口等待实际权限 URI 配置。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
guard arguments.contains("--scenic-materials-preview") else { return nil }
|
||||
let model = ScenicMaterialsViewModel()
|
||||
if let value = arguments.first(where: { $0.hasPrefix("--scenic-materials-scenario=") }),
|
||||
let scenario = ScenicMaterialsScenario(rawValue: String(value.dropFirst("--scenic-materials-scenario=".count))) {
|
||||
model.applyScenario(scenario)
|
||||
}
|
||||
let controller = ScenicMaterialsViewController(viewModel: model,
|
||||
isDemoPhotoPermissionAllowed: !arguments.contains("--scenic-materials-permission-denied"))
|
||||
return UINavigationController(rootViewController: controller)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,467 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 独立景区空镜库页面,提供筛选、分组预览、选择与前台下载演示,不依赖机巢订单。
|
||||
@MainActor
|
||||
final class ScenicMaterialsViewController: BaseViewController {
|
||||
/// 当前景区的素材与本地选择、下载状态。
|
||||
let viewModel: ScenicMaterialsViewModel
|
||||
|
||||
/// 辅助说明与每次拍摄批次分别使用稳定分区身份。
|
||||
private enum Section: Hashable { case retention, group(String), end }
|
||||
/// 选择与进度不参与身份,Diffable 更新时复用原有单元。
|
||||
private enum Item: Hashable { case retention, clip(String), expand(String), end }
|
||||
|
||||
private let filterBar = UIStackView()
|
||||
private let routeButton = UIButton(type: .system)
|
||||
private let dateButton = UIButton(type: .system)
|
||||
private let footer = ScenicMaterialsFooterView()
|
||||
private let emptyView = UIView()
|
||||
private let emptyTitle = ScenicMaterialsStyle.label(size: 18, weight: .semibold)
|
||||
private let emptyMessage = ScenicMaterialsStyle.label(size: 14, color: ScenicMaterialsStyle.secondary)
|
||||
private let resetButton = UIButton(type: .system)
|
||||
private let driver = ScenicMaterialDemoDownloadDriver()
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||||
private var isDemoPhotoPermissionAllowed: Bool
|
||||
|
||||
/// 注入独立景区上下文;权限开关只用于本地演示,不读写系统相册授权。
|
||||
init(viewModel: ScenicMaterialsViewModel = ScenicMaterialsViewModel(), isDemoPhotoPermissionAllowed: Bool = true) {
|
||||
self.viewModel = viewModel
|
||||
self.isDemoPhotoPermissionAllowed = isDemoPhotoPermissionAllowed
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "景区素材"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
let appearance = UINavigationBarAppearance()
|
||||
appearance.configureWithOpaqueBackground()
|
||||
appearance.backgroundColor = .white
|
||||
appearance.shadowColor = .clear
|
||||
appearance.titleTextAttributes = [.foregroundColor: ScenicMaterialsStyle.text,
|
||||
.font: UIFont.systemFont(ofSize: 18, weight: .semibold)]
|
||||
navigationItem.standardAppearance = appearance
|
||||
navigationItem.scrollEdgeAppearance = appearance
|
||||
#if DEBUG
|
||||
var actions: [UIAction] = ScenicMaterialsScenario.allCases.map { scenario in
|
||||
UIAction(title: scenario.title) { [weak self] _ in self?.applyPreviewScenario(scenario) }
|
||||
}
|
||||
actions.append(UIAction(title: "相册权限不足") { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.driver.stop()
|
||||
self.viewModel.pauseDownload()
|
||||
self.isDemoPhotoPermissionAllowed = false
|
||||
self.refreshDisplay(animated: false)
|
||||
self.presentPermissionDemo()
|
||||
})
|
||||
let menu = UIBarButtonItem(image: UIImage(systemName: "slider.horizontal.3"), menu: UIMenu(title: "空镜库本地演示", children: actions))
|
||||
menu.accessibilityLabel = "体验空镜库其他状态"
|
||||
menu.accessibilityIdentifier = "scenic.materials.scenarios"
|
||||
navigationItem.rightBarButtonItem = menu
|
||||
#endif
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
view.accessibilityIdentifier = "scenic.materials"
|
||||
filterBar.axis = .horizontal
|
||||
filterBar.distribution = .fillEqually
|
||||
filterBar.spacing = 10
|
||||
configureFilterButton(routeButton, identifier: "scenic.materials.routeFilter")
|
||||
configureFilterButton(dateButton, identifier: "scenic.materials.dateFilter")
|
||||
filterBar.addArrangedSubview(routeButton)
|
||||
filterBar.addArrangedSubview(dateButton)
|
||||
collectionView.backgroundColor = .white
|
||||
collectionView.alwaysBounceVertical = true
|
||||
collectionView.showsVerticalScrollIndicator = true
|
||||
collectionView.accessibilityIdentifier = "scenic.materials.list"
|
||||
collectionView.register(ScenicMaterialClipCell.self, forCellWithReuseIdentifier: "clip")
|
||||
collectionView.register(ScenicMaterialExpandCell.self, forCellWithReuseIdentifier: "expand")
|
||||
collectionView.register(ScenicMaterialTextCell.self, forCellWithReuseIdentifier: "text")
|
||||
collectionView.register(ScenicMaterialGroupHeaderView.self,
|
||||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
||||
withReuseIdentifier: "group")
|
||||
view.addSubview(filterBar)
|
||||
view.addSubview(collectionView)
|
||||
view.addSubview(footer)
|
||||
setupEmptyView()
|
||||
configureDataSource()
|
||||
refreshDisplay(animated: false)
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
filterBar.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide).offset(10)
|
||||
make.leading.trailing.equalToSuperview().inset(16)
|
||||
make.height.equalTo(42)
|
||||
}
|
||||
collectionView.snp.makeConstraints { make in
|
||||
make.top.equalTo(filterBar.snp.bottom).offset(8)
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.bottom.equalTo(footer.snp.top)
|
||||
}
|
||||
footer.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
routeButton.addTarget(self, action: #selector(selectRoute), for: .touchUpInside)
|
||||
dateButton.addTarget(self, action: #selector(selectDateRange), for: .touchUpInside)
|
||||
resetButton.addTarget(self, action: #selector(resetFilters), for: .touchUpInside)
|
||||
footer.onPrimaryTap = { [weak self] in self?.performPrimaryAction() }
|
||||
footer.onSecondaryTap = { [weak self] in
|
||||
guard let self else { return }
|
||||
self.driver.stop()
|
||||
if self.viewModel.phase == .downloading || self.viewModel.phase == .paused {
|
||||
self.viewModel.cancelDownload()
|
||||
} else {
|
||||
self.viewModel.continueSelecting()
|
||||
}
|
||||
self.refreshDisplay(animated: true)
|
||||
}
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(pauseForBackground),
|
||||
name: UIApplication.willResignActiveNotification, object: nil)
|
||||
}
|
||||
|
||||
/// 真正离开时暂停;预览或筛选弹层不会中止下载,取消返回手势也不会误暂停。
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true else { return }
|
||||
if let coordinator = transitionCoordinator, coordinator.isInteractive {
|
||||
coordinator.animate(alongsideTransition: nil) { [weak self] context in
|
||||
if !context.isCancelled { self?.pauseForBackground() }
|
||||
}
|
||||
} else {
|
||||
pauseForBackground()
|
||||
}
|
||||
}
|
||||
|
||||
/// 外部演示回执后显式刷新,不自动开始或继续任何传输。
|
||||
func refreshDisplay(animated: Bool = true) {
|
||||
guard dataSource != nil else { return }
|
||||
routeButton.setTitle(viewModel.routeFilterTitle, for: .normal)
|
||||
dateButton.setTitle(viewModel.dateFilterTitle, for: .normal)
|
||||
routeButton.isEnabled = !viewModel.isSelectionLocked
|
||||
dateButton.isEnabled = !viewModel.isSelectionLocked
|
||||
emptyTitle.text = viewModel.emptyTitle
|
||||
emptyMessage.text = viewModel.emptyMessage
|
||||
resetButton.isHidden = viewModel.selectedRouteID == nil && viewModel.dateRange == nil
|
||||
collectionView.backgroundView = viewModel.filteredGroups.isEmpty ? emptyView : nil
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
||||
snapshot.appendSections([.retention])
|
||||
snapshot.appendItems([.retention])
|
||||
for group in viewModel.filteredGroups {
|
||||
snapshot.appendSections([.group(group.id)])
|
||||
snapshot.appendItems(viewModel.visibleClips(in: group).map { .clip($0.id) })
|
||||
if group.clips.count > 5 { snapshot.appendItems([.expand(group.id)]) }
|
||||
}
|
||||
if !viewModel.filteredGroups.isEmpty {
|
||||
snapshot.appendSections([.end]); snapshot.appendItems([.end])
|
||||
}
|
||||
let existing = Set(dataSource.snapshot().itemIdentifiers)
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
|
||||
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
|
||||
guard let self else { return }
|
||||
self.collectionView.collectionViewLayout.invalidateLayout()
|
||||
self.refreshVisibleHeaders()
|
||||
}
|
||||
updateFooter()
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
/// 状态菜单只切换本地演示,重置演示权限后等待工作人员主动操作。
|
||||
func applyPreviewScenario(_ scenario: ScenicMaterialsScenario) {
|
||||
driver.stop()
|
||||
isDemoPhotoPermissionAllowed = true
|
||||
viewModel.applyScenario(scenario)
|
||||
refreshDisplay(animated: true)
|
||||
}
|
||||
#endif
|
||||
|
||||
private func configureFilterButton(_ button: UIButton, identifier: String) {
|
||||
var configuration = UIButton.Configuration.plain()
|
||||
configuration.image = UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium))
|
||||
configuration.imagePlacement = .trailing
|
||||
configuration.imagePadding = 8
|
||||
configuration.baseForegroundColor = ScenicMaterialsStyle.text
|
||||
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)
|
||||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
|
||||
var result = incoming; result.font = .systemFont(ofSize: 13); return result
|
||||
}
|
||||
button.configuration = configuration
|
||||
button.backgroundColor = UIColor(hex: 0xF6F7F9)
|
||||
button.layer.cornerRadius = 10
|
||||
button.layer.borderWidth = 0.5
|
||||
button.layer.borderColor = ScenicMaterialsStyle.border.cgColor
|
||||
button.titleLabel?.lineBreakMode = .byTruncatingTail
|
||||
button.accessibilityIdentifier = identifier
|
||||
}
|
||||
|
||||
private func setupEmptyView() {
|
||||
let icon = UIImageView(image: UIImage(systemName: "photo.on.rectangle.angled"))
|
||||
icon.tintColor = ScenicMaterialsStyle.secondary.withAlphaComponent(0.5)
|
||||
icon.contentMode = .scaleAspectFit
|
||||
emptyTitle.textAlignment = .center
|
||||
emptyTitle.numberOfLines = 0
|
||||
emptyMessage.textAlignment = .center
|
||||
emptyMessage.numberOfLines = 0
|
||||
resetButton.setTitle("重置筛选", for: .normal)
|
||||
resetButton.tintColor = ScenicMaterialsStyle.primary
|
||||
resetButton.accessibilityIdentifier = "scenic.materials.resetFilters"
|
||||
emptyView.accessibilityIdentifier = "scenic.materials.empty"
|
||||
let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 14
|
||||
emptyView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in
|
||||
make.centerX.equalToSuperview(); make.centerY.equalToSuperview().offset(-24)
|
||||
make.leading.trailing.equalToSuperview().inset(32)
|
||||
}
|
||||
icon.snp.makeConstraints { $0.height.equalTo(48) }
|
||||
resetButton.snp.makeConstraints { $0.height.equalTo(44).priority(999) }
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
|
||||
guard let self else { return UICollectionViewCell() }
|
||||
switch item {
|
||||
case .clip(let id):
|
||||
guard let clip = self.viewModel.clip(id: id),
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "clip", for: path) as? ScenicMaterialClipCell else { return UICollectionViewCell() }
|
||||
self.configureClip(cell, clip: clip)
|
||||
return cell
|
||||
case .expand(let id):
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "expand", for: path) as! ScenicMaterialExpandCell
|
||||
let expanded = self.viewModel.expandedGroupIDs.contains(id)
|
||||
let remaining = max((self.viewModel.group(id: id)?.clips.count ?? 5) - 5, 0)
|
||||
cell.configure(groupID: id, title: expanded ? "收起片段" : "展开其余 \(remaining) 段")
|
||||
cell.onToggleExpanded = { [weak self] in
|
||||
self?.viewModel.toggleExpandedGroup(id: id)
|
||||
self?.refreshDisplay(animated: true)
|
||||
}
|
||||
return cell
|
||||
case .retention, .end:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! ScenicMaterialTextCell
|
||||
cell.configure(item == .retention ? "素材保留 90 天,请及时下载" : "已显示保留期内的全部演示记录", identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end")
|
||||
return cell
|
||||
}
|
||||
}
|
||||
dataSource.supplementaryViewProvider = { [weak self] list, kind, path in
|
||||
guard let self, kind == UICollectionView.elementKindSectionHeader else { return nil }
|
||||
let sections = self.dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(path.section), case .group(let id) = sections[path.section],
|
||||
let group = self.viewModel.group(id: id) else { return nil }
|
||||
let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "group", for: path) as! ScenicMaterialGroupHeaderView
|
||||
self.configureHeader(header, group: group)
|
||||
return header
|
||||
}
|
||||
}
|
||||
|
||||
private func configureClip(_ cell: ScenicMaterialClipCell, clip: ScenicMaterialClip) {
|
||||
let completed = viewModel.completedIDs.contains(clip.id)
|
||||
let failed = viewModel.failedIDs.contains(clip.id)
|
||||
let inBatch = viewModel.batchItemIDs.contains(clip.id)
|
||||
let status: String? = completed ? "演示已下载" : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil
|
||||
cell.configure(clip: clip, selected: viewModel.selectedIDs.contains(clip.id),
|
||||
isSelectionEnabled: viewModel.canSelect(id: clip.id), statusText: status,
|
||||
progress: inBatch && viewModel.phase == .downloading && !completed ? viewModel.progressByID[clip.id] ?? 0 : nil,
|
||||
isHero: viewModel.group(id: clip.groupID)?.clips.first?.id == clip.id)
|
||||
cell.onToggleSelection = { [weak self] in
|
||||
self?.viewModel.toggleSelection(id: clip.id)
|
||||
self?.refreshDisplay(animated: true)
|
||||
}
|
||||
cell.onPreview = { [weak self] in self?.preview(clip) }
|
||||
}
|
||||
|
||||
private func configureHeader(_ header: ScenicMaterialGroupHeaderView, group: ScenicMaterialGroup) {
|
||||
let index = viewModel.filteredGroups.firstIndex { $0.id == group.id } ?? 0
|
||||
let showRoute = index == 0 || viewModel.filteredGroups[index - 1].routeID != group.routeID
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.calendar = viewModel.calendar
|
||||
formatter.timeZone = viewModel.calendar.timeZone
|
||||
formatter.dateFormat = "MM-dd HH:mm"
|
||||
header.configure(groupID: group.id, routeName: showRoute ? viewModel.route(id: group.routeID)?.name : nil,
|
||||
timeTitle: formatter.string(from: group.capturedAt), count: group.clips.count,
|
||||
isSelected: viewModel.isGroupSelected(id: group.id),
|
||||
canSelect: group.clips.contains { viewModel.canSelect(id: $0.id) })
|
||||
header.onToggleGroup = { [weak self] in
|
||||
self?.viewModel.toggleGroup(id: group.id)
|
||||
self?.refreshDisplay(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshVisibleHeaders() {
|
||||
for path in collectionView.indexPathsForVisibleSupplementaryElements(ofKind: UICollectionView.elementKindSectionHeader) {
|
||||
let sections = dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(path.section), case .group(let id) = sections[path.section],
|
||||
let group = viewModel.group(id: id),
|
||||
let header = collectionView.supplementaryView(forElementKind: UICollectionView.elementKindSectionHeader, at: path) as? ScenicMaterialGroupHeaderView else { continue }
|
||||
configureHeader(header, group: group)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { [weak self] index, environment in
|
||||
guard let self, let dataSource = self.dataSource else { return nil }
|
||||
let sections = dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(index) else { return nil }
|
||||
let section = sections[index]
|
||||
guard case .group(let id) = section, let group = self.viewModel.group(id: id) else {
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
|
||||
let row = NSCollectionLayoutGroup.vertical(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(36)), subitems: [item])
|
||||
let layout = NSCollectionLayoutSection(group: row)
|
||||
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
|
||||
return layout
|
||||
}
|
||||
let width = max(environment.container.effectiveContentSize.width - 32, 1)
|
||||
let heroHeight = width * 9 / 16
|
||||
let smallWidth = (width - 8) / 2
|
||||
let smallHeight = smallWidth * 9 / 16
|
||||
var rows: [NSCollectionLayoutItem] = [NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(heroHeight)))]
|
||||
var height = heroHeight
|
||||
var remaining = max(self.viewModel.visibleClips(in: group).count - 1, 0)
|
||||
while remaining > 0 {
|
||||
let count = min(remaining, 2)
|
||||
let items = (0..<count).map { _ in NSCollectionLayoutItem(layoutSize: .init(widthDimension: .absolute(smallWidth), heightDimension: .fractionalHeight(1))) }
|
||||
// 奇数末项限定行宽,防止组合布局将下一条“收起”单元补入右侧空位。
|
||||
let rowWidth: NSCollectionLayoutDimension = count == 1 ? .absolute(smallWidth) : .fractionalWidth(1)
|
||||
let row = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: rowWidth, heightDimension: .absolute(smallHeight)), subitems: items)
|
||||
row.interItemSpacing = .fixed(8)
|
||||
rows.append(row); height += 8 + smallHeight; remaining -= count
|
||||
}
|
||||
if group.clips.count > 5 {
|
||||
rows.append(NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(40))))
|
||||
height += 48
|
||||
}
|
||||
let grid = NSCollectionLayoutGroup.vertical(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)), subitems: rows)
|
||||
grid.interItemSpacing = .fixed(8)
|
||||
let layout = NSCollectionLayoutSection(group: grid)
|
||||
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 20, trailing: 16)
|
||||
let previous = self.viewModel.filteredGroups.firstIndex { $0.id == id } ?? 0
|
||||
let showRoute = previous == 0 || self.viewModel.filteredGroups[previous - 1].routeID != group.routeID
|
||||
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
|
||||
layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(showRoute ? 94 : 48)),
|
||||
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
|
||||
return layout
|
||||
}
|
||||
}
|
||||
|
||||
private func updateFooter() {
|
||||
let completed = viewModel.completedCount
|
||||
let total = viewModel.totalCount
|
||||
switch viewModel.phase {
|
||||
case .idle:
|
||||
footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: "本地演示 · 不下载或保存真实文件",
|
||||
primaryTitle: viewModel.selectedCount > 0 ? "下载所选(\(viewModel.selectedCount))" : "下载所选", primaryEnabled: viewModel.canStartDownload)
|
||||
case .downloading:
|
||||
footer.configure(title: "下载中 · \(completed)/\(total) 段", detail: "请保持页面开启,切后台将暂停",
|
||||
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress))
|
||||
case .paused:
|
||||
footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "演示进度已保留,请手动继续",
|
||||
primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消")
|
||||
case .partialFailure:
|
||||
footer.configure(title: "演示完成 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: "未保存真实文件,成功项不重复下载",
|
||||
primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择")
|
||||
case .completed:
|
||||
footer.configure(title: "演示完成 \(completed) 段", detail: "未写入系统相册",
|
||||
primaryTitle: "继续选择素材", primaryEnabled: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func performPrimaryAction() {
|
||||
if viewModel.phase == .completed {
|
||||
viewModel.continueSelecting(); refreshDisplay(); return
|
||||
}
|
||||
guard isDemoPhotoPermissionAllowed else { presentPermissionDemo(); return }
|
||||
let started: Bool
|
||||
switch viewModel.phase {
|
||||
case .idle: started = viewModel.startDownload()
|
||||
case .paused: started = viewModel.continueDownload()
|
||||
case .partialFailure: started = viewModel.retryFailedDownloads()
|
||||
case .downloading, .completed: started = false
|
||||
}
|
||||
refreshDisplay(animated: false)
|
||||
if started { driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) } }
|
||||
}
|
||||
|
||||
@objc private func pauseForBackground() {
|
||||
driver.stop()
|
||||
viewModel.pauseDownload()
|
||||
if isViewLoaded { refreshDisplay(animated: false) }
|
||||
}
|
||||
|
||||
@objc private func selectRoute() {
|
||||
guard !viewModel.isSelectionLocked else { return }
|
||||
let picker = ScenicMaterialRouteFilterViewController(routes: viewModel.routes, selectedRouteID: viewModel.selectedRouteID)
|
||||
picker.onSelectRoute = { [weak self] id in
|
||||
self?.viewModel.setRoute(id: id)
|
||||
self?.refreshDisplay()
|
||||
self?.collectionView.setContentOffset(.zero, animated: false)
|
||||
}
|
||||
present(picker, animated: true)
|
||||
}
|
||||
|
||||
@objc private func selectDateRange() {
|
||||
guard !viewModel.isSelectionLocked else { return }
|
||||
let picker = ScenicMaterialDateFilterViewController(start: viewModel.dateRange?.start, end: viewModel.dateRange?.end,
|
||||
minimumDate: viewModel.minimumDate, maximumDate: viewModel.maximumDate,
|
||||
calendar: viewModel.calendar)
|
||||
picker.onSelectRange = { [weak self] start, end in
|
||||
guard let self else { return }
|
||||
if self.viewModel.setDateRange(start: start, end: end) {
|
||||
self.refreshDisplay()
|
||||
self.collectionView.setContentOffset(.zero, animated: false)
|
||||
} else { self.showToast("请选择保留期内的有效日期范围") }
|
||||
}
|
||||
present(picker, animated: true)
|
||||
}
|
||||
|
||||
@objc private func resetFilters() {
|
||||
viewModel.resetFilters()
|
||||
refreshDisplay()
|
||||
}
|
||||
|
||||
private func preview(_ clip: ScenicMaterialClip) {
|
||||
guard clip.isAvailable, let group = viewModel.group(id: clip.groupID) else { return }
|
||||
let controller = ScenicMaterialPreviewViewController(clip: clip, routeName: viewModel.route(id: group.routeID)?.name ?? "景区航线",
|
||||
capturedAt: group.capturedAt, calendar: viewModel.calendar)
|
||||
present(controller, animated: true)
|
||||
}
|
||||
|
||||
private func presentPermissionDemo() {
|
||||
guard presentedViewController == nil else { return }
|
||||
let alert = UIAlertController(title: "需要相册保存权限", message: "真实下载需允许保存视频。此处仅演示权限流程,不读取或修改系统权限。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "暂不下载", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "演示允许权限", style: .default) { [weak self] _ in
|
||||
self?.isDemoPhotoPermissionAllowed = true
|
||||
self?.refreshDisplay(animated: false)
|
||||
self?.showToast("演示权限已恢复,请手动下载")
|
||||
})
|
||||
present(alert, animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 空镜列表的保留期与末尾说明,不参与素材选择。
|
||||
private final class ScenicMaterialTextCell: UICollectionViewCell {
|
||||
private let label = ScenicMaterialsStyle.label(size: 12, color: ScenicMaterialsStyle.secondary)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
contentView.addSubview(label)
|
||||
label.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 根据单元用途更新文案及可访问标识。
|
||||
func configure(_ text: String, identifier: String) {
|
||||
label.text = text
|
||||
label.accessibilityIdentifier = identifier
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user