652 lines
35 KiB
Swift
652 lines
35 KiB
Swift
import Photos
|
||
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), loadMore, 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 let downloadService = ScenicMaterialDownloadService()
|
||
private var loadTask: Task<Void, Never>?
|
||
private var isLoadingNextPage = false
|
||
private let refreshControl = UIRefreshControl()
|
||
private let retryButton = UIButton(type: .system)
|
||
private var authorizationTask: Task<Void, Never>?
|
||
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 viewDidLoad() {
|
||
super.viewDidLoad()
|
||
if viewModel.isRemote { reloadRemoteMaterials() }
|
||
}
|
||
|
||
@objc private func reloadRemoteMaterials() {
|
||
guard viewModel.isRemote, !viewModel.isSelectionLocked else { refreshControl.endRefreshing(); return }
|
||
loadTask?.cancel()
|
||
isLoadingNextPage = false
|
||
let session = AppStore.shared.session
|
||
guard session.accountType == .storeUser, session.userId == viewModel.context.userID,
|
||
String(session.currentScenicId) == viewModel.context.scenicID else {
|
||
refreshControl.endRefreshing()
|
||
showToast("请使用门店账号并重新进入当前景区素材库")
|
||
return
|
||
}
|
||
let api = ScenicMaterialsAPI(client: NetworkServices.shared.apiClient)
|
||
emptyTitle.text = "正在加载素材"
|
||
emptyMessage.text = "请稍候"
|
||
retryButton.isHidden = true
|
||
routeButton.isEnabled = false
|
||
dateButton.isEnabled = false
|
||
loadTask = Task { @MainActor [weak self] in
|
||
guard let self else { return }
|
||
await self.viewModel.loadRemoteSessions(api: api)
|
||
guard !Task.isCancelled else { return }
|
||
self.refreshControl.endRefreshing()
|
||
self.refreshDisplay()
|
||
}
|
||
}
|
||
|
||
/// 用户主动加载下一页;不把第一页误标为全部素材,失败时保留已展示内容。
|
||
private func loadMoreRemoteMaterials() {
|
||
guard viewModel.isRemote, !viewModel.isSelectionLocked, !viewModel.isLoading,
|
||
!isLoadingNextPage, viewModel.hasMoreRemoteSessions else { return }
|
||
let session = AppStore.shared.session
|
||
guard session.accountType == .storeUser, session.userId == viewModel.context.userID,
|
||
String(session.currentScenicId) == viewModel.context.scenicID else {
|
||
showToast("请使用门店账号并重新进入当前景区素材库")
|
||
return
|
||
}
|
||
isLoadingNextPage = true
|
||
refreshDisplay(animated: false)
|
||
let api = ScenicMaterialsAPI(client: NetworkServices.shared.apiClient)
|
||
loadTask = Task { @MainActor [weak self] in
|
||
guard let self else { return }
|
||
await self.viewModel.loadMoreRemoteSessions(api: api)
|
||
guard !Task.isCancelled else { return }
|
||
self.isLoadingNextPage = false
|
||
self.refreshDisplay()
|
||
if let error = self.viewModel.loadMoreError { self.showToast(error) }
|
||
}
|
||
}
|
||
|
||
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
|
||
guard !viewModel.isRemote else { return }
|
||
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.downloadService.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(ScenicMaterialPageFooterCell.self, forCellWithReuseIdentifier: "pageFooter")
|
||
collectionView.register(ScenicMaterialGroupHeaderView.self,
|
||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
||
withReuseIdentifier: "group")
|
||
view.addSubview(filterBar)
|
||
view.addSubview(collectionView)
|
||
view.addSubview(footer)
|
||
if viewModel.isRemote {
|
||
collectionView.refreshControl = refreshControl
|
||
refreshControl.addTarget(self, action: #selector(reloadRemoteMaterials), for: .valueChanged)
|
||
}
|
||
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(40)
|
||
}
|
||
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()
|
||
self.downloadService.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?.finishLeaving() }
|
||
}
|
||
} else {
|
||
finishLeaving()
|
||
}
|
||
}
|
||
|
||
/// 仅在确认离开页面后作废异步工作,取消返回手势继续保留原来的加载及下载。
|
||
private func finishLeaving() {
|
||
loadTask?.cancel()
|
||
isLoadingNextPage = false
|
||
viewModel.cancelRemoteLoad()
|
||
authorizationTask?.cancel()
|
||
authorizationTask = nil
|
||
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 && !viewModel.isLoading && !isLoadingNextPage
|
||
dateButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading && !isLoadingNextPage
|
||
retryButton.isHidden = viewModel.loadError == nil
|
||
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([viewModel.isRemote && viewModel.hasMoreRemoteSessions ? .loadMore : .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.baseForegroundColor = ScenicMaterialsStyle.text
|
||
configuration.cornerStyle = .fixed
|
||
configuration.background.cornerRadius = 11
|
||
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 32)
|
||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
|
||
var result = incoming; result.font = .systemFont(ofSize: 15, weight: .medium); return result
|
||
}
|
||
button.configuration = configuration
|
||
button.contentHorizontalAlignment = .leading
|
||
button.backgroundColor = UIColor(hex: 0xF7F8FA)
|
||
button.layer.cornerRadius = 11
|
||
button.layer.borderWidth = 1
|
||
button.layer.borderColor = ScenicMaterialsStyle.border.cgColor
|
||
button.titleLabel?.lineBreakMode = .byTruncatingTail
|
||
button.titleLabel?.numberOfLines = 1
|
||
button.accessibilityIdentifier = identifier
|
||
let chevron = UIImageView(image: UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium)))
|
||
chevron.tintColor = ScenicMaterialsStyle.secondary
|
||
chevron.isUserInteractionEnabled = false
|
||
button.addSubview(chevron)
|
||
chevron.snp.makeConstraints { $0.trailing.equalToSuperview().inset(12); $0.centerY.equalToSuperview() }
|
||
}
|
||
|
||
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"
|
||
retryButton.setTitle("重新加载", for: .normal)
|
||
retryButton.accessibilityIdentifier = "scenic.materials.retry"
|
||
retryButton.addTarget(self, action: #selector(reloadRemoteMaterials), for: .touchUpInside)
|
||
let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton, retryButton])
|
||
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 .loadMore:
|
||
let cell = list.dequeueReusableCell(withReuseIdentifier: "pageFooter", for: path) as! ScenicMaterialPageFooterCell
|
||
let title = self.isLoadingNextPage ? "正在加载更多场次…" : self.viewModel.loadMoreError != nil ? "加载失败,点击重试" :
|
||
"加载更多场次(\(self.viewModel.loadedRemoteSessionCount) / \(self.viewModel.remoteTotalCount))"
|
||
cell.configure(title: title, enabled: !self.isLoadingNextPage && !self.viewModel.isSelectionLocked)
|
||
cell.onLoadMore = { [weak self] in self?.loadMoreRemoteMaterials() }
|
||
return cell
|
||
case .retention, .end:
|
||
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! ScenicMaterialTextCell
|
||
cell.configure(item == .retention ? self.viewModel.retentionTips : (self.viewModel.isRemote ? "已显示全部素材" : "已显示保留期内的全部演示记录"), 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 ? (viewModel.isRemote ? "已保存相册" : "演示已下载") : 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(section == .end ? 48 : 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: viewModel.isRemote ? nil : "本地演示 · 不下载或保存真实文件",
|
||
primaryTitle: "下载所选", primaryEnabled: viewModel.canStartDownload && !isLoadingNextPage)
|
||
case .downloading:
|
||
footer.configure(title: "下载中 · \(completed)/\(total) 段", detail: "请保持页面开启,切后台将暂停",
|
||
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress, isBusy: true)
|
||
case .paused:
|
||
footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "已完成项已保留,请手动继续",
|
||
primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress)
|
||
case .partialFailure:
|
||
footer.configure(title: "已下载 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: viewModel.isRemote ? "成功项已保存相册" : "演示结果 · 未保存真实文件",
|
||
primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择", layout: .result)
|
||
case .completed:
|
||
footer.configure(title: viewModel.isRemote ? "已保存 \(completed) 段" : "演示完成 \(completed) 段", detail: viewModel.isRemote ? "可在系统相册查看" : "未写入系统相册",
|
||
primaryTitle: "继续选择素材", primaryEnabled: true, layout: .result)
|
||
}
|
||
}
|
||
|
||
private func performPrimaryAction() {
|
||
guard !isLoadingNextPage, !viewModel.isLoading, !viewModel.isLoadingMore else { return }
|
||
if viewModel.phase == .completed {
|
||
viewModel.continueSelecting(); refreshDisplay(); return
|
||
}
|
||
if viewModel.isRemote {
|
||
guard authorizationTask == nil else { return }
|
||
authorizationTask = Task { @MainActor [weak self] in
|
||
let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
|
||
guard let self else { return }
|
||
self.authorizationTask = nil
|
||
guard !Task.isCancelled, self.view.window != nil,
|
||
UIApplication.shared.applicationState == .active else { return }
|
||
guard status == .authorized || status == .limited else {
|
||
self.presentPhotoPermissionSettings()
|
||
return
|
||
}
|
||
self.startTransfer()
|
||
}
|
||
return
|
||
}
|
||
guard isDemoPhotoPermissionAllowed else { presentPermissionDemo(); return }
|
||
startTransfer()
|
||
}
|
||
|
||
private func startTransfer() {
|
||
guard !isLoadingNextPage, !viewModel.isLoading, !viewModel.isLoadingMore else { 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)
|
||
guard started else { return }
|
||
if viewModel.isRemote, let batchID = viewModel.batchID {
|
||
let items = viewModel.pendingIDs.compactMap { id -> ScenicMaterialDownloadItem? in
|
||
guard let clip = viewModel.clip(id: id), let url = clip.remoteURL else { return nil }
|
||
return ScenicMaterialDownloadItem(id: id, remoteURL: url,
|
||
fileName: url.pathExtension.isEmpty ? "scenic-material.mp4" : url.lastPathComponent)
|
||
}
|
||
downloadService.start(items: items, batchID: batchID) { [weak self] id, token, event in
|
||
self?.viewModel.receive(event, clipID: id, batchID: token)
|
||
self?.refreshDisplay(animated: false)
|
||
} onFailure: { [weak self] _, error in self?.showToast(error.localizedDescription) }
|
||
} else {
|
||
driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) }
|
||
}
|
||
}
|
||
|
||
@objc private func pauseForBackground() {
|
||
driver.stop()
|
||
downloadService.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?.reloadRemoteMaterials()
|
||
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.reloadRemoteMaterials()
|
||
self.refreshDisplay()
|
||
self.collectionView.setContentOffset(.zero, animated: false)
|
||
} else { self.showToast("请选择保留期内的有效日期范围") }
|
||
}
|
||
present(picker, animated: true)
|
||
}
|
||
|
||
@objc private func resetFilters() {
|
||
viewModel.resetFilters()
|
||
reloadRemoteMaterials()
|
||
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 presentPhotoPermissionSettings() {
|
||
guard presentedViewController == nil else { return }
|
||
let alert = UIAlertController(title: "需要相册保存权限", message: "请允许添加照片和视频,以保存所选素材。", preferredStyle: .alert)
|
||
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
|
||
alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in
|
||
if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
|
||
})
|
||
present(alert, 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)
|
||
}
|
||
}
|
||
|
||
/// 分页末行仅负责触发用户主动加载,加载中禁用,失败后由页面设置重试文案。
|
||
@MainActor
|
||
final class ScenicMaterialPageFooterCell: UICollectionViewCell {
|
||
/// 请求下一页或重试失败页。
|
||
var onLoadMore: (() -> Void)?
|
||
private let button = UIButton(type: .system)
|
||
|
||
/// 创建完整行宽的可访问加载按钮。
|
||
override init(frame: CGRect) {
|
||
super.init(frame: frame)
|
||
button.titleLabel?.font = .systemFont(ofSize: 13)
|
||
button.tintColor = ScenicMaterialsStyle.primary
|
||
button.accessibilityIdentifier = "scenic.materials.loadMore"
|
||
button.addTarget(self, action: #selector(loadMore), 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()
|
||
onLoadMore = nil
|
||
}
|
||
|
||
/// 显示数量、加载中或重试状态,避免重复触发网络请求。
|
||
func configure(title: String, enabled: Bool) {
|
||
button.setTitle(title, for: .normal)
|
||
button.isEnabled = enabled
|
||
}
|
||
|
||
@objc private func loadMore() {
|
||
guard button.isEnabled else { return }
|
||
onLoadMore?()
|
||
}
|
||
}
|
||
|
||
/// 空镜列表的保留期与末尾说明,不参与素材选择。
|
||
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
|
||
}
|
||
}
|