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! 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() 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(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.. 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 } }