602 lines
33 KiB
Swift
602 lines
33 KiB
Swift
import AVKit
|
|
import PhotosUI
|
|
import SnapKit
|
|
import UIKit
|
|
import UniformTypeIdentifiers
|
|
|
|
/// 订单列表与任务素材入口共用的云端成片交付页,一个任务保存一个视频。
|
|
@MainActor
|
|
final class DroneDockDeliveryViewController: BaseViewController {
|
|
/// 当前订单、任务选择及上传保存状态。
|
|
let viewModel: DroneDockDeliveryViewModel
|
|
private let onDidSave: (() -> Void)?
|
|
private let videoPicker: (@MainActor () async throws -> DroneDockDeliveryVideo?)?
|
|
private var operationTask: Task<Void, Never>?
|
|
private var hasAppeared = false
|
|
private var isRefreshing = false
|
|
private var isPicking = false
|
|
private var isStartingSubmission = false
|
|
private var pickerError: String?
|
|
private var ownedVideoURLs: Set<URL> = []
|
|
private var previousGestureEnabled: Bool?
|
|
private var onCloseSheet: (() -> Void)?
|
|
private weak var trackedNavigationController: UINavigationController?
|
|
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
|
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
|
private let footer = UIView()
|
|
private let stateLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
|
private let progressView = UIProgressView(progressViewStyle: .default)
|
|
private let footerNote = DroneDockStyle.label("保存成功后,游客可在小程序相册查看", size: 11, color: DroneDockDeliveryDesign.secondary)
|
|
private let submitButton = UIButton(type: .system)
|
|
private let selectedVideoView = DroneDockDeliverySelectedVideoView()
|
|
private var selectedVideoHeight: Constraint?
|
|
private var selectedVideoBottom: Constraint?
|
|
private var progressHeight: Constraint?
|
|
private var displayedVideoHeight: CGFloat = 0
|
|
|
|
/// 点位横向排列,其余信息按步骤向下展示。
|
|
private enum Section: Hashable { case order, points, tasks, state }
|
|
/// 身份稳定的 Diffable 项目,上传进度不改变选择。
|
|
private enum Item: Hashable { case order, intro, point(Int), task(Int), boundTask, choosePoint, emptyTasks, state }
|
|
|
|
/// 注入上传状态、真实保存回调和可测试的视频选择入口。
|
|
init(viewModel: DroneDockDeliveryViewModel, onDidSave: (() -> Void)? = nil,
|
|
videoPicker: (@MainActor () async throws -> DroneDockDeliveryVideo?)? = nil) {
|
|
self.viewModel = viewModel
|
|
self.onDidSave = onDidSave
|
|
self.videoPicker = videoPicker
|
|
super.init(nibName: nil, bundle: nil)
|
|
hidesBottomBarWhenPushed = true
|
|
}
|
|
|
|
@available(*, unavailable)
|
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
|
|
deinit {
|
|
operationTask?.cancel()
|
|
ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard)
|
|
}
|
|
|
|
/// 交付入口以弹窗展示时复用上传流程,并将关闭动作纳入处理中退出确认。
|
|
func configureSheetPresentation(onClose: @escaping () -> Void) {
|
|
onCloseSheet = onClose
|
|
}
|
|
|
|
override func setupNavigationBar() {
|
|
title = "云端上传"
|
|
navigationItem.backButtonDisplayMode = .minimal
|
|
let appearance = UINavigationBarAppearance()
|
|
appearance.configureWithOpaqueBackground()
|
|
appearance.backgroundColor = DroneDockDeliveryDesign.background
|
|
appearance.shadowColor = .clear
|
|
appearance.titleTextAttributes = [.foregroundColor: DroneDockDeliveryDesign.text, .font: UIFont.systemFont(ofSize: 18, weight: .semibold)]
|
|
navigationItem.standardAppearance = appearance
|
|
navigationItem.scrollEdgeAppearance = appearance
|
|
navigationController?.navigationBar.tintColor = DroneDockDeliveryDesign.text
|
|
let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(backTapped))
|
|
back.accessibilityLabel = onCloseSheet == nil ? "返回" : "返回交付方式"
|
|
back.accessibilityIdentifier = "drone.delivery.back"
|
|
navigationItem.leftBarButtonItem = back
|
|
let close = UIBarButtonItem(image: UIImage(systemName: "xmark"), style: .plain, target: self, action: #selector(closeSheetTapped))
|
|
close.accessibilityLabel = "关闭成片交付"
|
|
close.accessibilityIdentifier = "drone.delivery.sheet.close"
|
|
navigationItem.rightBarButtonItem = close
|
|
}
|
|
|
|
override func setupUI() {
|
|
view.backgroundColor = DroneDockDeliveryDesign.background
|
|
collectionView.backgroundColor = .clear
|
|
collectionView.alwaysBounceVertical = true
|
|
collectionView.accessibilityIdentifier = "drone.delivery.remote.list"
|
|
collectionView.delegate = self
|
|
collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "point")
|
|
collectionView.register(DroneDockDeliveryTextCell.self, forCellWithReuseIdentifier: "text")
|
|
collectionView.register(DroneDockDeliveryCustomerCell.self, forCellWithReuseIdentifier: "customer")
|
|
collectionView.register(DroneDockDeliveryIntroCell.self, forCellWithReuseIdentifier: "intro")
|
|
collectionView.register(DroneDockDeliveryBoundTaskCell.self, forCellWithReuseIdentifier: "boundTask")
|
|
let refresh = UIRefreshControl()
|
|
refresh.addTarget(self, action: #selector(refreshTapped), for: .valueChanged)
|
|
collectionView.refreshControl = refresh
|
|
footer.backgroundColor = .white
|
|
stateLabel.numberOfLines = 0
|
|
stateLabel.accessibilityIdentifier = "drone.delivery.progressText"
|
|
progressView.progressTintColor = DroneDockDeliveryDesign.primary
|
|
progressView.accessibilityIdentifier = "drone.delivery.progress"
|
|
var configuration = UIButton.Configuration.filled()
|
|
configuration.imagePadding = 10
|
|
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 20, weight: .medium)
|
|
configuration.cornerStyle = .fixed
|
|
configuration.background.cornerRadius = 12
|
|
configuration.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 14, bottom: 0, trailing: 14)
|
|
submitButton.configuration = configuration
|
|
submitButton.configurationUpdateHandler = { button in
|
|
guard var configuration = button.configuration else { return }
|
|
let foreground = button.isEnabled || configuration.showsActivityIndicator ? UIColor.white : DroneDockDeliveryDesign.primary.withAlphaComponent(0.55)
|
|
configuration.background.backgroundColor = button.isEnabled || configuration.showsActivityIndicator
|
|
? DroneDockDeliveryDesign.primary : UIColor(hex: 0xE5EFFF)
|
|
configuration.baseForegroundColor = foreground
|
|
configuration.imageColorTransformer = UIConfigurationColorTransformer { _ in foreground }
|
|
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
|
|
var result = attributes
|
|
result.font = .systemFont(ofSize: 17, weight: .semibold)
|
|
result.foregroundColor = foreground
|
|
return result
|
|
}
|
|
button.configuration = configuration
|
|
}
|
|
submitButton.accessibilityIdentifier = "drone.delivery.submit"
|
|
submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
|
|
view.addSubview(collectionView)
|
|
view.addSubview(selectedVideoView)
|
|
selectedVideoView.isHidden = true
|
|
view.addSubview(footer)
|
|
footerNote.numberOfLines = 0
|
|
footerNote.textAlignment = .center
|
|
[stateLabel, progressView, submitButton, footerNote].forEach(footer.addSubview)
|
|
let divider = UIView()
|
|
divider.backgroundColor = DroneDockDeliveryDesign.border
|
|
footer.addSubview(divider)
|
|
divider.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(0.5) }
|
|
configureDataSource()
|
|
applySnapshot(animated: false)
|
|
}
|
|
|
|
override func setupConstraints() {
|
|
collectionView.snp.makeConstraints { make in
|
|
make.top.equalTo(view.safeAreaLayoutGuide)
|
|
make.leading.trailing.equalToSuperview()
|
|
make.bottom.equalTo(selectedVideoView.snp.top)
|
|
}
|
|
selectedVideoView.snp.makeConstraints { make in
|
|
make.leading.trailing.equalToSuperview().inset(20)
|
|
selectedVideoBottom = make.bottom.equalTo(footer.snp.top).constraint
|
|
selectedVideoHeight = make.height.equalTo(0).constraint
|
|
}
|
|
footer.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
|
|
stateLabel.snp.makeConstraints { make in make.top.equalToSuperview().offset(10); make.leading.trailing.equalToSuperview().inset(20) }
|
|
progressView.snp.makeConstraints { make in
|
|
make.top.equalTo(stateLabel.snp.bottom).offset(4)
|
|
make.leading.trailing.equalTo(stateLabel)
|
|
progressHeight = make.height.equalTo(0).constraint
|
|
}
|
|
submitButton.snp.makeConstraints { make in
|
|
make.top.equalTo(progressView.snp.bottom).offset(8)
|
|
make.leading.trailing.equalToSuperview().inset(20)
|
|
make.height.equalTo(52)
|
|
}
|
|
footerNote.snp.makeConstraints { make in
|
|
make.top.equalTo(submitButton.snp.bottom).offset(8)
|
|
make.leading.trailing.equalTo(submitButton)
|
|
make.bottom.equalTo(footer.safeAreaLayoutGuide).offset(-8)
|
|
}
|
|
}
|
|
|
|
override func viewDidLayoutSubviews() {
|
|
super.viewDidLayoutSubviews()
|
|
updateSelectedVideoLayout()
|
|
}
|
|
|
|
override func viewWillAppear(_ animated: Bool) {
|
|
super.viewWillAppear(animated)
|
|
if onCloseSheet != nil {
|
|
navigationController?.setNavigationBarHidden(false, animated: false)
|
|
navigationController?.isModalInPresentation = true
|
|
navigationController?.sheetPresentationController?.detents = [.large()]
|
|
navigationController?.sheetPresentationController?.selectedDetentIdentifier = .large
|
|
}
|
|
trackedNavigationController = navigationController
|
|
if previousGestureEnabled == nil { previousGestureEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled }
|
|
guard !hasAppeared else { updateFooter(); return }
|
|
hasAppeared = true
|
|
refresh()
|
|
}
|
|
|
|
/// 预览和系统选择器覆盖不清空上传页,只有确认离开后才取消并清理。
|
|
override func viewDidDisappear(_ animated: Bool) {
|
|
super.viewDidDisappear(animated)
|
|
trackedNavigationController?.interactivePopGestureRecognizer?.isEnabled = previousGestureEnabled ?? true
|
|
guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true || parent == nil else { return }
|
|
operationTask?.cancel()
|
|
viewModel.invalidate()
|
|
ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard)
|
|
ownedVideoURLs.removeAll()
|
|
hasAppeared = false
|
|
}
|
|
|
|
private func configureDataSource() {
|
|
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
|
|
guard let self else { return nil }
|
|
if item == .order {
|
|
let cell = list.dequeueReusableCell(withReuseIdentifier: "customer", for: path) as! DroneDockDeliveryCustomerCell
|
|
let order = self.viewModel.detail?.order ?? self.viewModel.order
|
|
cell.apply(title: order.touristTitle, orderNumber: order.orderNumber)
|
|
return cell
|
|
}
|
|
if item == .intro { return list.dequeueReusableCell(withReuseIdentifier: "intro", for: path) }
|
|
if item == .boundTask {
|
|
let cell = list.dequeueReusableCell(withReuseIdentifier: "boundTask", for: path) as! DroneDockDeliveryBoundTaskCell
|
|
cell.apply(task: self.viewModel.selectedTask)
|
|
return cell
|
|
}
|
|
if case .point(let id) = item {
|
|
let cell = list.dequeueReusableCell(withReuseIdentifier: "point", for: path) as! DroneMaterialFilterCell
|
|
let title = self.viewModel.spots.first { $0.id == id }.map { Self.text($0.name, fallback: "点位 \(id)") } ?? "点位 \(id)"
|
|
cell.apply(title: title, id: String(id), selected: self.viewModel.selectedSpotID == id, locked: self.locked, wrapsTitle: true)
|
|
cell.accessibilityIdentifier = "drone.delivery.point.\(id)"
|
|
return cell
|
|
}
|
|
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! DroneDockDeliveryTextCell
|
|
self.configureText(cell, item: item)
|
|
return cell
|
|
}
|
|
}
|
|
|
|
private func configureText(_ cell: DroneDockDeliveryTextCell, item: Item) {
|
|
switch item {
|
|
case .choosePoint:
|
|
cell.apply(title: "选择点位与拍摄任务", body: "每个拍摄任务可交付一个视频成片", id: "drone.delivery.chooseTask")
|
|
case .task(let id):
|
|
guard let task = viewModel.tasks.first(where: { $0.id == id }) else { return }
|
|
let number = task.sequence.map(String.init) ?? String(task.id)
|
|
let film = task.film.map { "已有成片:\(Self.text($0.fileName, fallback: "视频成片"))\n重新上传将替换此任务的原成片" } ?? "尚未交付成片"
|
|
cell.apply(title: "任务 \(number) · \(Self.text(task.spotName, fallback: "点位 \(task.spotID)"))",
|
|
body: "\(Self.text(task.airLineName, fallback: "航线待确认")) · \(Self.flightTitle(task.flightStatus))\n\(Self.text(task.createdAt, fallback: "时间待确认"))\n\(film)",
|
|
id: "drone.delivery.task.\(id)", selected: viewModel.selectedTaskID == id, selectable: true)
|
|
case .emptyTasks:
|
|
let noTasks = viewModel.tasks.isEmpty
|
|
cell.apply(title: noTasks ? "暂无可交付的拍摄任务" : "此点位暂无拍摄任务", body: "请在拍摄任务创建后刷新,再选择对应任务上传成片", id: "drone.delivery.empty")
|
|
case .state:
|
|
if isRefreshing || viewModel.isLoading { cell.apply(title: "正在读取订单与任务", body: nil, id: "drone.delivery.loading") }
|
|
else if let error = viewModel.loadErrorMessage {
|
|
cell.apply(title: "订单信息加载失败", body: error, id: "drone.delivery.error", button: "重试", actionID: "drone.delivery.retry") { [weak self] in self?.refresh() }
|
|
} else if let error = pickerError ?? viewModel.submissionErrorMessage {
|
|
cell.apply(title: "交付尚未完成", body: error, id: "drone.delivery.error")
|
|
} else if let success = viewModel.successMessage {
|
|
cell.apply(title: success, body: viewModel.refreshWarning ?? "成片已保存,可返回素材库查看", id: "drone.delivery.success")
|
|
} else if !viewModel.canUpload {
|
|
cell.apply(title: "当前订单暂不可上传成片", body: "请确认订单已付款且已有有效拍摄任务,刷新后重试", id: "drone.delivery.unavailable")
|
|
} else { cell.apply(title: "上传说明", body: "选择一段本地视频,预览确认后再上传", id: "drone.delivery.hint") }
|
|
default: break
|
|
}
|
|
}
|
|
|
|
private var locked: Bool { isRefreshing || isPicking || isStartingSubmission || viewModel.isLoading || viewModel.isSubmitting }
|
|
|
|
private func makeLayout() -> UICollectionViewLayout {
|
|
UICollectionViewCompositionalLayout { [weak self] index, environment in
|
|
guard let self, let source = self.dataSource else { return nil }
|
|
let sections = source.snapshot().sectionIdentifiers
|
|
guard sections.indices.contains(index) else { return nil }
|
|
let points = sections[index] == .points
|
|
if points, !self.viewModel.spots.isEmpty {
|
|
let maximumWidth = min(200, max(1, environment.container.effectiveContentSize.width - 32))
|
|
let sizes = self.viewModel.spots.map {
|
|
DroneMaterialFilterCell.wrappedSize(title: Self.text($0.name, fallback: "点位 \($0.id)"), maximumWidth: maximumWidth)
|
|
}
|
|
let width = sizes.reduce(0) { $0 + $1.width } + CGFloat(sizes.count - 1) * 10
|
|
let height = sizes.map(\.height).max() ?? 40
|
|
let group = NSCollectionLayoutGroup.custom(layoutSize: .init(widthDimension: .absolute(width), heightDimension: .absolute(height))) { _ in
|
|
var x: CGFloat = 0
|
|
return sizes.map { size in
|
|
defer { x += size.width + 10 }
|
|
return NSCollectionLayoutGroupCustomItem(frame: CGRect(x: x, y: 0, width: size.width, height: size.height))
|
|
}
|
|
}
|
|
let section = NSCollectionLayoutSection(group: group)
|
|
section.contentInsets = .init(top: 0, leading: 20, bottom: 12, trailing: 20)
|
|
section.orthogonalScrollingBehavior = .continuous
|
|
return section
|
|
}
|
|
let size = NSCollectionLayoutSize(widthDimension: points ? .estimated(112) : .fractionalWidth(1), heightDimension: points ? .absolute(40) : .estimated(100))
|
|
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: points ? .fractionalHeight(1) : .estimated(100)))
|
|
let group = NSCollectionLayoutGroup.vertical(layoutSize: size, subitems: [item])
|
|
let section = NSCollectionLayoutSection(group: group)
|
|
section.contentInsets = .init(top: 0, leading: 20, bottom: 12, trailing: 20)
|
|
section.interGroupSpacing = 10
|
|
if points { section.orthogonalScrollingBehavior = .continuous }
|
|
return section
|
|
}
|
|
}
|
|
|
|
private func applySnapshot(animated: Bool) {
|
|
guard dataSource != nil else { return }
|
|
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
|
snapshot.appendSections([.order])
|
|
snapshot.appendItems([.order, .intro], toSection: .order)
|
|
if viewModel.detail != nil && !isRefreshing {
|
|
if viewModel.isTaskScoped {
|
|
snapshot.appendSections([.tasks])
|
|
snapshot.appendItems([.boundTask], toSection: .tasks)
|
|
} else {
|
|
snapshot.appendItems([.choosePoint], toSection: .order)
|
|
snapshot.appendSections([.points, .tasks])
|
|
snapshot.appendItems(viewModel.spots.map { .point($0.id) }, toSection: .points)
|
|
if viewModel.selectedSpotID != nil {
|
|
snapshot.appendItems(viewModel.filteredTasks.isEmpty ? [.emptyTasks] : viewModel.filteredTasks.map { .task($0.id) }, toSection: .tasks)
|
|
} else if viewModel.tasks.isEmpty { snapshot.appendItems([.emptyTasks], toSection: .tasks) }
|
|
}
|
|
}
|
|
if isRefreshing || viewModel.isLoading || viewModel.loadErrorMessage != nil || pickerError != nil
|
|
|| viewModel.submissionErrorMessage != nil || viewModel.successMessage != nil || !viewModel.canUpload {
|
|
snapshot.appendSections([.state])
|
|
snapshot.appendItems([.state], toSection: .state)
|
|
}
|
|
let previous = Set(dataSource.snapshot().itemIdentifiers)
|
|
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) })
|
|
collectionView.collectionViewLayout.invalidateLayout()
|
|
dataSource.apply(snapshot, animatingDifferences: animated)
|
|
updateFooter()
|
|
}
|
|
|
|
private func updateFooter() {
|
|
guard isViewLoaded else { return }
|
|
let working = viewModel.isSubmitting
|
|
let status: String
|
|
switch viewModel.phase {
|
|
case .validating: status = "正在核对订单与任务…"
|
|
case .uploading: status = "正在上传视频 \(viewModel.progress)%"
|
|
case .saving: status = "视频上传完成,正在保存成片…"
|
|
case .succeeded: status = "成片交付成功"
|
|
case .idle: status = isPicking ? "正在准备视频文件…" : viewModel.uploadedFileURL != nil ? "视频已上传,可重试保存成片" : viewModel.video != nil ? "已选择 1 个视频,预览确认后上传" : "请选择一个视频成片,选中后再上传"
|
|
}
|
|
stateLabel.text = status
|
|
progressView.isHidden = !working
|
|
progressHeight?.update(offset: working ? 3 : 0)
|
|
progressView.progress = Float(viewModel.progress) / 100
|
|
let title = viewModel.successMessage != nil ? "交付成功" : viewModel.video == nil ? "去相册选视频" : "上传所选视频"
|
|
submitButton.setTitle(isPicking ? "正在准备视频…" : working ? "处理中…" : title, for: .normal)
|
|
submitButton.configuration?.title = submitButton.title(for: .normal)
|
|
submitButton.configuration?.image = UIImage(systemName: viewModel.video == nil ? "photo.on.rectangle" : "square.and.arrow.up")
|
|
submitButton.configuration?.showsActivityIndicator = working || isPicking
|
|
submitButton.isEnabled = (viewModel.video == nil ? viewModel.canChooseVideo : viewModel.canSubmit) && !locked
|
|
submitButton.setNeedsUpdateConfiguration()
|
|
selectedVideoView.isHidden = viewModel.video == nil
|
|
selectedVideoBottom?.update(offset: viewModel.video == nil ? 0 : -16)
|
|
updateSelectedVideoLayout()
|
|
selectedVideoView.apply(video: viewModel.video, enabled: viewModel.canChooseVideo && !locked,
|
|
preview: { [weak self] in self?.previewVideo() },
|
|
replace: { [weak self] in self?.chooseVideo(fromFiles: false) },
|
|
remove: { [weak self] in self?.removeVideo() })
|
|
collectionView.refreshControl?.isEnabled = !working && !isPicking && !isRefreshing
|
|
navigationController?.interactivePopGestureRecognizer?.isEnabled = !working && !isStartingSubmission && !isPicking && (previousGestureEnabled ?? true)
|
|
}
|
|
|
|
private func updateSelectedVideoLayout() {
|
|
guard isViewLoaded else { return }
|
|
let naturalHeight = max(1, view.bounds.width - 64) * 9 / 16 + 119
|
|
let available = max(220, view.safeAreaLayoutGuide.layoutFrame.height * 0.44)
|
|
let height = viewModel.video == nil ? 0 : min(naturalHeight, available)
|
|
guard abs(displayedVideoHeight - height) > 0.5 else { return }
|
|
displayedVideoHeight = height
|
|
selectedVideoHeight?.update(offset: height)
|
|
}
|
|
|
|
private func refresh() {
|
|
guard !viewModel.isSubmitting, !isStartingSubmission, !isPicking else { collectionView.refreshControl?.endRefreshing(); return }
|
|
operationTask?.cancel()
|
|
isRefreshing = true
|
|
pickerError = nil
|
|
applySnapshot(animated: false)
|
|
operationTask = Task { @MainActor [weak self] in
|
|
guard let self else { return }
|
|
await self.viewModel.refresh()
|
|
guard !Task.isCancelled else { return }
|
|
self.isRefreshing = false
|
|
self.discardUnusedVideos()
|
|
self.collectionView.refreshControl?.endRefreshing()
|
|
self.applySnapshot(animated: true)
|
|
}
|
|
}
|
|
|
|
@objc private func refreshTapped() { refresh() }
|
|
|
|
@objc private func submitTapped() {
|
|
if viewModel.video == nil {
|
|
chooseVideo(fromFiles: false)
|
|
return
|
|
}
|
|
guard viewModel.canSubmit, !locked else { return }
|
|
if viewModel.needsReplacementConfirmation {
|
|
let alert = UIAlertController(title: "替换此任务的成片?", message: "保存成功后,游客将看到新视频。保存失败会保留原成片。", preferredStyle: .alert)
|
|
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
|
|
let replace = UIAlertAction(title: "替换成片", style: .destructive) { [weak self] _ in self?.submit(confirmed: true) }
|
|
alert.addAction(replace)
|
|
present(alert, animated: true)
|
|
} else { submit(confirmed: false) }
|
|
}
|
|
|
|
private func submit(confirmed: Bool) {
|
|
guard viewModel.canSubmit, !locked else { return }
|
|
pickerError = nil
|
|
isStartingSubmission = true
|
|
updateFooter()
|
|
operationTask = Task { @MainActor [weak self] in
|
|
guard let self else { return }
|
|
await self.viewModel.submit(confirmReplacement: confirmed) { [weak self] _ in self?.applySnapshot(animated: false) }
|
|
guard !Task.isCancelled else { return }
|
|
self.isStartingSubmission = false
|
|
self.discardUnusedVideos()
|
|
self.applySnapshot(animated: true)
|
|
if self.viewModel.successMessage != nil { self.onDidSave?() }
|
|
}
|
|
}
|
|
|
|
private func chooseVideo(fromFiles: Bool) {
|
|
guard viewModel.canChooseVideo, !locked else { return }
|
|
pickerError = nil
|
|
if let videoPicker {
|
|
loadPickedVideo { try await videoPicker() }
|
|
} else if fromFiles {
|
|
let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.movie], asCopy: true)
|
|
picker.allowsMultipleSelection = false
|
|
picker.delegate = self
|
|
present(picker, animated: true)
|
|
} else {
|
|
var configuration = PHPickerConfiguration(photoLibrary: .shared())
|
|
configuration.filter = .videos
|
|
configuration.selectionLimit = 1
|
|
configuration.preferredAssetRepresentationMode = .current
|
|
let picker = PHPickerViewController(configuration: configuration)
|
|
picker.delegate = self
|
|
present(picker, animated: true)
|
|
}
|
|
}
|
|
|
|
private func loadPickedVideo(_ loader: @escaping @MainActor () async throws -> DroneDockDeliveryVideo?) {
|
|
isPicking = true
|
|
applySnapshot(animated: false)
|
|
operationTask = Task { @MainActor [weak self] in
|
|
guard let self else { return }
|
|
defer {
|
|
if !Task.isCancelled {
|
|
self.isPicking = false
|
|
self.applySnapshot(animated: true)
|
|
}
|
|
}
|
|
do {
|
|
if let selected = try await loader() {
|
|
guard !Task.isCancelled, self.viewModel.canChooseVideo else { DroneDockDeliveryVideoLoader.discard(selected.url); return }
|
|
do { _ = try DroneDockFilmPolicy.validate(video: selected) }
|
|
catch { DroneDockDeliveryVideoLoader.discard(selected.url); throw error }
|
|
self.viewModel.selectVideo(selected)
|
|
if self.viewModel.video?.id == selected.id {
|
|
self.ownedVideoURLs.insert(selected.url)
|
|
self.discardUnusedVideos()
|
|
} else { DroneDockDeliveryVideoLoader.discard(selected.url) }
|
|
}
|
|
} catch {
|
|
if !Task.isCancelled { self.pickerError = error.localizedDescription }
|
|
}
|
|
guard !Task.isCancelled else { return }
|
|
}
|
|
}
|
|
|
|
private func discardUnusedVideos() {
|
|
let unused = ownedVideoURLs.filter { $0 != viewModel.video?.url }
|
|
unused.forEach(DroneDockDeliveryVideoLoader.discard)
|
|
ownedVideoURLs.subtract(unused)
|
|
}
|
|
|
|
private func removeVideo() {
|
|
guard !locked else { return }
|
|
if let video = viewModel.video { DroneDockDeliveryVideoLoader.discard(video.url); ownedVideoURLs.remove(video.url) }
|
|
viewModel.removeVideo()
|
|
pickerError = nil
|
|
applySnapshot(animated: true)
|
|
}
|
|
|
|
private func previewVideo() {
|
|
guard !locked, let video = viewModel.video else { return }
|
|
let player = AVPlayerViewController()
|
|
player.player = AVPlayer(url: video.url)
|
|
present(player, animated: true) { player.player?.play() }
|
|
}
|
|
|
|
@objc private func backTapped() {
|
|
requestExit { [weak self] in self?.navigationController?.popViewController(animated: true) }
|
|
}
|
|
|
|
@objc private func closeSheetTapped() {
|
|
requestExit { [weak self] in
|
|
guard let self else { return }
|
|
if let onCloseSheet = self.onCloseSheet { onCloseSheet() }
|
|
else if (self.navigationController?.viewControllers.count ?? 0) > 1 { self.navigationController?.popViewController(animated: true) }
|
|
else { self.dismiss(animated: true) }
|
|
}
|
|
}
|
|
|
|
private func requestExit(_ exit: @escaping () -> Void) {
|
|
guard presentedViewController == nil else { return }
|
|
guard viewModel.isSubmitting || isStartingSubmission || isPicking else { exit(); return }
|
|
let alert = UIAlertController(title: "停止处理并返回?", message: "未完成的上传将停止。如果正在保存成片,返回素材库刷新可核对实际结果。", preferredStyle: .alert)
|
|
alert.addAction(UIAlertAction(title: "继续处理", style: .cancel))
|
|
alert.addAction(UIAlertAction(title: "停止并返回", style: .destructive) { [weak self] _ in
|
|
guard let self else { return }
|
|
self.operationTask?.cancel()
|
|
self.viewModel.invalidate()
|
|
exit()
|
|
})
|
|
present(alert, animated: true)
|
|
}
|
|
|
|
private static func text(_ value: String?, fallback: String) -> String { DroneDockHomeMetric.usableText(value) ?? fallback }
|
|
private static func flightTitle(_ value: Int?) -> String {
|
|
switch value { case 10: "待飞行"; case 20: "执行中"; case 30: "飞行成功"; case 40: "飞行失败"; case 50: "已取消"; case 60: "待确认"; default: "状态待确认" }
|
|
}
|
|
}
|
|
|
|
extension DroneDockDeliveryViewController: UICollectionViewDelegate {
|
|
/// 仅显式选择的点位与任务用于上传;切换任务不自动提交文件。
|
|
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
|
guard !locked, let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
|
switch item {
|
|
case .point(let id): viewModel.selectSpot(id: id)
|
|
case .task(let id): viewModel.selectTask(id: id)
|
|
default: return
|
|
}
|
|
discardUnusedVideos()
|
|
pickerError = nil
|
|
applySnapshot(animated: true)
|
|
}
|
|
}
|
|
|
|
extension DroneDockDeliveryViewController: PHPickerViewControllerDelegate {
|
|
/// 相册取消不改变已选视频;选择结果复制完成后才交给上传状态。
|
|
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
|
|
picker.dismiss(animated: true)
|
|
guard let result = results.first else { return }
|
|
loadPickedVideo { try await DroneDockDeliveryVideoLoader.load(provider: result.itemProvider) }
|
|
}
|
|
}
|
|
|
|
extension DroneDockDeliveryViewController: UIDocumentPickerDelegate {
|
|
/// 文件选择器只接受一段视频,复制到本页临时目录后读取。
|
|
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
|
|
guard let url = urls.first else { return }
|
|
loadPickedVideo { try await DroneDockDeliveryVideoLoader.load(documentURL: url) }
|
|
}
|
|
}
|
|
|
|
/// 订单、任务与错误提示共用的自适应卡片。
|
|
@MainActor
|
|
private final class DroneDockDeliveryTextCell: UICollectionViewCell {
|
|
private let titleLabel = DroneDockStyle.label(size: 15, weight: .semibold)
|
|
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
|
private let actionButton = UIButton(type: .system)
|
|
private var action: (() -> Void)?
|
|
|
|
override init(frame: CGRect) {
|
|
super.init(frame: frame)
|
|
DroneDockDeliveryDesign.card(to: contentView, cornerRadius: 16)
|
|
titleLabel.numberOfLines = 0
|
|
detailLabel.numberOfLines = 0
|
|
let stack = UIStackView(arrangedSubviews: [titleLabel, detailLabel, actionButton])
|
|
stack.axis = .vertical; stack.spacing = 8; stack.alignment = .leading
|
|
contentView.addSubview(stack)
|
|
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(14) }
|
|
titleLabel.snp.makeConstraints { $0.width.equalTo(stack) }
|
|
detailLabel.snp.makeConstraints { $0.width.equalTo(stack) }
|
|
actionButton.addTarget(self, action: #selector(tapped), for: .touchUpInside)
|
|
}
|
|
|
|
@available(*, unavailable)
|
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
|
|
/// 重配内容时同步清除旧操作与选中状态。
|
|
func apply(title: String, body: String?, id: String, selected: Bool = false, selectable: Bool = false,
|
|
button: String? = nil, actionID: String? = nil, action: (() -> Void)? = nil) {
|
|
titleLabel.text = (selectable ? (selected ? "● " : "○ ") : "") + title
|
|
detailLabel.text = body
|
|
detailLabel.isHidden = body == nil
|
|
actionButton.setTitle(button, for: .normal)
|
|
actionButton.isHidden = button == nil
|
|
actionButton.accessibilityIdentifier = actionID
|
|
self.action = action
|
|
contentView.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor
|
|
contentView.layer.borderWidth = selected ? 1 : 0
|
|
accessibilityIdentifier = id
|
|
accessibilityTraits = selected ? [.button, .selected] : selectable ? .button : []
|
|
}
|
|
@objc private func tapped() { action?() }
|
|
}
|