feat(scenic-materials): 搭建独立景区空镜库UI与下载演示

This commit is contained in:
2026-10-26 15:37:50 +08:00
parent 837623ee7f
commit c13282c7bc
29 changed files with 2876 additions and 4 deletions
@@ -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
}
}