407 lines
22 KiB
Swift
407 lines
22 KiB
Swift
import AVKit
|
|
import Kingfisher
|
|
import SnapKit
|
|
import UIKit
|
|
|
|
/// 从订单详情与任务接口读取的素材库,点位筛选只改变任务列表。
|
|
@MainActor
|
|
final class DroneDockMaterialsViewController: BaseViewController {
|
|
/// 保存当前订单摘要、点位和任务的真实状态。
|
|
let viewModel: DroneDockMaterialsViewModel
|
|
private let thumbnailProvider: ((Int, Int, Bool) -> UIImage?)?
|
|
private let mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)?
|
|
private let footerView = DroneMaterialsFooterView()
|
|
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
|
|
|
|
/// 元数据与媒体分区独立,任务没有素材时也保留其状态。
|
|
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), film(Int, Int), message
|
|
}
|
|
/// 整页刷新更新两个接口;筛选及列表重试只读取任务。
|
|
private enum LoadAction { case refresh, filter(Int?), retry }
|
|
|
|
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
|
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
|
private var loadTask: Task<Void, Never>?
|
|
private var operation: LoadAction?
|
|
private var hasAppeared = false
|
|
private var refreshAfterDelivery = false
|
|
|
|
/// 注入冻结订单范围的只读素材服务。
|
|
init(viewModel: DroneDockMaterialsViewModel,
|
|
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil,
|
|
thumbnailProvider: ((Int, Int, Bool) -> UIImage?)? = nil,
|
|
mediaPreviewControllerFactory: ((URL, Bool, String) -> UIViewController)? = nil) {
|
|
self.viewModel = viewModel
|
|
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.rightBarButtonItem = 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() }
|
|
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
|
|
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<Section, Item>(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.viewModel.selectableMaterialIDs.isEmpty)
|
|
cell.accessibilityIdentifier = "drone.materials.remote.summary"
|
|
cell.onSelectAllTap = { [weak self] in
|
|
guard let self, self.operation == nil 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
|
|
let title = id.flatMap { id in self.viewModel.spots.first { $0.id == id } }.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位"
|
|
cell.apply(title: title, id: id.map(String.init), selected: id == self.displayedSpotID, locked: self.viewModel.detail == nil)
|
|
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.viewModel.detail?.order.canUploadFilm == 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.viewModel.selectableMaterialIDs.contains(identity),
|
|
localImage: self.thumbnailProvider?(taskID, fileID, false),
|
|
allowsRemoteImage: self.thumbnailProvider == nil,
|
|
preview: { [weak self] in self?.previewFile(taskID: taskID, fileID: fileID) },
|
|
select: { [weak self] in
|
|
guard let self, self.operation == nil else { return }
|
|
self.viewModel.toggleSelection(taskID: taskID, fileID: fileID)
|
|
self.applySnapshot(animated: false)
|
|
})
|
|
}
|
|
return cell
|
|
case .film(let taskID, _):
|
|
let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell
|
|
if let film = self.task(taskID)?.film {
|
|
cell.apply(film: film, taskID: taskID, localImage: self.thumbnailProvider?(taskID, film.id, true),
|
|
allowsRemoteImage: self.thumbnailProvider == nil) { [weak self] in self?.previewFilm(taskID: taskID) }
|
|
}
|
|
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 item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
|
|
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .estimated(104), heightDimension: .absolute(36)), subitems: [item])
|
|
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<Section, Item>()
|
|
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))
|
|
var media = task.materials.map { Item.file(task.id, $0.id) }
|
|
if let film = task.film { media.append(.film(task.id, film.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)
|
|
}
|
|
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "",
|
|
primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line",
|
|
enabled: operation == nil && viewModel.selectedCount > 0,
|
|
identifier: "drone.materials.remote.download", progress: nil,
|
|
trailingText: "仅可选择已上传素材")
|
|
let previous = Set(dataSource.snapshot().itemIdentifiers)
|
|
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) })
|
|
dataSource.apply(snapshot, animatingDifferences: animated)
|
|
}
|
|
|
|
private func load(_ action: LoadAction) {
|
|
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, presentedViewController == nil,
|
|
let order = viewModel.detail?.order, order.canUploadFilm == true, 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, viewModel.selectedCount > 0 else { return }
|
|
showAlert(title: "下载功能暂未开放", message: "已选择的素材会保留。当前版本尚未接入下载和保存相册功能。")
|
|
}
|
|
|
|
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 previewFilm(taskID: Int) {
|
|
guard operation == nil, let film = task(taskID)?.film, let url = film.previewURL else { return }
|
|
preview(url: url, isVideo: true, title: film.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
|
|
}
|
|
|
|
|
|
}
|
|
|
|
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, id != displayedSpotID else { return }
|
|
load(.filter(id))
|
|
case .file(let taskID, let fileID):
|
|
previewFile(taskID: taskID, fileID: fileID)
|
|
case .film(let taskID, _):
|
|
previewFilm(taskID: taskID)
|
|
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 = "图片加载失败,请返回后重试"
|
|
}
|
|
}
|
|
}
|
|
}
|