feat(drone-dock): 搭建素材库预览选择与下载演示
This commit is contained in:
@@ -6,7 +6,7 @@ import UIKit
|
||||
enum DroneDockPreview {
|
||||
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview"]
|
||||
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview", "--dock-ui-materials-preview"]
|
||||
guard arguments.contains(where: { entryFlags.contains($0) }) else { return nil }
|
||||
let store = DroneDockDemoStore()
|
||||
if let argument = arguments.first(where: { $0.hasPrefix("--dock-ui-scenario=") }),
|
||||
@@ -48,6 +48,17 @@ enum DroneDockPreview {
|
||||
}
|
||||
navigation.setViewControllers(controllers, animated: false)
|
||||
}
|
||||
if arguments.contains("--dock-ui-materials-preview"), let order = store.orders.first(where: { $0.successfulShootingCount > 0 }) {
|
||||
let pointArgument = arguments.first { $0.hasPrefix("--dock-materials-point=") }
|
||||
let pointID = pointArgument.map { String($0.dropFirst("--dock-materials-point=".count)) }
|
||||
let materialsViewModel = DroneMaterialsViewModel(store: store, orderID: order.id, pointID: pointID)
|
||||
let scenarioArgument = arguments.first { $0.hasPrefix("--dock-materials-scenario=") }
|
||||
let scenario = scenarioArgument.flatMap { DroneMaterialsScenario(rawValue: String($0.dropFirst("--dock-materials-scenario=".count))) } ?? .mixed
|
||||
materialsViewModel.applyScenario(scenario)
|
||||
let materials = DroneMaterialsViewController(viewModel: materialsViewModel)
|
||||
materials.delegate = workbench
|
||||
navigation.setViewControllers([workbench, materials], animated: false)
|
||||
}
|
||||
return navigation
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,7 +209,7 @@ final class DroneDockWorkbenchViewController: BaseViewController {
|
||||
navigationController?.pushViewController(controller, animated: true)
|
||||
}
|
||||
|
||||
/// 拍摄进入本地准备/原任务,其他下级业务暂保留入口提示。
|
||||
/// 拍摄和素材进入对应本地页面,成片交付暂保留入口提示。
|
||||
private enum OrderEntry { case shooting, materials, delivery }
|
||||
|
||||
private func showOrderEntry(id: String, action: OrderEntry) {
|
||||
@@ -225,8 +225,8 @@ final class DroneDockWorkbenchViewController: BaseViewController {
|
||||
openShootingOrder(id: order.id, from: presenter ?? self)
|
||||
return
|
||||
case .materials:
|
||||
title = "查看素材"
|
||||
detail = order.materialState.title
|
||||
openMaterials(orderID: order.id, from: presenter ?? self)
|
||||
return
|
||||
case .delivery:
|
||||
title = "交付成片"
|
||||
detail = "\(order.deliveredVideoCount) 个已交付视频"
|
||||
@@ -258,6 +258,15 @@ final class DroneDockWorkbenchViewController: BaseViewController {
|
||||
presenter.navigationController?.pushViewController(controller, animated: true)
|
||||
}
|
||||
|
||||
private func openMaterials(orderID: String, pointID: String? = nil, from presenter: UIViewController) {
|
||||
guard viewModel.store.shootingOrder(id: orderID) != nil else { return }
|
||||
let controller = DroneMaterialsViewController(
|
||||
viewModel: DroneMaterialsViewModel(store: viewModel.store, orderID: orderID, pointID: pointID)
|
||||
)
|
||||
controller.delegate = self
|
||||
presenter.navigationController?.pushViewController(controller, animated: true)
|
||||
}
|
||||
|
||||
@objc private func receiptTapped() {
|
||||
showAlert(title: "收款码", message: "套餐收款页面将在后续搭建,当前不会创建订单或发起收款。")
|
||||
}
|
||||
@@ -312,7 +321,21 @@ extension DroneDockWorkbenchViewController: DroneShootingTaskViewControllerDeleg
|
||||
|
||||
func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestMaterialsFor order: DroneShootingOrder) {
|
||||
guard let order = viewModel.store.shootingOrder(id: order.id) else { return }
|
||||
showPreviewEntry(order: order, action: .materials, presenter: controller)
|
||||
let pointID = viewModel.store.shootingSession(orderID: order.id)?.point.id
|
||||
openMaterials(orderID: order.id, pointID: pointID, from: controller)
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockWorkbenchViewController: DroneMaterialsViewControllerDelegate {
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestPreview material: DroneMaterial) {
|
||||
guard material.canPreview else { return }
|
||||
let preview = DroneMaterialPreviewViewController(items: controller.viewModel.previewMaterials, initialMaterialID: material.id)
|
||||
controller.present(preview, animated: true)
|
||||
}
|
||||
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord) {
|
||||
guard let order = viewModel.store.shootingOrder(id: controller.viewModel.orderID) else { return }
|
||||
showPreviewEntry(order: order, action: .delivery, presenter: controller)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 素材库的订单摘要,保留拍摄履约与素材处理相互独立的表达。
|
||||
@MainActor
|
||||
final class DroneMaterialOrderCell: UICollectionViewCell {
|
||||
private let customerLabel = DroneDockStyle.label(size: 18, weight: .semibold)
|
||||
private let statusLabel = DroneDockStatusLabel()
|
||||
private let numberLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let countLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
let titleRow = UIStackView(arrangedSubviews: [customerLabel, statusLabel, UIView()])
|
||||
titleRow.axis = .horizontal
|
||||
titleRow.alignment = .center
|
||||
titleRow.spacing = 9
|
||||
let stack = UIStackView(arrangedSubviews: [titleRow, numberLabel, countLabel])
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 9
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.top.equalToSuperview().offset(16)
|
||||
make.bottom.equalToSuperview().inset(18)
|
||||
}
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 显示本次入口订单的脱敏信息与拍摄次数。
|
||||
func apply(order: DroneShootingOrder?) {
|
||||
guard let order else {
|
||||
customerLabel.text = "订单信息暂不可用"
|
||||
statusLabel.isHidden = true
|
||||
numberLabel.text = "请返回订单列表重新进入"
|
||||
countLabel.text = nil
|
||||
accessibilityLabel = "订单信息暂不可用,请返回订单列表重新进入"
|
||||
return
|
||||
}
|
||||
customerLabel.text = order.customerName
|
||||
statusLabel.isHidden = false
|
||||
statusLabel.apply(title: order.fulfillmentState.title, tone: order.fulfillmentState.tone)
|
||||
numberLabel.text = order.orderNumber
|
||||
countLabel.text = "含\(order.totalShootingCount)次拍摄 · 已拍摄\(order.successfulShootingCount)次 · 剩余\(order.remainingShootingCount)次"
|
||||
accessibilityLabel = [order.customerName, order.fulfillmentState.title, order.orderNumber, countLabel.text].compactMap { $0 }.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
/// 可横向浏览的点位筛选标签,下载期间保留现有筛选并禁用交互。
|
||||
@MainActor
|
||||
final class DroneMaterialFilterCell: UICollectionViewCell {
|
||||
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
contentView.layer.cornerRadius = 7
|
||||
contentView.layer.cornerCurve = .continuous
|
||||
contentView.layer.borderWidth = 1
|
||||
titleLabel.textAlignment = .center
|
||||
contentView.addSubview(titleLabel)
|
||||
titleLabel.snp.makeConstraints { make in make.edges.equalToSuperview().inset(5) }
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 映射筛选名称、选中态与交互许可。
|
||||
func apply(title: String, id: String?, selected: Bool, locked: Bool) {
|
||||
titleLabel.text = title
|
||||
titleLabel.textColor = selected ? DroneDockStyle.primary : UIColor(hex: 0x677183)
|
||||
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.09) : .white
|
||||
contentView.layer.borderColor = (selected ? UIColor.clear : DroneDockStyle.border).cgColor
|
||||
contentView.alpha = locked ? 0.5 : 1
|
||||
accessibilityIdentifier = "drone.materials.filter.\(id ?? "all")"
|
||||
accessibilityLabel = title
|
||||
var traits: UIAccessibilityTraits = .button
|
||||
if selected { traits.insert(.selected) }
|
||||
if locked { traits.insert(.notEnabled) }
|
||||
accessibilityTraits = traits
|
||||
}
|
||||
}
|
||||
|
||||
/// 点位限定入口的只读提示,不将当前任务点位伪装成可切换筛选。
|
||||
@MainActor
|
||||
final class DroneMaterialPointContextCell: UICollectionViewCell {
|
||||
private let icon = UIImageView(image: UIImage(systemName: "mappin.circle.fill"))
|
||||
private let titleLabel = DroneDockStyle.label(size: 14, weight: .semibold)
|
||||
private let detailLabel = DroneDockStyle.label("仅显示当前打卡点素材", size: 11, color: DroneDockStyle.secondary)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
icon.tintColor = DroneDockStyle.primary
|
||||
[icon, titleLabel, detailLabel].forEach(contentView.addSubview)
|
||||
icon.snp.makeConstraints { make in make.leading.centerY.equalToSuperview(); make.size.equalTo(16) }
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.leading.equalTo(icon.snp.trailing).offset(6)
|
||||
make.centerY.equalToSuperview()
|
||||
make.trailing.lessThanOrEqualTo(detailLabel.snp.leading).offset(-8)
|
||||
}
|
||||
detailLabel.snp.makeConstraints { make in make.trailing.centerY.equalToSuperview() }
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 展示限定点位的名称。
|
||||
func apply(title: String) {
|
||||
titleLabel.text = title
|
||||
accessibilityLabel = "\(title),仅显示当前打卡点素材"
|
||||
}
|
||||
}
|
||||
|
||||
/// 素材分组上方的数量与全选控制,数量由当前可见记录提供。
|
||||
@MainActor
|
||||
final class DroneMaterialSelectionCell: UICollectionViewCell {
|
||||
/// 点击后由控制器调用 ViewModel 的全选操作。
|
||||
var onSelectAllTap: (() -> Void)?
|
||||
private let countLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let selectAllButton = UIButton(type: .system)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
selectAllButton.titleLabel?.font = .systemFont(ofSize: 12)
|
||||
selectAllButton.tintColor = DroneDockStyle.primary
|
||||
selectAllButton.accessibilityIdentifier = "drone.materials.selectAll"
|
||||
selectAllButton.addTarget(self, action: #selector(selectAllTapped), for: .touchUpInside)
|
||||
let divider = UIView()
|
||||
divider.backgroundColor = DroneDockStyle.border
|
||||
[countLabel, selectAllButton, divider].forEach(contentView.addSubview)
|
||||
countLabel.snp.makeConstraints { make in make.leading.centerY.equalToSuperview().offset(-2) }
|
||||
selectAllButton.snp.makeConstraints { make in
|
||||
make.trailing.equalToSuperview()
|
||||
make.centerY.equalTo(countLabel)
|
||||
make.leading.greaterThanOrEqualTo(countLabel.snp.trailing).offset(8)
|
||||
make.height.equalTo(44)
|
||||
}
|
||||
divider.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 全选只面向当前可下载项,上传中与失败素材不会计入。
|
||||
func apply(recordCount: Int, allSelected: Bool, enabled: Bool) {
|
||||
countLabel.text = "\(recordCount)次拍摄 · 最新在前"
|
||||
var config = UIButton.Configuration.plain()
|
||||
config.title = "全选可下载"
|
||||
config.image = UIImage(systemName: allSelected ? "checkmark.circle.fill" : "circle")
|
||||
config.imagePadding = 6
|
||||
config.contentInsets = .zero
|
||||
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 15)
|
||||
selectAllButton.configuration = config
|
||||
selectAllButton.isEnabled = enabled
|
||||
selectAllButton.accessibilityLabel = "全选可下载"
|
||||
selectAllButton.accessibilityTraits = allSelected ? [.button, .selected] : .button
|
||||
}
|
||||
|
||||
@objc private func selectAllTapped() { onSelectAllTap?() }
|
||||
}
|
||||
|
||||
/// 每条拍摄记录的点位、航线、时间与独立的交付入口。
|
||||
@MainActor
|
||||
final class DroneMaterialRecordHeaderView: UICollectionReusableView {
|
||||
/// 交付入口目前只向上层请求展示占位说明。
|
||||
var onDeliveryTap: (() -> Void)?
|
||||
private let titleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
|
||||
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let deliveryButton = UIButton(type: .system)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
deliveryButton.titleLabel?.font = .systemFont(ofSize: 12)
|
||||
var config = UIButton.Configuration.plain()
|
||||
config.title = "交付成片"
|
||||
config.image = UIImage(systemName: "play.rectangle")
|
||||
config.imagePadding = 5
|
||||
config.contentInsets = .zero
|
||||
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13)
|
||||
deliveryButton.configuration = config
|
||||
deliveryButton.tintColor = DroneDockStyle.primary
|
||||
deliveryButton.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside)
|
||||
[titleLabel, detailLabel, deliveryButton].forEach(addSubview)
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.leading.equalToSuperview()
|
||||
make.top.equalToSuperview().offset(20)
|
||||
make.trailing.lessThanOrEqualTo(deliveryButton.snp.leading).offset(-12)
|
||||
}
|
||||
deliveryButton.snp.makeConstraints { make in
|
||||
make.trailing.equalToSuperview()
|
||||
make.centerY.equalTo(titleLabel)
|
||||
make.height.equalTo(40)
|
||||
}
|
||||
detailLabel.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.top.equalTo(titleLabel.snp.bottom).offset(9)
|
||||
make.bottom.lessThanOrEqualToSuperview().inset(10)
|
||||
}
|
||||
titleLabel.accessibilityTraits = .header
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 使用完整拍摄记录身份绑定交付入口,避免仅按同名点位匹配。
|
||||
func apply(record: DroneMaterialRecord) {
|
||||
titleLabel.text = record.pointName
|
||||
detailLabel.text = record.summary
|
||||
deliveryButton.accessibilityLabel = "\(record.pointName)交付成片,记录\(record.sequenceNumber)"
|
||||
deliveryButton.accessibilityIdentifier = "drone.materials.delivery.\(record.id)"
|
||||
}
|
||||
|
||||
@objc private func deliveryTapped() { onDeliveryTap?() }
|
||||
}
|
||||
|
||||
/// 两列素材网格单元;缩略图预览与右上角多选按钮互不替代。
|
||||
@MainActor
|
||||
final class DroneMaterialCell: UICollectionViewCell {
|
||||
/// 点击就绪缩略图时请求预览。
|
||||
var onPreviewTap: (() -> Void)?
|
||||
/// 点击右上角选择控件时仅改变选择。
|
||||
var onSelectionTap: (() -> Void)?
|
||||
private let thumbnail = UIImageView()
|
||||
private let previewButton = UIButton(type: .custom)
|
||||
private let selectionButton = UIButton(type: .custom)
|
||||
private let placeholderIcon = UIImageView()
|
||||
private let videoBadge = UILabel()
|
||||
private let nameLabel = DroneDockStyle.label(size: 12, weight: .medium)
|
||||
private let statusLabel = DroneDockStyle.label(size: 11)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
thumbnail.contentMode = .scaleAspectFill
|
||||
thumbnail.clipsToBounds = true
|
||||
thumbnail.layer.cornerRadius = 6
|
||||
thumbnail.layer.cornerCurve = .continuous
|
||||
thumbnail.backgroundColor = UIColor(hex: 0xE9EDF5)
|
||||
thumbnail.layer.borderWidth = 2
|
||||
placeholderIcon.contentMode = .scaleAspectFit
|
||||
placeholderIcon.tintColor = UIColor(hex: 0x9CA6B6)
|
||||
videoBadge.font = .systemFont(ofSize: 10, weight: .medium)
|
||||
videoBadge.textColor = .white
|
||||
videoBadge.backgroundColor = UIColor.black.withAlphaComponent(0.48)
|
||||
videoBadge.layer.cornerRadius = 3
|
||||
videoBadge.clipsToBounds = true
|
||||
videoBadge.textAlignment = .center
|
||||
videoBadge.text = "视频"
|
||||
selectionButton.imageView?.contentMode = .scaleAspectFit
|
||||
selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
|
||||
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
|
||||
[thumbnail, placeholderIcon, previewButton, videoBadge, selectionButton, nameLabel, statusLabel].forEach(contentView.addSubview)
|
||||
thumbnail.snp.makeConstraints { make in
|
||||
make.leading.trailing.top.equalToSuperview()
|
||||
make.height.equalTo(thumbnail.snp.width).multipliedBy(0.57)
|
||||
}
|
||||
previewButton.snp.makeConstraints { make in make.edges.equalTo(thumbnail) }
|
||||
placeholderIcon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(29) }
|
||||
videoBadge.snp.makeConstraints { make in
|
||||
make.leading.equalTo(thumbnail).offset(6)
|
||||
make.bottom.equalTo(thumbnail).inset(6)
|
||||
make.width.equalTo(32)
|
||||
make.height.equalTo(18)
|
||||
}
|
||||
selectionButton.snp.makeConstraints { make in
|
||||
make.top.trailing.equalTo(thumbnail)
|
||||
make.size.equalTo(44)
|
||||
}
|
||||
nameLabel.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.top.equalTo(thumbnail.snp.bottom).offset(7)
|
||||
}
|
||||
statusLabel.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.top.equalTo(nameLabel.snp.bottom).offset(4)
|
||||
make.bottom.lessThanOrEqualToSuperview().inset(5)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 上传未就绪时显示占位且禁选,演示完成也不会标记为本机已保存。
|
||||
func apply(material: DroneMaterial, selected: Bool, selectionEnabled: Bool, completed: Bool) {
|
||||
nameLabel.text = material.title
|
||||
statusLabel.text = material.statusTitle
|
||||
statusLabel.textColor = DroneDockStyle.color(for: material.statusTone)
|
||||
thumbnail.image = material.canPreview ? UIImage(named: material.previewAssetName) : nil
|
||||
thumbnail.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor
|
||||
placeholderIcon.isHidden = material.canPreview
|
||||
placeholderIcon.image = UIImage(systemName: material.uploadState == .failed ? "exclamationmark.icloud" : "play.fill")
|
||||
videoBadge.isHidden = material.kind != .video || !material.canPreview
|
||||
previewButton.isEnabled = material.canPreview
|
||||
previewButton.accessibilityIdentifier = "drone.materials.preview.\(material.id)"
|
||||
previewButton.accessibilityLabel = "预览\(material.title)"
|
||||
selectionButton.isHidden = material.uploadState != .ready
|
||||
selectionButton.isEnabled = selectionEnabled && !completed
|
||||
selectionButton.accessibilityIdentifier = "drone.materials.select.\(material.id)"
|
||||
selectionButton.accessibilityLabel = completed ? "\(material.title),演示完成,未写入相册" : "选择\(material.title)"
|
||||
selectionButton.accessibilityTraits = selected || completed ? [.button, .selected] : .button
|
||||
let symbol = UIImage(systemName: selected || completed ? "checkmark.circle.fill" : "circle",
|
||||
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22, weight: .regular))
|
||||
let tint = completed ? DroneDockStyle.success : selected ? DroneDockStyle.primary : UIColor.white
|
||||
selectionButton.setImage(symbol?.withTintColor(tint, renderingMode: .alwaysOriginal), for: .normal)
|
||||
selectionButton.setImage(symbol?.withTintColor(tint.withAlphaComponent(0.6), renderingMode: .alwaysOriginal), for: .disabled)
|
||||
selectionButton.imageView?.layer.shadowColor = UIColor.black.cgColor
|
||||
selectionButton.imageView?.layer.shadowOpacity = 0.22
|
||||
selectionButton.imageView?.layer.shadowRadius = 2
|
||||
selectionButton.imageView?.layer.shadowOffset = .zero
|
||||
}
|
||||
|
||||
@objc private func previewTapped() { onPreviewTap?() }
|
||||
@objc private func selectionTapped() { onSelectionTap?() }
|
||||
}
|
||||
|
||||
/// 分组之间轻量的分隔线。
|
||||
@MainActor
|
||||
final class DroneMaterialSeparatorView: UICollectionReusableView {
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
let line = UIView()
|
||||
line.backgroundColor = DroneDockStyle.border
|
||||
addSubview(line)
|
||||
line.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
}
|
||||
|
||||
/// 列表加载、为空与失败时的就地说明,保留顶部订单与刷新入口。
|
||||
@MainActor
|
||||
final class DroneMaterialMessageCell: UICollectionViewCell {
|
||||
private let icon = UIImageView()
|
||||
private let titleLabel = DroneDockStyle.label(size: 16, weight: .medium)
|
||||
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
icon.tintColor = DroneDockStyle.secondary
|
||||
icon.contentMode = .scaleAspectFit
|
||||
titleLabel.textAlignment = .center
|
||||
detailLabel.textAlignment = .center
|
||||
detailLabel.numberOfLines = 0
|
||||
let stack = UIStackView(arrangedSubviews: [icon, titleLabel, detailLabel])
|
||||
stack.axis = .vertical
|
||||
stack.alignment = .center
|
||||
stack.spacing = 13
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { make in make.centerY.equalToSuperview().offset(-12); make.leading.trailing.equalToSuperview().inset(12) }
|
||||
icon.snp.makeConstraints { make in make.size.equalTo(38) }
|
||||
isAccessibilityElement = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 通过明确文案区分上传等待、空记录与加载异常。
|
||||
func apply(title: String, detail: String, symbol: String) {
|
||||
titleLabel.text = title
|
||||
detailLabel.text = detail
|
||||
icon.image = UIImage(systemName: symbol)
|
||||
accessibilityLabel = "\(title),\(detail)"
|
||||
}
|
||||
}
|
||||
|
||||
/// 固定底栏以同一组件呈现选择、批次进度、暂停与演示结果。
|
||||
@MainActor
|
||||
final class DroneMaterialsFooterView: UIView {
|
||||
/// 执行当前状态对应的主要操作。
|
||||
var onPrimaryTap: (() -> Void)?
|
||||
/// 返回选择状态或请求预留的交付入口。
|
||||
var onSecondaryTap: (() -> Void)?
|
||||
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
|
||||
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let progressView = UIProgressView(progressViewStyle: .default)
|
||||
private let primaryButton = UIButton(type: .system)
|
||||
private let secondaryButton = UIButton(type: .system)
|
||||
private let stack = UIStackView()
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
backgroundColor = .white
|
||||
let divider = UIView()
|
||||
divider.backgroundColor = DroneDockStyle.border
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 10
|
||||
titleLabel.numberOfLines = 2
|
||||
detailLabel.numberOfLines = 2
|
||||
progressView.progressTintColor = DroneDockStyle.primary
|
||||
progressView.trackTintColor = UIColor(hex: 0xE8EDF7)
|
||||
progressView.accessibilityLabel = "本次演示下载完成项数"
|
||||
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
|
||||
primaryButton.layer.cornerRadius = 7
|
||||
primaryButton.layer.cornerCurve = .continuous
|
||||
primaryButton.tintColor = .white
|
||||
primaryButton.setTitleColor(.white, for: .normal)
|
||||
primaryButton.setTitleColor(UIColor.white.withAlphaComponent(0.85), for: .disabled)
|
||||
secondaryButton.titleLabel?.font = .systemFont(ofSize: 12)
|
||||
secondaryButton.tintColor = DroneDockStyle.secondary
|
||||
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
|
||||
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
|
||||
[titleLabel, progressView, detailLabel, primaryButton, secondaryButton].forEach(stack.addArrangedSubview)
|
||||
addSubview(divider)
|
||||
addSubview(stack)
|
||||
divider.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
|
||||
stack.snp.makeConstraints { make in
|
||||
make.top.equalToSuperview().offset(12)
|
||||
make.leading.trailing.equalToSuperview().inset(16)
|
||||
make.bottom.equalTo(safeAreaLayoutGuide).inset(10)
|
||||
}
|
||||
primaryButton.snp.makeConstraints { make in make.height.equalTo(44) }
|
||||
secondaryButton.snp.makeConstraints { make in make.height.equalTo(24) }
|
||||
progressView.snp.makeConstraints { make in make.height.equalTo(3) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 只接受显示值,按钮语义和下载状态由控制器及 ViewModel 决定。
|
||||
func apply(title: String, detail: String, primaryTitle: String, primarySymbol: String,
|
||||
enabled: Bool, identifier: String, progress: Double?, secondaryTitle: String? = nil,
|
||||
tone: DroneDockStatusTone = .gray) {
|
||||
titleLabel.text = title
|
||||
titleLabel.textColor = tone == .gray ? DroneDockStyle.text : DroneDockStyle.color(for: tone)
|
||||
detailLabel.text = detail
|
||||
detailLabel.isHidden = detail.isEmpty
|
||||
progressView.isHidden = progress == nil
|
||||
progressView.setProgress(Float(progress ?? 0), animated: true)
|
||||
var config = UIButton.Configuration.plain()
|
||||
config.title = primaryTitle
|
||||
config.image = UIImage(systemName: primarySymbol)
|
||||
config.imagePadding = 7
|
||||
config.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)
|
||||
config.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 16)
|
||||
primaryButton.configuration = config
|
||||
primaryButton.isEnabled = enabled
|
||||
primaryButton.backgroundColor = enabled ? DroneDockStyle.primary : UIColor(hex: 0xCEDBFC)
|
||||
primaryButton.accessibilityIdentifier = identifier
|
||||
secondaryButton.setTitle(secondaryTitle, for: .normal)
|
||||
secondaryButton.isHidden = secondaryTitle == nil
|
||||
secondaryButton.accessibilityIdentifier = "drone.materials.continueSelecting"
|
||||
}
|
||||
|
||||
@objc private func primaryTapped() { onPrimaryTap?() }
|
||||
@objc private func secondaryTapped() { onSecondaryTap?() }
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
|
||||
/// 本地 UI 演示的下载回执驱动,不连接网络、不写文件或系统相册。
|
||||
@MainActor
|
||||
final class DroneMaterialDemoTransferDriver {
|
||||
private var task: Task<Void, Never>?
|
||||
private var runningBatchID: UUID?
|
||||
|
||||
/// 推进当前演示批次;相同批次不会重复启动,实际结果由 ViewModel 校验。
|
||||
func start(viewModel: DroneMaterialsViewModel, onTransferUpdate: @escaping () -> Void) {
|
||||
guard let batch = viewModel.batch, !batch.isPaused else { return }
|
||||
guard runningBatchID != batch.id || task == nil else { return }
|
||||
stop()
|
||||
let batchID = batch.id
|
||||
runningBatchID = batchID
|
||||
task = Task { @MainActor [weak self, weak viewModel] in
|
||||
guard let self, let viewModel else { return }
|
||||
defer {
|
||||
if self.runningBatchID == batchID {
|
||||
self.task = nil
|
||||
self.runningBatchID = nil
|
||||
}
|
||||
}
|
||||
for materialID in batch.itemIDs {
|
||||
guard self.isCurrent(viewModel, batchID: batchID),
|
||||
let material = viewModel.material(id: materialID) else { return }
|
||||
switch material.downloadState {
|
||||
case .downloading, .paused, .available:
|
||||
for progress in [0.2, 0.45, 0.7, 1.0] {
|
||||
guard await self.wait(viewModel, batchID: batchID) else { return }
|
||||
viewModel.receive(.progress(progress), materialID: materialID, batchID: batchID)
|
||||
onTransferUpdate()
|
||||
}
|
||||
viewModel.receive(.downloadCompleted, materialID: materialID, batchID: batchID)
|
||||
onTransferUpdate()
|
||||
case .awaitingSave: break
|
||||
default: continue
|
||||
}
|
||||
guard self.isCurrent(viewModel, batchID: batchID) else { return }
|
||||
viewModel.receive(.saveStarted, materialID: materialID, batchID: batchID)
|
||||
onTransferUpdate()
|
||||
guard await self.wait(viewModel, batchID: batchID) else { return }
|
||||
viewModel.receive(.saveSucceeded, materialID: materialID, batchID: batchID)
|
||||
onTransferUpdate()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 取消演示回执;调用方再通知 ViewModel 暂停,返回前台不会自动启动。
|
||||
func stop() {
|
||||
task?.cancel()
|
||||
task = nil
|
||||
runningBatchID = nil
|
||||
}
|
||||
|
||||
private func isCurrent(_ viewModel: DroneMaterialsViewModel, batchID: UUID) -> Bool {
|
||||
!Task.isCancelled && runningBatchID == batchID
|
||||
&& viewModel.batch?.id == batchID && viewModel.batch?.isPaused == false
|
||||
}
|
||||
|
||||
private func wait(_ viewModel: DroneMaterialsViewModel, batchID: UUID) async -> Bool {
|
||||
do { try await Task.sleep(nanoseconds: 180_000_000) } catch { return false }
|
||||
return isCurrent(viewModel, batchID: batchID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
import AVFoundation
|
||||
import AVKit
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 订单素材的本地只读预览页;分页与缩放不会改变素材选择、下载或拍摄任务。
|
||||
@MainActor
|
||||
final class DroneMaterialPreviewViewController: UIViewController {
|
||||
/// 本地预览列表只有一个媒体分区。
|
||||
private enum Section {
|
||||
case materials
|
||||
}
|
||||
|
||||
private let items: [DroneMaterial]
|
||||
private var currentIndex: Int
|
||||
private var lastCollectionSize = CGSize.zero
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, String>!
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeCollectionLayout())
|
||||
private let closeButton = UIButton(type: .system)
|
||||
private let counterLabel = UILabel()
|
||||
private let emptyLabel = UILabel()
|
||||
private let instructionLabel = UILabel()
|
||||
private weak var videoController: AVPlayerViewController?
|
||||
private var playbackTask: Task<Void, Never>?
|
||||
|
||||
/// 以当前素材为起点预览已就绪素材;未就绪项不会被带入预览列表。
|
||||
init(items: [DroneMaterial], initialMaterialID: String) {
|
||||
var identifiers = Set<String>()
|
||||
self.items = items.filter { $0.canPreview && identifiers.insert($0.id).inserted }
|
||||
currentIndex = self.items.firstIndex { $0.id == initialMaterialID } ?? 0
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .fullScreen
|
||||
modalTransitionStyle = .crossDissolve
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
setupUI()
|
||||
setupConstraints()
|
||||
setupDataSource()
|
||||
applySnapshot()
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
guard collectionView.bounds.width > 0, collectionView.bounds.size != lastCollectionSize else { return }
|
||||
lastCollectionSize = collectionView.bounds.size
|
||||
collectionView.collectionViewLayout.invalidateLayout()
|
||||
collectionView.setContentOffset(CGPoint(x: CGFloat(currentIndex) * collectionView.bounds.width, y: 0), animated: false)
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
if isBeingDismissed || navigationController?.isBeingDismissed == true {
|
||||
playbackTask?.cancel()
|
||||
videoController?.player?.pause()
|
||||
}
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
view.backgroundColor = UIColor(hex: 0x141820)
|
||||
view.accessibilityIdentifier = "drone.material.preview"
|
||||
collectionView.backgroundColor = .clear
|
||||
collectionView.isPagingEnabled = true
|
||||
collectionView.showsHorizontalScrollIndicator = false
|
||||
collectionView.alwaysBounceHorizontal = items.count > 1
|
||||
collectionView.contentInsetAdjustmentBehavior = .never
|
||||
collectionView.accessibilityIdentifier = "drone.material.preview.pages"
|
||||
collectionView.delegate = self
|
||||
collectionView.register(DroneMaterialPreviewCell.self, forCellWithReuseIdentifier: DroneMaterialPreviewCell.reuseIdentifier)
|
||||
|
||||
closeButton.setImage(UIImage(systemName: "xmark", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular)), for: .normal)
|
||||
closeButton.tintColor = .white
|
||||
closeButton.accessibilityLabel = "关闭素材预览"
|
||||
closeButton.accessibilityIdentifier = "drone.material.preview.close"
|
||||
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
|
||||
|
||||
counterLabel.textColor = UIColor.white.withAlphaComponent(0.75)
|
||||
counterLabel.font = .monospacedDigitSystemFont(ofSize: 13, weight: .medium)
|
||||
counterLabel.textAlignment = .center
|
||||
counterLabel.accessibilityIdentifier = "drone.material.preview.counter"
|
||||
updateCounter()
|
||||
|
||||
emptyLabel.text = "暂无可预览的就绪素材"
|
||||
emptyLabel.textColor = UIColor.white.withAlphaComponent(0.7)
|
||||
emptyLabel.font = .systemFont(ofSize: 15)
|
||||
emptyLabel.textAlignment = .center
|
||||
emptyLabel.numberOfLines = 0
|
||||
emptyLabel.isHidden = !items.isEmpty
|
||||
|
||||
instructionLabel.text = items.count > 1 ? "双指或双击缩放 · 左右滑动切换" : "双指或双击缩放"
|
||||
instructionLabel.textColor = UIColor.white.withAlphaComponent(0.4)
|
||||
instructionLabel.font = .systemFont(ofSize: 11)
|
||||
instructionLabel.textAlignment = .center
|
||||
instructionLabel.isHidden = items.isEmpty
|
||||
|
||||
view.addSubview(collectionView)
|
||||
view.addSubview(emptyLabel)
|
||||
view.addSubview(closeButton)
|
||||
view.addSubview(counterLabel)
|
||||
view.addSubview(instructionLabel)
|
||||
}
|
||||
|
||||
private func setupConstraints() {
|
||||
collectionView.snp.makeConstraints { make in
|
||||
make.edges.equalToSuperview()
|
||||
}
|
||||
closeButton.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide).offset(4)
|
||||
make.trailing.equalToSuperview().inset(10)
|
||||
make.size.equalTo(44)
|
||||
}
|
||||
counterLabel.snp.makeConstraints { make in
|
||||
make.centerY.equalTo(closeButton)
|
||||
make.centerX.equalToSuperview()
|
||||
make.leading.greaterThanOrEqualToSuperview().offset(64)
|
||||
make.trailing.lessThanOrEqualTo(closeButton.snp.leading).offset(-8)
|
||||
}
|
||||
emptyLabel.snp.makeConstraints { make in
|
||||
make.center.equalToSuperview()
|
||||
make.leading.trailing.equalToSuperview().inset(32)
|
||||
}
|
||||
instructionLabel.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview().inset(24)
|
||||
make.bottom.equalTo(view.safeAreaLayoutGuide).inset(16)
|
||||
}
|
||||
}
|
||||
|
||||
private func setupDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Section, String>(collectionView: collectionView) { [weak self] collectionView, indexPath, identifier in
|
||||
guard let self, let material = self.items.first(where: { $0.id == identifier }),
|
||||
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DroneMaterialPreviewCell.reuseIdentifier, for: indexPath) as? DroneMaterialPreviewCell else {
|
||||
return UICollectionViewCell()
|
||||
}
|
||||
cell.configure(material: material)
|
||||
cell.onPlayLocalVideo = { [weak self, weak cell] in
|
||||
self?.playLocalVideo(material, sourceCell: cell)
|
||||
}
|
||||
return cell
|
||||
}
|
||||
}
|
||||
|
||||
private func applySnapshot() {
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
|
||||
snapshot.appendSections([.materials])
|
||||
snapshot.appendItems(items.map(\.id))
|
||||
dataSource.apply(snapshot, animatingDifferences: false) { [weak self] in
|
||||
guard let self, self.collectionView.bounds.width > 0 else { return }
|
||||
self.collectionView.layoutIfNeeded()
|
||||
self.collectionView.setContentOffset(CGPoint(x: CGFloat(self.currentIndex) * self.collectionView.bounds.width, y: 0), animated: false)
|
||||
}
|
||||
}
|
||||
|
||||
private func makeCollectionLayout() -> UICollectionViewLayout {
|
||||
let layout = UICollectionViewFlowLayout()
|
||||
layout.scrollDirection = .horizontal
|
||||
layout.minimumLineSpacing = 0
|
||||
layout.minimumInteritemSpacing = 0
|
||||
return layout
|
||||
}
|
||||
|
||||
private func updateCounter() {
|
||||
counterLabel.text = items.isEmpty ? "0 / 0" : "\(currentIndex + 1) / \(items.count)"
|
||||
counterLabel.accessibilityLabel = items.isEmpty ? "没有可预览素材" : "第 \(currentIndex + 1) 项,共 \(items.count) 项"
|
||||
}
|
||||
|
||||
private func updateCurrentIndex() {
|
||||
guard collectionView.bounds.width > 0, !items.isEmpty else { return }
|
||||
currentIndex = min(max(Int(round(collectionView.contentOffset.x / collectionView.bounds.width)), 0), items.count - 1)
|
||||
updateCounter()
|
||||
}
|
||||
|
||||
private func playLocalVideo(_ material: DroneMaterial, sourceCell: DroneMaterialPreviewCell?) {
|
||||
guard playbackTask == nil, let url = DroneMaterialPreviewCell.localVideoURL(for: material) else { return }
|
||||
sourceCell?.setVideoValidationInProgress(true)
|
||||
playbackTask = Task { @MainActor [weak self, weak sourceCell] in
|
||||
let playable = (try? await AVURLAsset(url: url).load(.isPlayable)) == true
|
||||
guard let self else { return }
|
||||
self.playbackTask = nil
|
||||
sourceCell?.setVideoValidationInProgress(false)
|
||||
guard !Task.isCancelled, self.view.window != nil, self.presentedViewController == nil,
|
||||
self.items.indices.contains(self.currentIndex), self.items[self.currentIndex].id == material.id else { return }
|
||||
guard playable else {
|
||||
sourceCell?.showUnavailableVideo()
|
||||
return
|
||||
}
|
||||
let controller = AVPlayerViewController()
|
||||
let player = AVPlayer(url: url)
|
||||
controller.player = player
|
||||
self.videoController = controller
|
||||
self.present(controller, animated: true) { player.play() }
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func closeTapped() {
|
||||
playbackTask?.cancel()
|
||||
playbackTask = nil
|
||||
videoController?.player?.pause()
|
||||
dismiss(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneMaterialPreviewViewController: UICollectionViewDelegateFlowLayout {
|
||||
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
|
||||
collectionView.bounds.size
|
||||
}
|
||||
|
||||
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { updateCurrentIndex() }
|
||||
|
||||
func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { updateCurrentIndex() }
|
||||
}
|
||||
|
||||
/// 单项本地素材预览,完整呈现图片并提供独立缩放,不触发远程请求。
|
||||
@MainActor
|
||||
private final class DroneMaterialPreviewCell: UICollectionViewCell, UIScrollViewDelegate {
|
||||
static let reuseIdentifier = "DroneMaterialPreviewCell"
|
||||
|
||||
/// 用户明确点击本地可播放视频后通知预览页。
|
||||
var onPlayLocalVideo: (() -> Void)?
|
||||
|
||||
private let scrollView = DroneMaterialPreviewZoomView()
|
||||
private var imageView: UIImageView { scrollView.imageView }
|
||||
private let titleLabel = UILabel()
|
||||
private let typeLabel = UILabel()
|
||||
private let zoomLabel = UILabel()
|
||||
private let unavailableImageLabel = UILabel()
|
||||
private let playButton = UIButton(type: .system)
|
||||
private var imageAspectRatio: CGFloat = 9 / 16
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
setupUI()
|
||||
setupConstraints()
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() {
|
||||
super.prepareForReuse()
|
||||
onPlayLocalVideo = nil
|
||||
scrollView.setZoomScale(1, animated: false)
|
||||
imageView.image = nil
|
||||
playButton.isEnabled = true
|
||||
}
|
||||
|
||||
/// 只读取本地图片资源;视频无本地片源时明确显示静帧说明。
|
||||
func configure(material: DroneMaterial) {
|
||||
scrollView.setZoomScale(1, animated: false)
|
||||
scrollView.setContentOffset(.zero, animated: false)
|
||||
let image: UIImage?
|
||||
if material.kind == .photo, let url = material.previewURL, url.isFileURL {
|
||||
image = UIImage(contentsOfFile: url.path) ?? UIImage(named: material.previewAssetName)
|
||||
} else {
|
||||
image = UIImage(named: material.previewAssetName)
|
||||
}
|
||||
imageView.image = image
|
||||
imageView.accessibilityLabel = material.title
|
||||
titleLabel.text = "\(material.title) · 演示素材"
|
||||
imageAspectRatio = image.map { $0.size.height / max($0.size.width, 1) } ?? 9 / 16
|
||||
unavailableImageLabel.isHidden = image != nil
|
||||
playButton.isHidden = Self.localVideoURL(for: material) == nil
|
||||
switch material.kind {
|
||||
case .photo:
|
||||
typeLabel.text = "照片 · 本地演示图片"
|
||||
case .video:
|
||||
typeLabel.text = playButton.isHidden ? "视频 · 本地演示静帧 · 暂无演示视频" : "视频 · 本地演示视频"
|
||||
}
|
||||
zoomLabel.text = "100%"
|
||||
updateMediaConstraints()
|
||||
setNeedsLayout()
|
||||
}
|
||||
|
||||
/// 只接受实际存在的本地文件,远程地址不会被交给播放器。
|
||||
static func localVideoURL(for material: DroneMaterial) -> URL? {
|
||||
guard material.kind == .video, let url = material.previewURL, url.isFileURL,
|
||||
FileManager.default.fileExists(atPath: url.path),
|
||||
["mp4", "mov", "m4v"].contains(url.pathExtension.lowercased()) else { return nil }
|
||||
return url
|
||||
}
|
||||
|
||||
/// 校验本地视频期间锁定播放按钮,避免重复创建播放器。
|
||||
func setVideoValidationInProgress(_ inProgress: Bool) {
|
||||
playButton.isEnabled = !inProgress
|
||||
playButton.accessibilityLabel = inProgress ? "正在检查本地视频" : "播放本地演示视频"
|
||||
}
|
||||
|
||||
/// 本地文件无法播放时保留真实静帧,不展示虚假的进度。
|
||||
func showUnavailableVideo() {
|
||||
playButton.isHidden = true
|
||||
typeLabel.text = "视频 · 本地演示静帧 · 暂无可播放演示视频"
|
||||
}
|
||||
|
||||
func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView }
|
||||
|
||||
func scrollViewDidZoom(_ scrollView: UIScrollView) {
|
||||
zoomLabel.text = "\(Int((scrollView.zoomScale * 100).rounded()))%"
|
||||
}
|
||||
|
||||
private func setupUI() {
|
||||
scrollView.minimumZoomScale = 1
|
||||
scrollView.maximumZoomScale = 3
|
||||
scrollView.delegate = self
|
||||
scrollView.showsHorizontalScrollIndicator = false
|
||||
scrollView.showsVerticalScrollIndicator = false
|
||||
scrollView.contentInsetAdjustmentBehavior = .never
|
||||
scrollView.bouncesZoom = true
|
||||
scrollView.accessibilityIdentifier = "drone.material.preview.zoomSurface"
|
||||
imageView.contentMode = .scaleAspectFit
|
||||
imageView.isAccessibilityElement = true
|
||||
imageView.accessibilityIdentifier = "drone.material.preview.image"
|
||||
|
||||
titleLabel.font = .systemFont(ofSize: 13, weight: .medium)
|
||||
titleLabel.textColor = UIColor.white.withAlphaComponent(0.75)
|
||||
titleLabel.textAlignment = .center
|
||||
titleLabel.numberOfLines = 2
|
||||
titleLabel.accessibilityIdentifier = "drone.material.preview.title"
|
||||
typeLabel.font = .systemFont(ofSize: 11)
|
||||
typeLabel.textColor = UIColor.white.withAlphaComponent(0.5)
|
||||
typeLabel.textAlignment = .center
|
||||
typeLabel.numberOfLines = 2
|
||||
typeLabel.accessibilityIdentifier = "drone.material.preview.type"
|
||||
zoomLabel.font = .monospacedDigitSystemFont(ofSize: 11, weight: .regular)
|
||||
zoomLabel.textColor = UIColor.white.withAlphaComponent(0.4)
|
||||
zoomLabel.textAlignment = .center
|
||||
zoomLabel.accessibilityIdentifier = "drone.material.preview.zoom"
|
||||
|
||||
unavailableImageLabel.text = "暂无本地演示图片"
|
||||
unavailableImageLabel.font = .systemFont(ofSize: 14)
|
||||
unavailableImageLabel.textColor = UIColor.white.withAlphaComponent(0.65)
|
||||
unavailableImageLabel.textAlignment = .center
|
||||
unavailableImageLabel.numberOfLines = 0
|
||||
playButton.setImage(UIImage(systemName: "play.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 58, weight: .regular)), for: .normal)
|
||||
playButton.tintColor = .white
|
||||
playButton.accessibilityLabel = "播放本地演示视频"
|
||||
playButton.accessibilityIdentifier = "drone.material.preview.play"
|
||||
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
|
||||
|
||||
contentView.addSubview(scrollView)
|
||||
contentView.addSubview(unavailableImageLabel)
|
||||
contentView.addSubview(titleLabel)
|
||||
contentView.addSubview(typeLabel)
|
||||
contentView.addSubview(zoomLabel)
|
||||
contentView.addSubview(playButton)
|
||||
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped(_:)))
|
||||
doubleTap.numberOfTapsRequired = 2
|
||||
scrollView.addGestureRecognizer(doubleTap)
|
||||
}
|
||||
|
||||
private func setupConstraints() {
|
||||
updateMediaConstraints()
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(scrollView.snp.bottom).offset(16)
|
||||
make.leading.trailing.equalToSuperview().inset(24)
|
||||
}
|
||||
typeLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(titleLabel.snp.bottom).offset(6)
|
||||
make.leading.trailing.equalTo(titleLabel)
|
||||
}
|
||||
zoomLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(typeLabel.snp.bottom).offset(6)
|
||||
make.leading.trailing.equalTo(titleLabel)
|
||||
}
|
||||
unavailableImageLabel.snp.makeConstraints { make in
|
||||
make.center.equalTo(scrollView)
|
||||
make.leading.trailing.equalToSuperview().inset(32)
|
||||
}
|
||||
playButton.snp.makeConstraints { make in
|
||||
make.center.equalTo(scrollView)
|
||||
make.size.equalTo(72)
|
||||
}
|
||||
}
|
||||
|
||||
private func updateMediaConstraints() {
|
||||
scrollView.snp.remakeConstraints { make in
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.centerY.equalToSuperview().offset(-28)
|
||||
make.height.equalTo(scrollView.snp.width).multipliedBy(imageAspectRatio).priority(999)
|
||||
make.height.lessThanOrEqualToSuperview().multipliedBy(0.6)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func playTapped() { onPlayLocalVideo?() }
|
||||
|
||||
@objc private func doubleTapped(_ gesture: UITapGestureRecognizer) {
|
||||
guard imageView.image != nil else { return }
|
||||
if scrollView.zoomScale > 1 {
|
||||
scrollView.setZoomScale(1, animated: true)
|
||||
return
|
||||
}
|
||||
let point = gesture.location(in: imageView)
|
||||
let targetScale: CGFloat = 3
|
||||
let size = CGSize(width: scrollView.bounds.width / targetScale, height: scrollView.bounds.height / targetScale)
|
||||
scrollView.zoom(to: CGRect(x: point.x - size.width / 2, y: point.y - size.height / 2, width: size.width, height: size.height), animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 在自身视口完成布局后设置图片尺寸,避免依赖集合单元与约束子树的布局先后顺序。
|
||||
@MainActor
|
||||
private final class DroneMaterialPreviewZoomView: UIScrollView {
|
||||
/// 由素材单元配置的图片,也是 UIScrollView 的缩放目标。
|
||||
let imageView = UIImageView()
|
||||
private var lastViewportSize = CGSize.zero
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
imageView.isUserInteractionEnabled = true
|
||||
addSubview(imageView)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func layoutSubviews() {
|
||||
super.layoutSubviews()
|
||||
let viewportSize = bounds.size
|
||||
guard viewportSize.width > 0, viewportSize.height > 0, viewportSize != lastViewportSize else { return }
|
||||
lastViewportSize = viewportSize
|
||||
setZoomScale(1, animated: false)
|
||||
imageView.frame = CGRect(origin: .zero, size: viewportSize)
|
||||
contentSize = viewportSize
|
||||
setContentOffset(.zero, animated: false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 素材库只提出导航请求,由机巢入口协调预览与尚未实现的交付流程。
|
||||
@MainActor
|
||||
protocol DroneMaterialsViewControllerDelegate: AnyObject {
|
||||
/// 预览单项素材,保持素材库现有选择与下载批次。
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestPreview material: DroneMaterial)
|
||||
/// 请求当前拍摄记录的交付占位入口。
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord)
|
||||
}
|
||||
|
||||
/// 订单素材库:按拍摄记录分组,支持点位筛选、独立预览选择与前台演示下载。
|
||||
@MainActor
|
||||
final class DroneMaterialsViewController: BaseViewController {
|
||||
/// 素材展示、选择与批次状态的来源。
|
||||
let viewModel: DroneMaterialsViewModel
|
||||
/// 将跨页面操作交给机巢导航入口。
|
||||
weak var delegate: DroneMaterialsViewControllerDelegate?
|
||||
|
||||
/// 订单、筛选和拍摄记录采用稳定分区标识,刷新时保留当前滚动位置。
|
||||
private enum Section: Hashable {
|
||||
case order, filters, summary, record(String), message
|
||||
}
|
||||
|
||||
/// 网格和辅助单元的稳定身份,不将可变选择状态纳入 Diffable 标识。
|
||||
private enum Item: Hashable {
|
||||
case order, filter(String?), context, summary, material(String), message
|
||||
}
|
||||
|
||||
/// 底部主按钮当前对应的操作;启用规则由 ViewModel 提供。
|
||||
private enum FooterAction {
|
||||
case download, resume, retry, selectMore, permission, none
|
||||
}
|
||||
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||||
private let footerView = DroneMaterialsFooterView()
|
||||
private let refreshControl = UIRefreshControl()
|
||||
private let transferDriver = DroneMaterialDemoTransferDriver()
|
||||
private var footerAction: FooterAction = .download
|
||||
private var recordsByID: [String: DroneMaterialRecord] = [:]
|
||||
private var materialsByID: [String: DroneMaterial] = [:]
|
||||
private var originalInteractivePopEnabled: Bool?
|
||||
|
||||
private var hasRunningDownload: Bool {
|
||||
switch viewModel.downloadPhase {
|
||||
case .downloading, .awaitingSave, .saving: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
|
||||
/// 使用入口共享的素材状态,支持订单全量入口与当前任务点位入口。
|
||||
init(viewModel: DroneMaterialsViewModel) {
|
||||
self.viewModel = viewModel
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 返回素材页只刷新快照,不自动继续已暂停的批次。
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
viewModel.refresh()
|
||||
if dataSource != nil { applySnapshot(animated: false) }
|
||||
}
|
||||
|
||||
/// 真正返回上层页面时停止未完成项;全屏预览覆盖素材页不触发离页处理。
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
if isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true {
|
||||
transferDriver.stop()
|
||||
viewModel.leavePage()
|
||||
restoreInteractivePopGesture()
|
||||
}
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "订单素材库"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain,
|
||||
target: self, action: #selector(backTapped))
|
||||
back.accessibilityIdentifier = "drone.materials.back"
|
||||
back.accessibilityLabel = "返回"
|
||||
navigationItem.leftBarButtonItem = back
|
||||
let refresh = UIBarButtonItem(title: "刷新", style: .plain,
|
||||
target: self, action: #selector(refreshTapped))
|
||||
refresh.accessibilityIdentifier = "drone.materials.refresh"
|
||||
refresh.accessibilityLabel = "刷新素材状态"
|
||||
#if DEBUG
|
||||
let scenarios = DroneMaterialsScenario.allCases.map { scenario in
|
||||
UIAction(title: scenario.title) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.transferDriver.stop()
|
||||
self.viewModel.applyScenario(scenario)
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
let advance = UIAction(title: "模拟下一项下载回执", image: UIImage(systemName: "arrow.forward.circle")) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.transferDriver.stop()
|
||||
self.viewModel.advanceDemoDownload()
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
let allowPermission = UIAction(title: "模拟相册权限恢复", image: UIImage(systemName: "lock.open")) { [weak self] _ in
|
||||
guard let self, self.viewModel.photoPermission != .allowed else { return }
|
||||
self.transferDriver.stop()
|
||||
self.viewModel.setPhotoPermission(.allowed)
|
||||
self.applySnapshot(animated: true)
|
||||
self.showToast("演示权限已恢复,请手动继续下载")
|
||||
}
|
||||
let menu = UIMenu(title: "素材库本地演示状态", children: [
|
||||
UIMenu(options: .displayInline, children: scenarios),
|
||||
UIMenu(options: .displayInline, children: [advance, allowPermission])
|
||||
])
|
||||
let debug = UIBarButtonItem(image: UIImage(systemName: "slider.horizontal.3"), menu: menu)
|
||||
debug.accessibilityIdentifier = "drone.materials.scenarios"
|
||||
debug.accessibilityLabel = "素材库演示状态"
|
||||
navigationItem.rightBarButtonItems = [refresh, debug]
|
||||
#else
|
||||
navigationItem.rightBarButtonItem = refresh
|
||||
#endif
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = .white
|
||||
collectionView.backgroundColor = .white
|
||||
collectionView.alwaysBounceVertical = true
|
||||
collectionView.showsVerticalScrollIndicator = false
|
||||
collectionView.accessibilityIdentifier = "drone.materials.list"
|
||||
collectionView.delegate = self
|
||||
collectionView.register(DroneMaterialOrderCell.self, forCellWithReuseIdentifier: "order")
|
||||
collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "filter")
|
||||
collectionView.register(DroneMaterialPointContextCell.self, forCellWithReuseIdentifier: "context")
|
||||
collectionView.register(DroneMaterialSelectionCell.self, forCellWithReuseIdentifier: "summary")
|
||||
collectionView.register(DroneMaterialCell.self, forCellWithReuseIdentifier: "material")
|
||||
collectionView.register(DroneMaterialMessageCell.self, forCellWithReuseIdentifier: "message")
|
||||
collectionView.register(DroneMaterialRecordHeaderView.self,
|
||||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
||||
withReuseIdentifier: "recordHeader")
|
||||
collectionView.register(DroneMaterialSeparatorView.self,
|
||||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
|
||||
withReuseIdentifier: "separator")
|
||||
refreshControl.tintColor = DroneDockStyle.primary
|
||||
collectionView.refreshControl = refreshControl
|
||||
view.addSubview(collectionView)
|
||||
view.addSubview(footerView)
|
||||
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 bindActions() {
|
||||
refreshControl.addTarget(self, action: #selector(refreshTapped), for: .valueChanged)
|
||||
footerView.onPrimaryTap = { [weak self] in self?.performFooterAction() }
|
||||
footerView.onSecondaryTap = { [weak self] in
|
||||
guard let self else { return }
|
||||
self.viewModel.clearBatch()
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
|
||||
name: UIApplication.willResignActiveNotification, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
|
||||
name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||
}
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { [weak self] sectionIndex, environment in
|
||||
guard let self, let dataSource = self.dataSource else { return nil }
|
||||
let sections = dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(sectionIndex) else { return nil }
|
||||
let section = sections[sectionIndex]
|
||||
switch section {
|
||||
case .record:
|
||||
let width = (environment.container.effectiveContentSize.width - 44) / 2
|
||||
let height = width * 0.57 + 51
|
||||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
|
||||
widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1)
|
||||
))
|
||||
let group = NSCollectionLayoutGroup.horizontal(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)),
|
||||
repeatingSubitem: item, count: 2
|
||||
)
|
||||
group.interItemSpacing = .fixed(12)
|
||||
let layoutSection = NSCollectionLayoutSection(group: group)
|
||||
layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 20, trailing: 16)
|
||||
layoutSection.interGroupSpacing = 12
|
||||
layoutSection.boundarySupplementaryItems = [
|
||||
NSCollectionLayoutBoundarySupplementaryItem(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(80)),
|
||||
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top
|
||||
),
|
||||
NSCollectionLayoutBoundarySupplementaryItem(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(1)),
|
||||
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom
|
||||
)
|
||||
]
|
||||
return layoutSection
|
||||
case .order:
|
||||
return self.singleColumnSection(height: .estimated(116))
|
||||
case .filters:
|
||||
if self.viewModel.pointID != nil { return self.singleColumnSection(height: .absolute(46)) }
|
||||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
|
||||
widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)
|
||||
))
|
||||
let group = NSCollectionLayoutGroup.horizontal(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .absolute(90), heightDimension: .absolute(36)),
|
||||
subitems: [item]
|
||||
)
|
||||
let layoutSection = NSCollectionLayoutSection(group: group)
|
||||
layoutSection.orthogonalScrollingBehavior = .continuous
|
||||
layoutSection.interGroupSpacing = 9
|
||||
layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 16, bottom: 8, trailing: 16)
|
||||
return layoutSection
|
||||
case .summary:
|
||||
return self.singleColumnSection(height: .absolute(46))
|
||||
case .message:
|
||||
return self.singleColumnSection(height: .absolute(250))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func singleColumnSection(height: NSCollectionLayoutDimension) -> NSCollectionLayoutSection {
|
||||
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
|
||||
widthDimension: .fractionalWidth(1), heightDimension: height
|
||||
))
|
||||
let group = NSCollectionLayoutGroup.vertical(
|
||||
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height), subitems: [item]
|
||||
)
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
|
||||
return section
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, indexPath, item in
|
||||
guard let self else { return nil }
|
||||
switch item {
|
||||
case .order:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: indexPath) as! DroneMaterialOrderCell
|
||||
cell.apply(order: self.viewModel.order)
|
||||
return cell
|
||||
case .filter(let id):
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "filter", for: indexPath) as! DroneMaterialFilterCell
|
||||
if let filter = self.viewModel.filters.first(where: { $0.id == id }) {
|
||||
cell.apply(title: filter.title, id: filter.id,
|
||||
selected: filter.id == self.viewModel.selectedFilterID, locked: self.viewModel.isSelectionLocked)
|
||||
}
|
||||
return cell
|
||||
case .context:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "context", for: indexPath) as! DroneMaterialPointContextCell
|
||||
let title = self.viewModel.filters.first(where: { $0.id == self.viewModel.pointID })?.title
|
||||
?? self.viewModel.sections.first?.pointName ?? "当前拍摄点"
|
||||
cell.apply(title: title)
|
||||
return cell
|
||||
case .summary:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "summary", for: indexPath) as! DroneMaterialSelectionCell
|
||||
cell.apply(recordCount: self.viewModel.sections.count, allSelected: self.viewModel.isAllSelected,
|
||||
enabled: !self.viewModel.isSelectionLocked && !self.viewModel.downloadableIDs.isEmpty)
|
||||
cell.onSelectAllTap = { [weak self] in
|
||||
guard let self else { return }
|
||||
self.viewModel.selectAll()
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
return cell
|
||||
case .material(let id):
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "material", for: indexPath) as! DroneMaterialCell
|
||||
if let material = self.materialsByID[id] {
|
||||
let completed: Bool
|
||||
if case .completed = material.downloadState { completed = true } else { completed = false }
|
||||
cell.apply(material: material, selected: self.viewModel.selectedIDs.contains(id),
|
||||
selectionEnabled: !self.viewModel.isSelectionLocked && self.viewModel.downloadableIDs.contains(id),
|
||||
completed: completed)
|
||||
cell.onPreviewTap = { [weak self] in
|
||||
guard let self, let current = self.viewModel.material(id: id), current.canPreview else { return }
|
||||
self.delegate?.materialsViewController(self, didRequestPreview: current)
|
||||
}
|
||||
cell.onSelectionTap = { [weak self] in
|
||||
guard let self else { return }
|
||||
self.viewModel.toggleSelection(id: id)
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
return cell
|
||||
case .message:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: indexPath) as! DroneMaterialMessageCell
|
||||
switch self.viewModel.listState {
|
||||
case .loading:
|
||||
cell.apply(title: "正在获取素材", detail: "请稍候", symbol: "arrow.triangle.2.circlepath")
|
||||
case .failed(let message):
|
||||
cell.apply(title: "素材加载失败", detail: "\(message)\n请下拉或点击右上角刷新", symbol: "wifi.exclamationmark")
|
||||
case .loaded:
|
||||
cell.apply(title: "暂无拍摄素材", detail: "拍摄完成后的素材会显示在这里", symbol: "photo.on.rectangle.angled")
|
||||
}
|
||||
return cell
|
||||
}
|
||||
}
|
||||
dataSource.supplementaryViewProvider = { [weak self] list, kind, indexPath in
|
||||
guard let self else { return nil }
|
||||
if kind == UICollectionView.elementKindSectionFooter {
|
||||
return list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "separator", for: indexPath)
|
||||
}
|
||||
let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "recordHeader", for: indexPath) as! DroneMaterialRecordHeaderView
|
||||
self.applyHeader(header, sectionIndex: indexPath.section)
|
||||
return header
|
||||
}
|
||||
}
|
||||
|
||||
private func applySnapshot(animated: Bool) {
|
||||
guard isViewLoaded, dataSource != nil else { return }
|
||||
let records = viewModel.sections
|
||||
recordsByID = Dictionary(uniqueKeysWithValues: records.map { ($0.id, $0) })
|
||||
materialsByID = Dictionary(uniqueKeysWithValues: records.flatMap(\.materials).map { ($0.id, $0) })
|
||||
let previous = dataSource.snapshot()
|
||||
let existing = Set(previous.itemIdentifiers)
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
||||
snapshot.appendSections([.order, .filters, .summary])
|
||||
snapshot.appendItems([.order], toSection: .order)
|
||||
snapshot.appendItems(viewModel.pointID == nil ? viewModel.filters.map { .filter($0.id) } : [.context], toSection: .filters)
|
||||
snapshot.appendItems([.summary], toSection: .summary)
|
||||
switch viewModel.listState {
|
||||
case .loaded where !records.isEmpty:
|
||||
for record in records {
|
||||
let section = Section.record(record.id)
|
||||
snapshot.appendSections([section])
|
||||
snapshot.appendItems(record.materials.map { .material($0.id) }, toSection: section)
|
||||
}
|
||||
default:
|
||||
snapshot.appendSections([.message])
|
||||
snapshot.appendItems([.message], toSection: .message)
|
||||
}
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
|
||||
applyFooter()
|
||||
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
|
||||
guard let self else { return }
|
||||
let kind = UICollectionView.elementKindSectionHeader
|
||||
for path in self.collectionView.indexPathsForVisibleSupplementaryElements(ofKind: kind) {
|
||||
guard let header = self.collectionView.supplementaryView(forElementKind: kind, at: path) as? DroneMaterialRecordHeaderView else { continue }
|
||||
self.applyHeader(header, sectionIndex: path.section)
|
||||
}
|
||||
}
|
||||
if previous.sectionIdentifiers != snapshot.sectionIdentifiers { collectionView.collectionViewLayout.invalidateLayout() }
|
||||
updateInteractivePopGesture()
|
||||
}
|
||||
|
||||
private func applyHeader(_ header: DroneMaterialRecordHeaderView, sectionIndex: Int) {
|
||||
let sections = dataSource.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(sectionIndex), case .record(let id) = sections[sectionIndex], let record = recordsByID[id] else { return }
|
||||
header.apply(record: record)
|
||||
header.onDeliveryTap = { [weak self] in
|
||||
guard let self, let current = self.recordsByID[id] else { return }
|
||||
self.delegate?.materialsViewController(self, didRequestDelivery: current)
|
||||
}
|
||||
}
|
||||
|
||||
private func applyFooter() {
|
||||
if viewModel.photoPermission != .allowed {
|
||||
footerAction = .permission
|
||||
footerView.apply(title: "无法保存到手机相册", detail: "演示相册权限未开启,恢复后请手动继续。",
|
||||
primaryTitle: "检查相册权限", primarySymbol: "lock", enabled: true,
|
||||
identifier: "drone.materials.permission", progress: nil, tone: .orange)
|
||||
return
|
||||
}
|
||||
switch viewModel.downloadPhase {
|
||||
case .idle:
|
||||
footerAction = .download
|
||||
footerView.apply(title: "已选择\(viewModel.selectedCount)项", detail: "仅可选择已上传素材 · 本次为本地演示",
|
||||
primaryTitle: "下载所选素材", primarySymbol: "arrow.down.to.line", enabled: viewModel.canStartDownload,
|
||||
identifier: "drone.materials.download", progress: nil)
|
||||
case .downloading, .awaitingSave, .saving:
|
||||
footerAction = .none
|
||||
footerView.apply(title: "本次下载\(viewModel.batchTotalCount)项 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
|
||||
detail: "请保持本页开启,下载期间不可更改选择",
|
||||
primaryTitle: viewModel.downloadButtonTitle, primarySymbol: "arrow.triangle.2.circlepath", enabled: false,
|
||||
identifier: "drone.materials.download", progress: viewModel.batchProgress, tone: .blue)
|
||||
case .paused:
|
||||
footerAction = .resume
|
||||
footerView.apply(title: "下载已暂停 · 已完成\(viewModel.completedCount)/\(viewModel.batchTotalCount)项",
|
||||
detail: "已完成项会保留;继续时仅处理未完成文件。",
|
||||
primaryTitle: "继续下载", primarySymbol: "play.fill", enabled: true,
|
||||
identifier: "drone.materials.continue", progress: viewModel.batchProgress, tone: .orange)
|
||||
case .partialFailure:
|
||||
footerAction = .retry
|
||||
footerView.apply(title: "部分素材下载失败", detail: "演示完成\(viewModel.completedCount)项 · 失败\(viewModel.failedCount)项,重试仅处理失败项",
|
||||
primaryTitle: "重试失败素材(\(viewModel.failedCount))", primarySymbol: "arrow.clockwise", enabled: viewModel.failedCount > 0,
|
||||
identifier: "drone.materials.retry", progress: nil, secondaryTitle: "选择其他素材", tone: .orange)
|
||||
case .completed:
|
||||
footerAction = .selectMore
|
||||
footerView.apply(title: "本次素材演示完成", detail: "\(viewModel.completedCount)项演示完成,未写入系统相册",
|
||||
primaryTitle: "继续选择素材", primarySymbol: "checkmark.circle", enabled: true,
|
||||
identifier: "drone.materials.continueSelecting", progress: nil, tone: .green)
|
||||
}
|
||||
}
|
||||
|
||||
private func performFooterAction() {
|
||||
var shouldStartDriver = false
|
||||
switch footerAction {
|
||||
case .download:
|
||||
shouldStartDriver = viewModel.startDownload()
|
||||
case .resume:
|
||||
shouldStartDriver = viewModel.continueDownload()
|
||||
case .retry:
|
||||
shouldStartDriver = viewModel.retryFailed()
|
||||
case .selectMore:
|
||||
viewModel.clearBatch()
|
||||
case .permission:
|
||||
showAlert(title: "相册权限演示", message: "当前为本地演示,不读取或修改系统相册权限。可在右上角演示状态中选择“模拟相册权限恢复”,再手动继续下载。")
|
||||
case .none:
|
||||
return
|
||||
}
|
||||
applySnapshot(animated: true)
|
||||
if shouldStartDriver { startDemoTransfer() }
|
||||
}
|
||||
|
||||
private func startDemoTransfer() {
|
||||
guard let batch = viewModel.batch, !batch.isPaused else { return }
|
||||
transferDriver.start(viewModel: viewModel) { [weak self] in self?.applySnapshot(animated: true) }
|
||||
}
|
||||
|
||||
private func updateInteractivePopGesture() {
|
||||
guard let gesture = navigationController?.interactivePopGestureRecognizer else { return }
|
||||
if hasRunningDownload {
|
||||
if originalInteractivePopEnabled == nil { originalInteractivePopEnabled = gesture.isEnabled }
|
||||
gesture.isEnabled = false
|
||||
} else {
|
||||
restoreInteractivePopGesture()
|
||||
}
|
||||
}
|
||||
|
||||
private func restoreInteractivePopGesture() {
|
||||
guard let originalInteractivePopEnabled else { return }
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = originalInteractivePopEnabled
|
||||
self.originalInteractivePopEnabled = nil
|
||||
}
|
||||
|
||||
private func leaveMaterialsPage() {
|
||||
transferDriver.stop()
|
||||
viewModel.leavePage()
|
||||
restoreInteractivePopGesture()
|
||||
if let navigationController, navigationController.viewControllers.first !== self {
|
||||
navigationController.popViewController(animated: true)
|
||||
} else {
|
||||
dismiss(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func backTapped() {
|
||||
guard hasRunningDownload else { leaveMaterialsPage(); return }
|
||||
let alert = UIAlertController(title: "素材仍在下载",
|
||||
message: "离开将暂停未完成的下载,已完成项会保留。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续下载", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "离开并暂停", style: .default) { [weak self] _ in self?.leaveMaterialsPage() })
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
@objc private func refreshTapped() {
|
||||
viewModel.refresh()
|
||||
applySnapshot(animated: true)
|
||||
refreshControl.endRefreshing()
|
||||
}
|
||||
|
||||
@objc private func applicationWillResignActive() {
|
||||
transferDriver.stop()
|
||||
viewModel.pauseDownloads(reason: .background)
|
||||
if isViewLoaded { applySnapshot(animated: false) }
|
||||
}
|
||||
|
||||
@objc private func applicationDidBecomeActive() {
|
||||
viewModel.refresh()
|
||||
if isViewLoaded { applySnapshot(animated: false) }
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneMaterialsViewController: UICollectionViewDelegate {
|
||||
/// 点位标签整项可点,素材的预览与选择交由各自按钮处理。
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath), case .filter(let id) = item else { return }
|
||||
viewModel.selectFilter(id: id)
|
||||
applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user