import AVKit import Kingfisher import SnapKit import UIKit /// 展示订单任务的原素材并提供成片交付入口,已交付成片由交付确认页展示。 @MainActor final class DroneDockMaterialsViewController: BaseViewController { /// 保存当前订单摘要、点位和任务的真实状态。 let viewModel: DroneDockMaterialsViewModel /// 当前页面的前台下载批次;成功保存后才计入完成数量。 let downloadViewModel: DroneDockMaterialDownloadViewModel private let thumbnailProvider: ((Int, Int) -> UIImage?)? private let mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? private let footerView = DroneMaterialsFooterView() private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController private let downloadSourceDescription: String? private let downloadIsSimulated: Bool /// 元数据与媒体分区独立,任务没有素材时也保留其状态。 private enum Section: Hashable { case order, filters, summary, task(Int), media(Int), message } /// 素材 ID 只在所属任务内唯一,使用任务 ID 共同构成稳定身份。 private enum Item: Hashable { case order, filter(Int?), summary, task(Int), file(Int, Int), message } /// 整页刷新更新两个接口;筛选及列表重试只读取任务。 private enum LoadAction { case refresh, filter(Int?), retry } private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout()) private var dataSource: UICollectionViewDiffableDataSource! private var loadTask: Task? private var operation: LoadAction? private var hasAppeared = false private var refreshAfterDelivery = false private var lastDownloadPhase = DroneDockMaterialDownloadViewModel.Phase.idle private var hasPresentedPhotoPermission = false private var selectionLocked: Bool { downloadViewModel.phase != .idle } /// 注入冻结订单范围的只读素材服务。 init(viewModel: DroneDockMaterialsViewModel, deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil, thumbnailProvider: ((Int, Int) -> UIImage?)? = nil, mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? = nil, downloadViewModel: DroneDockMaterialDownloadViewModel? = nil, downloadSourceDescription: String? = nil, downloadIsSimulated: Bool = false) { self.viewModel = viewModel self.downloadViewModel = downloadViewModel ?? DroneDockMaterialDownloadViewModel( isContextValid: { [weak viewModel] in viewModel?.acceptsDownloadContext() == true }) self.downloadSourceDescription = downloadSourceDescription self.downloadIsSimulated = downloadIsSimulated self.thumbnailProvider = thumbnailProvider self.mediaPreviewControllerFactory = mediaPreviewControllerFactory self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController super.init(nibName: nil, bundle: nil) hidesBottomBarWhenPushed = true } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { loadTask?.cancel() } override func setupNavigationBar() { title = "订单素材库" navigationItem.backButtonDisplayMode = .minimal let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTapped)) refresh.accessibilityLabel = "刷新素材状态" refresh.accessibilityIdentifier = "drone.materials.remote.refresh" navigationItem.rightBarButtonItems = [refresh] } override func setupUI() { view.backgroundColor = .white collectionView.backgroundColor = .white collectionView.alwaysBounceVertical = true collectionView.showsVerticalScrollIndicator = false collectionView.accessibilityIdentifier = "drone.materials.remote.list" collectionView.delegate = self collectionView.register(DroneDockMaterialOrderCell.self, forCellWithReuseIdentifier: "order") collectionView.register(DroneMaterialSelectionCell.self, forCellWithReuseIdentifier: "summary") collectionView.register(DroneDockMaterialRecordCell.self, forCellWithReuseIdentifier: "record") collectionView.register(DroneDockMaterialMessageCell.self, forCellWithReuseIdentifier: "message") collectionView.register(DroneMaterialSeparatorView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "separator") collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "filter") collectionView.register(DroneDockMaterialMediaCell.self, forCellWithReuseIdentifier: "media") let refresh = UIRefreshControl() refresh.tintColor = DroneDockStyle.primary refresh.addTarget(self, action: #selector(refreshTapped), for: .valueChanged) collectionView.refreshControl = refresh view.addSubview(collectionView) view.addSubview(footerView) footerView.accessibilityIdentifier = "drone.materials.remote.footer" footerView.onPrimaryTap = { [weak self] in self?.downloadTapped() } footerView.onSecondaryTap = { [weak self] in self?.downloadViewModel.cancel() } downloadViewModel.onUpdate = { [weak self] in self?.downloadUpdated() } NotificationCenter.default.addObserver(self, selector: #selector(pauseDownloadForBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) configureDataSource() applySnapshot(animated: false) } override func setupConstraints() { collectionView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide) make.leading.trailing.equalToSuperview() make.bottom.equalTo(footerView.snp.top) } footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard !hasAppeared || refreshAfterDelivery else { return } hasAppeared = true refreshAfterDelivery = false load(.refresh) } /// 确认离开后再清理;交互式返回取消或媒体预览覆盖不会丢失当前数据。 override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true || parent == nil else { return } hasAppeared = false downloadViewModel.cancel() loadTask?.cancel() operation = nil viewModel.invalidate() collectionView.refreshControl?.endRefreshing() } private var displayedSpotID: Int? { if case .filter(let id) = operation { return id } return viewModel.selectedSpotID } private func configureDataSource() { dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { [weak self] collection, path, item in guard let self else { return nil } switch item { case .order: let cell = collection.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DroneDockMaterialOrderCell if let order = self.viewModel.detail?.order { cell.apply(order: order) } return cell case .summary: let cell = collection.dequeueReusableCell(withReuseIdentifier: "summary", for: path) as! DroneMaterialSelectionCell cell.apply(recordCount: self.viewModel.total ?? 0, allSelected: self.viewModel.allDownloadableSelected, enabled: self.operation == nil && !self.selectionLocked && !self.viewModel.selectableMaterialIDs.isEmpty) cell.accessibilityIdentifier = "drone.materials.remote.summary" cell.onSelectAllTap = { [weak self] in guard let self, self.operation == nil, !self.selectionLocked else { return } self.viewModel.toggleSelectAll() self.applySnapshot(animated: false) } return cell case .filter(let id): let cell = collection.dequeueReusableCell(withReuseIdentifier: "filter", for: path) as! DroneMaterialFilterCell cell.apply(title: self.filterTitle(for: id), id: id.map(String.init), selected: id == self.displayedSpotID, locked: self.viewModel.detail == nil || self.selectionLocked, wrapsTitle: true) return cell case .task(let taskID): let cell = collection.dequeueReusableCell(withReuseIdentifier: "record", for: path) as! DroneDockMaterialRecordCell if let task = self.task(taskID) { cell.apply(task: task, canDeliver: self.operation == nil && !self.selectionLocked && self.viewModel.detail?.order.canDeliverFilm == true) { [weak self] in self?.openDelivery(taskID: taskID) } } return cell case .file(let taskID, let fileID): let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell if let file = self.task(taskID)?.materials.first(where: { $0.id == fileID }) { let identity = DroneDockMaterialSelectionID(taskID: taskID, fileID: fileID) cell.apply(file: file, taskID: taskID, selected: self.viewModel.selectedMaterialIDs.contains(identity), selectionEnabled: self.operation == nil && !self.selectionLocked && self.viewModel.selectableMaterialIDs.contains(identity), localImage: self.thumbnailProvider?(taskID, fileID), allowsRemoteImage: self.thumbnailProvider == nil, preview: { [weak self] in self?.previewFile(taskID: taskID, fileID: fileID) }, select: { [weak self] in guard let self, self.operation == nil, !self.selectionLocked else { return } self.viewModel.toggleSelection(taskID: taskID, fileID: fileID) self.applySnapshot(animated: false) }) } return cell case .message: let cell = collection.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DroneDockMaterialMessageCell self.configureMessage(cell) return cell } } dataSource.supplementaryViewProvider = { collection, kind, path in collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "separator", for: path) } } private func configureMessage(_ cell: DroneDockMaterialMessageCell) { if operation != nil || viewModel.isLoading || viewModel.isLoadingTasks { cell.apply(title: viewModel.detail == nil ? "正在加载订单素材库" : "正在加载任务素材", detail: "请稍候", identifier: "drone.materials.remote.loading", loading: true) } else if let error = viewModel.detailErrorMessage { cell.apply(title: "订单信息加载失败", detail: error, identifier: "drone.materials.remote.error", error: true) { [weak self] in self?.load(.refresh) } } else if let error = viewModel.tasksErrorMessage { cell.apply(title: "任务素材加载失败", detail: error, identifier: "drone.materials.remote.error", error: true) { [weak self] in self?.load(.retry) } } else { cell.apply(title: displayedSpotID == nil ? "暂无任务记录" : "当前点位暂无任务记录", detail: "拍摄任务与素材更新后,可下拉刷新查看", identifier: "drone.materials.remote.empty") } } 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 } switch sections[index] { case .filters: let maximumWidth = min(200, max(1, environment.container.effectiveContentSize.width - 32)) let sizes = dataSource.snapshot().itemIdentifiers(inSection: .filters).compactMap { item -> CGSize? in guard case .filter(let id) = item else { return nil } return DroneMaterialFilterCell.wrappedSize(title: self.filterTitle(for: id), maximumWidth: maximumWidth) } let width = sizes.reduce(0) { $0 + $1.width } + CGFloat(max(0, sizes.count - 1)) * 8 let height = sizes.map(\.height).max() ?? 40 let group = NSCollectionLayoutGroup.custom(layoutSize: .init(widthDimension: .absolute(max(1, width)), heightDimension: .absolute(height))) { _ in var x: CGFloat = 0 return sizes.map { size in defer { x += size.width + 8 } return NSCollectionLayoutGroupCustomItem(frame: CGRect(x: x, y: 0, width: size.width, height: size.height)) } } let section = NSCollectionLayoutSection(group: group) section.orthogonalScrollingBehavior = .continuous section.interGroupSpacing = 8 section.contentInsets = .init(top: 0, leading: 16, bottom: 8, trailing: 16) return section case .media: let width = (environment.container.effectiveContentSize.width - 44) / 2 let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1))) let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 9 / 16 + 51)), repeatingSubitem: item, count: 2) group.interItemSpacing = .fixed(12) let section = NSCollectionLayoutSection(group: group) section.contentInsets = .init(top: 0, leading: 16, bottom: 16, trailing: 16) section.interGroupSpacing = 12 section.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem( layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(1)), elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom)] return section case .message: return self.singleColumnSection(height: .absolute(250)) case .summary: return self.singleColumnSection(height: .absolute(46)) default: return self.singleColumnSection(height: .estimated(90)) } } } private func singleColumnSection(height: NSCollectionLayoutDimension) -> NSCollectionLayoutSection { let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: height)) let group = NSCollectionLayoutGroup.vertical(layoutSize: item.layoutSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) section.contentInsets = .init(top: 0, leading: 16, bottom: 0, trailing: 16) return section } private func applySnapshot(animated: Bool) { guard dataSource != nil else { return } var snapshot = NSDiffableDataSourceSnapshot() if viewModel.detail != nil { snapshot.appendSections([.order, .filters]) snapshot.appendItems([.order], toSection: .order) snapshot.appendItems([.filter(nil)] + viewModel.spots.map { .filter($0.id) }, toSection: .filters) } if operation == nil && !viewModel.isLoading && !viewModel.isLoadingTasks && viewModel.tasksErrorMessage == nil && viewModel.detailErrorMessage == nil && viewModel.total != nil { snapshot.appendSections([.summary]) snapshot.appendItems([.summary], toSection: .summary) for task in viewModel.tasks { snapshot.appendSections([.task(task.id)]) snapshot.appendItems([.task(task.id)], toSection: .task(task.id)) let media = task.materials.map { Item.file(task.id, $0.id) } if !media.isEmpty { snapshot.appendSections([.media(task.id)]) snapshot.appendItems(media, toSection: .media(task.id)) } } } if viewModel.tasks.isEmpty || operation != nil || viewModel.isLoading || viewModel.isLoadingTasks || viewModel.detailErrorMessage != nil || viewModel.tasksErrorMessage != nil { snapshot.appendSections([.message]) snapshot.appendItems([.message], toSection: .message) } updateDownloadFooter() let previous = Set(dataSource.snapshot().itemIdentifiers) snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) }) dataSource.apply(snapshot, animatingDifferences: animated) } private func load(_ action: LoadAction) { guard !selectionLocked else { collectionView.refreshControl?.endRefreshing() return } loadTask?.cancel() operation = action applySnapshot(animated: false) loadTask = Task { @MainActor [weak self] in guard let self else { return } switch action { case .refresh: await self.viewModel.refresh() case .filter(let id): await self.viewModel.selectSpot(id: id) case .retry: await self.viewModel.retryTasks() } guard !Task.isCancelled else { return } self.operation = nil self.collectionView.refreshControl?.endRefreshing() self.applySnapshot(animated: true) } } @objc private func refreshTapped() { load(.refresh) } private func task(_ id: Int) -> DroneDockMaterialTask? { viewModel.tasks.first { $0.id == id } } private func openDelivery(taskID: Int) { guard operation == nil, !selectionLocked, presentedViewController == nil, let order = viewModel.detail?.order, order.canDeliverFilm, task(taskID) != nil else { return } let sheet = DroneDockDeliveryEntry.makeMethodSheet(order: order, context: viewModel.context, taskID: taskID, controllerFactory: deliveryControllerFactory) { [weak self] in guard let self else { return } self.refreshAfterDelivery = true guard self.viewIfLoaded?.window != nil else { return } self.refreshAfterDelivery = false self.load(.refresh) } present(sheet, animated: true) } private func downloadTapped() { guard operation == nil else { return } switch downloadViewModel.phase { case .idle: _ = downloadViewModel.start(items: viewModel.selectedDownloadItems()) applySnapshot(animated: false) case .downloading: downloadViewModel.pause() case .paused: downloadViewModel.resume() case .finished: if downloadViewModel.failedCount > 0 { downloadViewModel.retryFailed() } else { downloadViewModel.cancel() } } } @objc private func pauseDownloadForBackground() { downloadViewModel.pause() } private func downloadUpdated() { if lastDownloadPhase != downloadViewModel.phase { lastDownloadPhase = downloadViewModel.phase applySnapshot(animated: false) } else { updateDownloadFooter() } if !downloadViewModel.permissionDenied { hasPresentedPhotoPermission = false } if downloadViewModel.permissionDenied, !hasPresentedPhotoPermission, viewIfLoaded?.window != nil, presentedViewController == nil { hasPresentedPhotoPermission = true 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 updateDownloadFooter() { navigationItem.rightBarButtonItem?.isEnabled = !selectionLocked let model = downloadViewModel let identifier = "drone.materials.remote.download" switch model.phase { case .idle: footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: model.lastErrorMessage ?? downloadSourceDescription ?? "", primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line", enabled: operation == nil && viewModel.selectedCount > 0, identifier: identifier, progress: nil, trailingText: "仅可选择已上传素材") case .downloading, .paused: let paused = model.phase == .paused footerView.apply(title: "\(paused ? "已暂停" : "下载中") · \(downloadIsSimulated ? "演示完成" : "已保存") \(model.completedCount)/\(model.totalCount) 项", detail: downloadSourceDescription ?? "请保持页面开启,切到后台将暂停", primaryTitle: paused ? "继续下载" : "暂停下载", primarySymbol: paused ? "play.fill" : "pause.fill", enabled: true, identifier: identifier, progress: model.progress, secondaryTitle: "取消下载", trailingText: "\(Int(model.progress * 100))%") case .finished: let failed = model.failedCount > 0 let saved = "\(downloadIsSimulated ? "演示完成" : "已保存") \(model.completedCount) 项" footerView.apply(title: failed ? "\(saved) · 失败 \(model.failedCount) 项" : saved, detail: failed ? model.lastErrorMessage ?? "失败项可重试,成功项已保存相册" : downloadSourceDescription ?? "可在系统相册查看", primaryTitle: failed ? "重试失败项" : "继续选择", primarySymbol: failed ? "arrow.clockwise" : "checkmark", enabled: true, identifier: identifier, progress: nil, secondaryTitle: failed ? "继续选择" : nil, tone: failed ? .orange : .green, resultSymbol: failed ? "exclamationmark.circle.fill" : "checkmark.circle.fill") } } private func previewFile(taskID: Int, fileID: Int) { guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return } preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材") } private func preview(url: URL, isVideo: Bool, title: String) { if let mediaPreviewControllerFactory { navigationController?.pushViewController(mediaPreviewControllerFactory(url, isVideo, title), animated: true) } else if isVideo { let player = AVPlayerViewController() player.player = AVPlayer(url: url) present(player, animated: true) { player.player?.play() } } else { navigationController?.pushViewController(DroneDockMaterialImageViewController(url: url, title: title), animated: true) } } private static func usable(_ value: String?, fallback: String) -> String { DroneDockHomeMetric.usableText(value) ?? fallback } private func filterTitle(for id: Int?) -> String { id.flatMap { id in viewModel.spots.first { $0.id == id } } .map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位" } } extension DroneDockMaterialsViewController: UICollectionViewDelegate { /// 点位只重读任务;仅已就绪且有合法地址的媒体可进入真实预览。 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let item = dataSource.itemIdentifier(for: indexPath) else { return } switch item { case .filter(let id): guard viewModel.detail != nil, !selectionLocked, id != displayedSpotID else { return } load(.filter(id)) case .file(let taskID, let fileID): previewFile(taskID: taskID, fileID: fileID) default: break } } } /// 通过 Kingfisher 展示真实图片,加载失败保留明确提示。 @MainActor private final class DroneDockMaterialImageViewController: UIViewController { private let url: URL private let imageView = UIImageView() private let message = UILabel() /// 仅接收素材模型已经校验可预览的 HTTP(S) 地址。 init(url: URL, title: String) { self.url = url super.init(nibName: nil, bundle: nil) self.title = title hidesBottomBarWhenPushed = true } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black imageView.contentMode = .scaleAspectFit imageView.accessibilityIdentifier = "drone.materials.remote.preview.image" message.text = "正在加载图片" message.textColor = .white message.textAlignment = .center message.numberOfLines = 0 view.addSubview(imageView) view.addSubview(message) imageView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) } message.snp.makeConstraints { make in make.center.equalToSuperview(); make.leading.trailing.equalToSuperview().inset(24) } imageView.kf.setImage(with: url) { [weak self] result in switch result { case .success: self?.message.isHidden = true case .failure: self?.message.text = "图片加载失败,请返回后重试" } } } }