Files
suixinkan_uikit/suixinkan/UI/DroneDock/DroneDockMaterialsViewController.swift
T

445 lines
22 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import AVKit
import Kingfisher
import SnapKit
import UIKit
/// 从订单详情与任务接口读取的素材库,点位筛选只改变任务列表。
@MainActor
final class DroneDockMaterialsViewController: BaseViewController {
/// 保存当前订单摘要、点位和任务的真实状态。
let viewModel: DroneDockMaterialsViewModel
/// 元数据与媒体分区独立,任务没有素材时也保留其状态。
private enum Section: Hashable { case order, filters, summary, task(Int), media(Int), message }
/// 素材 ID 只在所属任务内唯一,使用任务 ID 共同构成稳定身份。
private enum Item: Hashable {
case order, filter(Int?), summary, task(Int), file(Int, Int), film(Int, Int), message
}
/// 整页刷新更新两个接口;筛选及列表重试只读取任务。
private enum LoadAction { case refresh, filter(Int?), retry }
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var loadTask: Task<Void, Never>?
private var operation: LoadAction?
private var hasAppeared = false
/// 注入冻结订单范围的只读素材服务。
init(viewModel: DroneDockMaterialsViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
hidesBottomBarWhenPushed = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
deinit { loadTask?.cancel() }
override func setupNavigationBar() {
title = "订单素材库"
navigationItem.backButtonDisplayMode = .minimal
let refresh = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshTapped))
refresh.accessibilityIdentifier = "drone.materials.remote.refresh"
navigationItem.rightBarButtonItem = refresh
}
override func setupUI() {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.accessibilityIdentifier = "drone.materials.remote.list"
collectionView.delegate = self
collectionView.register(DroneDockMaterialTextCell.self, forCellWithReuseIdentifier: "text")
collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "filter")
collectionView.register(DroneDockMaterialMediaCell.self, forCellWithReuseIdentifier: "media")
let refresh = UIRefreshControl()
refresh.tintColor = DroneDockStyle.primary
refresh.addTarget(self, action: #selector(refreshTapped), for: .valueChanged)
collectionView.refreshControl = refresh
view.addSubview(collectionView)
configureDataSource()
applySnapshot(animated: false)
}
override func setupConstraints() {
collectionView.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.bottom.equalToSuperview()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard !hasAppeared else { return }
hasAppeared = true
load(.refresh)
}
/// 确认离开后再清理;交互式返回取消或媒体预览覆盖不会丢失当前数据。
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true || parent == nil else { return }
hasAppeared = false
loadTask?.cancel()
operation = nil
viewModel.invalidate()
collectionView.refreshControl?.endRefreshing()
}
private var displayedSpotID: Int? {
if case .filter(let id) = operation { return id }
return viewModel.selectedSpotID
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] collection, path, item in
guard let self else { return nil }
switch item {
case .filter(let id):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "filter", for: path) as! DroneMaterialFilterCell
let title = id.flatMap { id in self.viewModel.spots.first { $0.id == id } }.map { Self.usable($0.name, fallback: "点位 \($0.id)") } ?? "全部点位"
cell.apply(title: title, id: id.map(String.init), selected: id == self.displayedSpotID, locked: self.viewModel.detail == nil)
return cell
case .file(let taskID, let fileID):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell
if let file = self.task(taskID)?.materials.first(where: { $0.id == fileID }) {
cell.apply(file: file, taskID: taskID)
}
return cell
case .film(let taskID, _):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "media", for: path) as! DroneDockMaterialMediaCell
if let film = self.task(taskID)?.film { cell.apply(film: film, taskID: taskID) }
return cell
default:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! DroneDockMaterialTextCell
self.configureText(cell, item: item)
return cell
}
}
}
private func configureText(_ cell: DroneDockMaterialTextCell, item: Item) {
switch item {
case .order:
guard let order = viewModel.detail?.order else { return }
cell.apply(title: order.touristTitle, body: "\(order.orderNumberText)\n\(order.packageTitle) · \(order.statusTitle)\n\(order.progressTitle)", identifier: "drone.materials.remote.order")
case .summary:
let text = viewModel.total.map { "\($0) 条任务记录 · 最新在前" } ?? "任务记录"
cell.apply(title: text, body: nil, identifier: "drone.materials.remote.summary", compact: true)
case .task(let id):
guard let task = task(id) else { return }
let number = task.sequence.map { "任务 \($0)" } ?? "任务 \(id)"
let title = "\(number) · \(Self.usable(task.spotName, fallback: "点位 \(task.spotID)"))"
var lines = ["\(Self.usable(task.airLineName, fallback: "航线待确认")) · \(Self.flightTitle(task.flightStatus))",
Self.usable(task.createdAt, fallback: "时间待确认")]
if task.materials.isEmpty { lines.append("暂无原素材") }
if task.film == nil { lines.append("暂无视频成片") }
cell.apply(title: title, body: lines.joined(separator: "\n"), identifier: "drone.materials.remote.task.\(id)")
case .message:
if operation != nil || viewModel.isLoading || viewModel.isLoadingTasks {
cell.apply(title: viewModel.detail == nil ? "正在加载订单素材库" : "正在加载任务素材", body: nil, identifier: "drone.materials.remote.loading")
} else if let error = viewModel.detailErrorMessage {
cell.apply(title: "订单信息加载失败", body: error, identifier: "drone.materials.remote.error", button: "重试", actionID: "drone.materials.remote.retry") { [weak self] in self?.load(.refresh) }
} else if let error = viewModel.tasksErrorMessage {
cell.apply(title: "任务素材加载失败", body: error, identifier: "drone.materials.remote.error", button: "重试", actionID: "drone.materials.remote.retry") { [weak self] in self?.load(.retry) }
} else {
cell.apply(title: displayedSpotID == nil ? "暂无任务记录" : "当前点位暂无任务记录", body: "拍摄任务与素材更新后,可下拉刷新查看", identifier: "drone.materials.remote.empty")
}
default: break
}
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, environment in
guard let self, let dataSource = self.dataSource else { return nil }
let sections = dataSource.snapshot().sectionIdentifiers
guard sections.indices.contains(index) else { return nil }
switch sections[index] {
case .filters:
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .estimated(104), heightDimension: .absolute(36)), subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .continuous
section.interGroupSpacing = 8
section.contentInsets = .init(top: 0, leading: 16, bottom: 8, trailing: 16)
return section
case .media:
let width = (environment.container.effectiveContentSize.width - 44) / 2
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 0.57 + 72)), repeatingSubitem: item, count: 2)
group.interItemSpacing = .fixed(12)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 0, leading: 16, bottom: 16, trailing: 16)
section.interGroupSpacing = 12
return section
default:
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .estimated(80)))
let group = NSCollectionLayoutGroup.vertical(layoutSize: item.layoutSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = .init(top: 0, leading: 16, bottom: 0, trailing: 16)
return section
}
}
}
private func applySnapshot(animated: Bool) {
guard dataSource != nil else { return }
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
if viewModel.detail != nil {
snapshot.appendSections([.order, .filters])
snapshot.appendItems([.order], toSection: .order)
snapshot.appendItems([.filter(nil)] + viewModel.spots.map { .filter($0.id) }, toSection: .filters)
}
if operation == nil && !viewModel.isLoading && !viewModel.isLoadingTasks && viewModel.tasksErrorMessage == nil && viewModel.detailErrorMessage == nil && viewModel.total != nil {
snapshot.appendSections([.summary])
snapshot.appendItems([.summary], toSection: .summary)
for task in viewModel.tasks {
snapshot.appendSections([.task(task.id)])
snapshot.appendItems([.task(task.id)], toSection: .task(task.id))
var media = task.materials.map { Item.file(task.id, $0.id) }
if let film = task.film { media.append(.film(task.id, film.id)) }
if !media.isEmpty {
snapshot.appendSections([.media(task.id)])
snapshot.appendItems(media, toSection: .media(task.id))
}
}
}
if viewModel.tasks.isEmpty || operation != nil || viewModel.isLoading || viewModel.isLoadingTasks || viewModel.detailErrorMessage != nil || viewModel.tasksErrorMessage != nil {
snapshot.appendSections([.message])
snapshot.appendItems([.message], toSection: .message)
}
let previous = Set(dataSource.snapshot().itemIdentifiers)
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) })
dataSource.apply(snapshot, animatingDifferences: animated)
}
private func load(_ action: LoadAction) {
loadTask?.cancel()
operation = action
applySnapshot(animated: false)
loadTask = Task { @MainActor [weak self] in
guard let self else { return }
switch action {
case .refresh: await self.viewModel.refresh()
case .filter(let id): await self.viewModel.selectSpot(id: id)
case .retry: await self.viewModel.retryTasks()
}
guard !Task.isCancelled else { return }
self.operation = nil
self.collectionView.refreshControl?.endRefreshing()
self.applySnapshot(animated: true)
}
}
@objc private func refreshTapped() { load(.refresh) }
private func task(_ id: Int) -> DroneDockMaterialTask? { viewModel.tasks.first { $0.id == id } }
private func preview(url: URL, isVideo: Bool, title: String) {
if isVideo {
let player = AVPlayerViewController()
player.player = AVPlayer(url: url)
present(player, animated: true) { player.player?.play() }
} else {
navigationController?.pushViewController(DroneDockMaterialImageViewController(url: url, title: title), animated: true)
}
}
private static func usable(_ value: String?, fallback: String) -> String {
DroneDockHomeMetric.usableText(value) ?? fallback
}
private static func flightTitle(_ status: Int?) -> String {
switch status {
case 10: "待飞行"
case 20: "执行中"
case 30: "飞行成功"
case 40: "飞行失败"
case 50: "已取消"
case 60: "待确认"
default: "飞行状态待确认"
}
}
}
extension DroneDockMaterialsViewController: UICollectionViewDelegate {
/// 点位只重读任务;仅已就绪且有合法地址的媒体可进入真实预览。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .filter(let id):
guard viewModel.detail != nil, id != displayedSpotID else { return }
load(.filter(id))
case .file(let taskID, let fileID):
guard operation == nil, let file = task(taskID)?.materials.first(where: { $0.id == fileID }), let url = file.previewURL else { return }
preview(url: url, isVideo: file.fileType == 2, title: file.fileName ?? "原素材")
case .film(let taskID, _):
guard operation == nil, let film = task(taskID)?.film, let url = film.previewURL else { return }
preview(url: url, isVideo: true, title: film.fileName ?? "视频成片")
default: break
}
}
}
/// 摘要、任务状态及可恢复错误共用的自适应文字行。
@MainActor
private final class DroneDockMaterialTextCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 15, weight: .semibold)
private let bodyLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let button = UIButton(type: .system)
private var action: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.numberOfLines = 0
bodyLabel.numberOfLines = 0
let stack = UIStackView(arrangedSubviews: [titleLabel, bodyLabel, button])
stack.axis = .vertical
stack.spacing = 8
stack.alignment = .leading
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 14, left: 0, bottom: 16, right: 0)) }
titleLabel.snp.makeConstraints { $0.width.equalTo(stack) }
bodyLabel.snp.makeConstraints { $0.width.equalTo(stack) }
button.tintColor = DroneDockStyle.primary
button.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?, identifier: String, compact: Bool = false,
button buttonTitle: String? = nil, actionID: String? = nil, action: (() -> Void)? = nil) {
titleLabel.text = title
titleLabel.font = .systemFont(ofSize: compact ? 13 : 15, weight: .semibold)
bodyLabel.text = body
bodyLabel.isHidden = body == nil
button.isHidden = buttonTitle == nil
button.setTitle(buttonTitle, for: .normal)
button.accessibilityIdentifier = actionID
self.action = action
accessibilityIdentifier = identifier
}
@objc private func tapped() { action?() }
}
/// 加载远程缩略图并明确区分原素材、视频成片及不可预览状态。
@MainActor
private final class DroneDockMaterialMediaCell: UICollectionViewCell {
private let thumbnail = UIImageView()
private let icon = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 12, weight: .medium)
private let stateLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
thumbnail.contentMode = .scaleAspectFill
thumbnail.clipsToBounds = true
thumbnail.layer.cornerRadius = 8
thumbnail.backgroundColor = DroneDockStyle.background
icon.tintColor = DroneDockStyle.secondary
icon.contentMode = .scaleAspectFit
titleLabel.numberOfLines = 2
stateLabel.numberOfLines = 2
[thumbnail, icon, titleLabel, stateLabel].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(thumbnail.snp.width).multipliedBy(0.57) }
icon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(28) }
titleLabel.snp.makeConstraints { make in make.top.equalTo(thumbnail.snp.bottom).offset(8); make.leading.trailing.equalToSuperview() }
stateLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(4); make.leading.trailing.equalToSuperview(); make.bottom.lessThanOrEqualToSuperview() }
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func prepareForReuse() {
super.prepareForReuse()
thumbnail.kf.cancelDownloadTask()
thumbnail.image = nil
}
/// 未就绪的原素材仍显示服务端状态,但不会启动播放或下载。
func apply(file: DroneDockMaterialFile, taskID: Int) {
let state: String
switch file.uploadStatus {
case 0: state = "待上传"
case 1: state = file.previewURL == nil ? "暂不可预览" : (file.fileType == 2 ? "点击播放" : "点击预览")
case 2: state = "上传中"
case 3: state = "上传失败"
default: state = "素材状态待确认"
}
let kind = file.fileType == 1 ? "图片" : file.fileType == 2 ? "视频" : "文件"
let title = DroneDockHomeMetric.usableText(file.fileName) ?? "原素材 \(file.id)"
apply(title: title, state: "原素材 · \(kind) · \(state)", cover: file.coverURL,
fallback: file.fileType == 1 ? file.previewURL : nil, video: file.fileType == 2,
enabled: file.previewURL != nil, identifier: "drone.materials.remote.file.\(taskID).\(file.id)")
accessibilityHint = file.uploadStatus == 3 ? DroneDockHomeMetric.usableText(file.failureReason) : nil
}
/// 成片是任务中的独立视频,不混入原素材数量或上传状态。
func apply(film: DroneDockMaterialFilm, taskID: Int) {
apply(title: DroneDockHomeMetric.usableText(film.fileName) ?? "视频成片", state: "视频成片 · \(film.previewURL == nil ? "暂不可预览" : "点击播放")",
cover: film.coverURL, fallback: nil, video: true, enabled: film.previewURL != nil,
identifier: "drone.materials.remote.film.\(taskID).\(film.id)")
accessibilityHint = nil
}
private func apply(title: String, state: String, cover: String?, fallback: URL?, video: Bool, enabled: Bool, identifier: String) {
thumbnail.kf.cancelDownloadTask()
thumbnail.image = nil
let coverURL = cover.flatMap(URL.init(string:)).flatMap { url in
["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil ? url : nil
}
thumbnail.kf.setImage(with: coverURL ?? fallback)
icon.image = UIImage(systemName: video && enabled ? "play.circle.fill" : video ? "video" : "photo")
icon.isHidden = !video && (coverURL ?? fallback) != nil
titleLabel.text = title
stateLabel.text = state
accessibilityIdentifier = identifier
accessibilityLabel = "\(title),\(state)"
accessibilityTraits = enabled ? .button : [.notEnabled]
}
}
/// 通过 Kingfisher 展示真实图片,加载失败保留明确提示。
@MainActor
private final class DroneDockMaterialImageViewController: UIViewController {
private let url: URL
private let imageView = UIImageView()
private let message = UILabel()
/// 仅接收素材模型已经校验可预览的 HTTP(S) 地址。
init(url: URL, title: String) {
self.url = url
super.init(nibName: nil, bundle: nil)
self.title = title
hidesBottomBarWhenPushed = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
imageView.contentMode = .scaleAspectFit
imageView.accessibilityIdentifier = "drone.materials.remote.preview.image"
message.text = "正在加载图片"
message.textColor = .white
message.textAlignment = .center
message.numberOfLines = 0
view.addSubview(imageView)
view.addSubview(message)
imageView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
message.snp.makeConstraints { make in make.center.equalToSuperview(); make.leading.trailing.equalToSuperview().inset(24) }
imageView.kf.setImage(with: url) { [weak self] result in
switch result {
case .success: self?.message.isHidden = true
case .failure: self?.message.text = "图片加载失败,请返回后重试"
}
}
}
}