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

457 lines
24 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 SnapKit
import UIKit
/// 机巢工作台:本地遥测、余次订单和今日统计;与订单页共享同一数据源。
final class DroneDockWorkbenchViewController: BaseViewController {
/// 工作台展示逻辑,后续真实数据源接入时可保留页面结构。
let viewModel: DroneDockWorkbenchViewModel
/// 工作台分区,设备和订单分别更新。
private enum Section: Int, CaseIterable { case context, devices, orders, statistics }
/// 使用稳定标识应用 Diffable 快照。
private enum Item: Hashable { case context, device(String), order(String), emptyDevices, emptyOrders, statistics }
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var devicePage = 0
private let pageControl = UIPageControl()
/// 默认使用本地演示数据,不会发起请求。
init(viewModel: DroneDockWorkbenchViewModel = DroneDockWorkbenchViewModel()) {
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 setupNavigationBar() {
title = "机巢工作台"
let receiptButton = UIButton(type: .system)
var configuration = UIButton.Configuration.plain()
configuration.title = "收款码"
configuration.image = UIImage(systemName: "qrcode")
configuration.imagePadding = 5
configuration.baseForegroundColor = DroneDockStyle.text
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 17)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var attributes = attributes
attributes.font = .systemFont(ofSize: 12)
return attributes
}
receiptButton.configuration = configuration
receiptButton.snp.makeConstraints { make in make.height.equalTo(44) }
receiptButton.accessibilityLabel = "收款码"
receiptButton.accessibilityIdentifier = "drone.workbench.receipt"
receiptButton.addTarget(self, action: #selector(receiptTapped), for: .touchUpInside)
let receipt = UIBarButtonItem(customView: receiptButton)
receipt.accessibilityLabel = "收款码"
navigationItem.rightBarButtonItem = receipt
navigationItem.backButtonDisplayMode = .minimal
}
override func setupUI() {
view.backgroundColor = DroneDockStyle.background
collectionView.backgroundColor = .clear
collectionView.alwaysBounceVertical = true
collectionView.accessibilityIdentifier = "drone.workbench.list"
collectionView.register(DroneDockDeviceCell.self, forCellWithReuseIdentifier: "device")
collectionView.register(DroneDockCompactOrderCell.self, forCellWithReuseIdentifier: "order")
collectionView.register(DroneDockContentCell.self, forCellWithReuseIdentifier: "content")
collectionView.register(DroneDockSectionHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
collectionView.register(DroneDockPageFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "pages")
let refresh = UIRefreshControl()
refresh.tintColor = DroneDockStyle.primary
refresh.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
collectionView.refreshControl = refresh
view.addSubview(collectionView)
pageControl.currentPageIndicatorTintColor = DroneDockStyle.primary
pageControl.pageIndicatorTintColor = UIColor(hex: 0xD9DFEB)
pageControl.isUserInteractionEnabled = false
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)
viewModel.refresh()
if dataSource != nil { applySnapshot(animated: false) }
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] collection, indexPath, item in
guard let self else { return nil }
switch item {
case .device(let id):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "device", for: indexPath) as! DroneDockDeviceCell
if let device = self.viewModel.devices.first(where: { $0.id == id }) { cell.cardView.apply(device: device) }
return cell
case .order(let id):
let cell = collection.dequeueReusableCell(withReuseIdentifier: "order", for: indexPath) as! DroneDockCompactOrderCell
if let order = self.viewModel.order(id: id) {
cell.apply(order: order)
cell.onShootingTap = { [weak self] in self?.showOrderEntry(id: id, action: .shooting) }
cell.onMaterialsTap = { [weak self] in self?.showOrderEntry(id: id, action: .materials) }
}
return cell
default:
let cell = collection.dequeueReusableCell(withReuseIdentifier: "content", for: indexPath) as! DroneDockContentCell
switch item {
case .context:
cell.applyContext("\(self.viewModel.context.scenicName) · \(self.viewModel.context.photographerName)")
#if DEBUG
cell.installScenarioMenu(UIMenu(title: "本地演示状态", children: DroneDockDemoScenario.allCases.map { scenario in
UIAction(title: scenario.title) { [weak self] _ in self?.applyScenario(scenario) }
}))
#endif
case .emptyDevices: cell.applyEmpty(symbol: "airplane", title: "暂无可用无人机", detail: "当前景区尚未配置无人机")
case .emptyOrders: cell.applyEmpty(symbol: "doc.text", title: "暂无待拍摄订单", detail: "已完成订单可在“查看全部”中查看")
case .statistics: cell.applyStatistics(self.viewModel.statistics)
default: break
}
return cell
}
}
dataSource.supplementaryViewProvider = { [weak self] collection, kind, indexPath in
guard let self else { return nil }
let sections = self.dataSource.snapshot().sectionIdentifiers
guard sections.indices.contains(indexPath.section) else { return nil }
let section = sections[indexPath.section]
if kind == UICollectionView.elementKindSectionFooter {
let footer = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "pages", for: indexPath) as! DroneDockPageFooter
footer.install(self.pageControl)
return footer
}
let header = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! DroneDockSectionHeader
header.apply(title: section == .orders ? "我的拍摄订单" : "今日统计",
count: section == .orders ? self.viewModel.orderCount : nil,
showsAction: section == .orders)
header.onViewAll = { [weak self] in self?.openOrders() }
return header
}
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, environment in
guard let self, let section = Section(rawValue: index) else { return nil }
let height: NSCollectionLayoutDimension
switch section {
case .context: height = .absolute(40)
case .devices: height = .absolute(self.viewModel.devices.isEmpty ? 132 : 248)
case .orders: height = .estimated(150)
case .statistics: height = .absolute(104)
}
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
let multiple = section == .devices && self.viewModel.devices.count > 1
let width: NSCollectionLayoutDimension = multiple ? .absolute(environment.container.effectiveContentSize.width - 48) : .fractionalWidth(1)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item])
let layout = NSCollectionLayoutSection(group: group)
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: section == .statistics ? 24 : 0, trailing: 16)
layout.interGroupSpacing = 12
if section == .devices {
if multiple {
layout.orthogonalScrollingBehavior = .groupPaging
layout.visibleItemsInvalidationHandler = { [weak self] _, offset, _ in
guard let self else { return }
let step = max(1, environment.container.effectiveContentSize.width - 36)
let page = min(self.viewModel.devices.count - 1, max(0, Int((offset.x / step).rounded())))
if self.devicePage != page {
self.devicePage = page
self.pageControl.currentPage = page
}
}
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(24)),
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom)]
} else { layout.contentInsets.bottom = 12 }
}
if section == .orders || section == .statistics {
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(54)),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)]
}
return layout
}
}
private func applySnapshot(animated: Bool) {
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections(Section.allCases)
snapshot.appendItems([.context], toSection: .context)
snapshot.appendItems(viewModel.devices.isEmpty ? [.emptyDevices] : viewModel.devices.map { .device($0.id) }, toSection: .devices)
snapshot.appendItems(viewModel.orders.isEmpty ? [.emptyOrders] : viewModel.orders.map { .order($0.id) }, toSection: .orders)
snapshot.appendItems([.statistics], toSection: .statistics)
let previous = Set(dataSource.snapshot().itemIdentifiers)
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) })
pageControl.numberOfPages = viewModel.devices.count
pageControl.currentPage = min(devicePage, max(0, viewModel.devices.count - 1))
dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in
guard let self else { return }
for case let header as DroneDockSectionHeader in self.collectionView.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionHeader) {
if header.representsOrders {
header.apply(title: "我的拍摄订单", count: self.viewModel.orderCount, showsAction: true)
}
}
}
}
private func openOrders() {
let controller = DroneShootingOrdersViewController(viewModel: DroneShootingOrdersViewModel(store: viewModel.store))
controller.delegate = self
navigationController?.pushViewController(controller, animated: true)
}
/// 拍摄和素材进入对应本地页面,成片交付暂保留入口提示。
private enum OrderEntry { case shooting, materials, delivery }
private func showOrderEntry(id: String, action: OrderEntry) {
guard let order = viewModel.store.orders.first(where: { $0.id == id }) else { return }
showPreviewEntry(order: order, action: action)
}
private func showPreviewEntry(order: DroneShootingOrder, action: OrderEntry, presenter: UIViewController? = nil) {
let title: String
let detail: String
switch action {
case .shooting:
openShootingOrder(id: order.id, from: presenter ?? self)
return
case .materials:
openMaterials(orderID: order.id, from: presenter ?? self)
return
case .delivery:
title = "交付成片"
detail = "\(order.deliveredVideoCount) 个已交付视频"
}
let alert = UIAlertController(title: title, message: "\(order.customerName)\n\(detail)\n\n此入口将在后续页面搭建时接入,当前不会执行实际操作。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "知道了", style: .default))
(presenter ?? self).present(alert, animated: true)
}
/// 始终读取当前范围快照,恢复原任务而不因重新进入重复召唤。
private func openShootingOrder(id: String, from presenter: UIViewController) {
guard let order = viewModel.store.shootingOrder(id: id) else { return }
if order.activeTask != nil {
openTask(orderID: id, from: presenter)
} else if order.remainingShootingCount > 0 {
let controller = DroneShootingPreparationViewController(
viewModel: DroneShootingPreparationViewModel(store: viewModel.store, orderID: id)
)
controller.delegate = self
presenter.navigationController?.pushViewController(controller, animated: true)
}
}
private func openTask(orderID: String, from presenter: UIViewController) {
let controller = DroneShootingTaskViewController(
viewModel: DroneShootingTaskViewModel(store: viewModel.store, orderID: orderID)
)
controller.delegate = self
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: "套餐收款页面将在后续搭建,当前不会创建订单或发起收款。")
}
@objc private func refreshTriggered() {
viewModel.refresh()
applySnapshot(animated: true)
collectionView.refreshControl?.endRefreshing()
}
#if DEBUG
private func applyScenario(_ scenario: DroneDockDemoScenario) {
viewModel.applyScenario(scenario)
devicePage = 0
collectionView.setCollectionViewLayout(makeLayout(), animated: false)
applySnapshot(animated: true)
}
#endif
}
extension DroneDockWorkbenchViewController: DroneShootingOrdersViewControllerDelegate {
func shootingOrdersViewController(_ controller: DroneShootingOrdersViewController, didSelectShooting order: DroneShootingOrder) {
showPreviewEntry(order: order, action: .shooting, presenter: controller)
}
func shootingOrdersViewController(_ controller: DroneShootingOrdersViewController, didSelectMaterials order: DroneShootingOrder) {
showPreviewEntry(order: order, action: .materials, presenter: controller)
}
func shootingOrdersViewController(_ controller: DroneShootingOrdersViewController, didSelectDelivery order: DroneShootingOrder) {
showPreviewEntry(order: order, action: .delivery, presenter: controller)
}
}
extension DroneDockWorkbenchViewController: DroneShootingPreparationViewControllerDelegate {
func shootingPreparationViewController(_ controller: DroneShootingPreparationViewController, didRequestTaskFor orderID: String) {
openTask(orderID: orderID, from: controller)
}
}
extension DroneDockWorkbenchViewController: DroneShootingTaskViewControllerDelegate {
func shootingTaskViewControllerDidRequestWorkbench(_ controller: DroneShootingTaskViewController) {
navigationController?.popToViewController(self, animated: true)
}
func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestPreparationFor order: DroneShootingOrder) {
guard let navigationController, let index = navigationController.viewControllers.firstIndex(where: { $0 === self }) else { return }
let preparation = DroneShootingPreparationViewController(
viewModel: DroneShootingPreparationViewModel(store: viewModel.store, orderID: order.id)
)
preparation.delegate = self
navigationController.setViewControllers(Array(navigationController.viewControllers.prefix(through: index)) + [preparation], animated: true)
}
func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestMaterialsFor order: DroneShootingOrder) {
guard let order = viewModel.store.shootingOrder(id: order.id) else { return }
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)
}
}
/// 工作台标题及查看全部入口。
private final class DroneDockSectionHeader: UICollectionReusableView {
var onViewAll: (() -> Void)?
private(set) var representsOrders = false
private let titleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
private let countLabel = DroneDockStyle.label(size: 15, color: DroneDockStyle.secondary)
private let button = UIButton(type: .system)
override init(frame: CGRect) {
super.init(frame: frame)
let stack = UIStackView(arrangedSubviews: [titleLabel, countLabel, UIView(), button])
stack.alignment = .center
stack.spacing = 9
button.setTitle("查看全部 ›", for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 13)
button.tintColor = DroneDockStyle.primary
button.accessibilityIdentifier = "drone.workbench.allOrders"
button.addTarget(self, action: #selector(viewAllTapped), for: .touchUpInside)
button.snp.makeConstraints { make in make.height.equalTo(44) }
addSubview(stack)
stack.snp.makeConstraints { make in make.leading.trailing.centerY.equalToSuperview() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
func apply(title: String, count: Int?, showsAction: Bool) {
representsOrders = showsAction
titleLabel.text = title
countLabel.text = count.map(String.init)
countLabel.isHidden = count == nil
button.isHidden = !showsAction
}
@objc private func viewAllTapped() { onViewAll?() }
}
/// 单个页面指示器的容器,只有多设备布局才创建此页脚。
private final class DroneDockPageFooter: UICollectionReusableView {
func install(_ control: UIPageControl) {
guard control.superview !== self else { return }
control.removeFromSuperview()
addSubview(control)
control.snp.makeConstraints { make in make.center.equalToSuperview(); make.height.equalTo(24) }
}
}
/// 场景名称、空态和今日统计共用的简单容器。
private final class DroneDockContentCell: UICollectionViewCell {
private var embeddedView: UIView?
private weak var contextLabel: UILabel?
func applyContext(_ title: String) {
let label = DroneDockStyle.label(title, size: 12, color: DroneDockStyle.secondary)
label.numberOfLines = 2
install(label, insets: UIEdgeInsets(top: 6, left: 0, bottom: 8, right: 0), isCard: false)
contextLabel = label
}
#if DEBUG
func installScenarioMenu(_ menu: UIMenu) {
guard let label = contextLabel else { return }
label.removeFromSuperview()
embeddedView = nil
let button = UIButton(type: .system)
button.setTitle("演示状态 ⌄", for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 11)
button.tintColor = DroneDockStyle.primary
button.menu = menu
button.showsMenuAsPrimaryAction = true
button.accessibilityLabel = "本地演示状态"
button.setContentHuggingPriority(.required, for: .horizontal)
let row = UIStackView(arrangedSubviews: [label, button])
row.alignment = .center
row.spacing = 8
install(row, insets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0), isCard: false)
}
#endif
func applyEmpty(symbol: String, title: String, detail: String) {
let icon = UIImageView(image: UIImage(systemName: symbol))
icon.tintColor = DroneDockStyle.secondary.withAlphaComponent(0.6)
icon.contentMode = .scaleAspectFit
icon.snp.makeConstraints { make in make.size.equalTo(28) }
let caption = DroneDockStyle.label(detail, size: 12, color: DroneDockStyle.secondary)
caption.numberOfLines = 0
caption.textAlignment = .center
let stack = UIStackView(arrangedSubviews: [icon, DroneDockStyle.label(title, size: 14, weight: .medium), caption])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 9
install(stack, insets: UIEdgeInsets(top: 20, left: 16, bottom: 20, right: 16), isCard: true)
}
func applyStatistics(_ value: DroneDockDailyStatistics) {
let values = [("\(value.orderCount)", "成交订单"), (value.revenueText, "成交金额"), ("\(value.successfulShootingCount)", "成功拍摄")]
let stack = UIStackView(arrangedSubviews: values.map { value, title in
let number = DroneDockStyle.label(value, size: 23, weight: .semibold)
number.adjustsFontSizeToFitWidth = true
number.minimumScaleFactor = 0.7
let column = UIStackView(arrangedSubviews: [number, DroneDockStyle.label(title, size: 12, color: DroneDockStyle.secondary)])
column.axis = .vertical
column.alignment = .center
column.spacing = 9
return column
})
stack.distribution = .fillEqually
install(stack, insets: UIEdgeInsets(top: 23, left: 10, bottom: 23, right: 10), isCard: true)
}
private func install(_ view: UIView, insets: UIEdgeInsets, isCard: Bool) {
embeddedView?.removeFromSuperview()
embeddedView = view
if isCard { DroneDockStyle.applyCard(to: contentView) } else { contentView.backgroundColor = .clear }
contentView.addSubview(view)
view.snp.makeConstraints { make in make.edges.equalToSuperview().inset(insets) }
}
}