feat(drone-dock): 搭建机巢工作台与拍摄订单UI

This commit is contained in:
2026-10-23 15:56:53 +08:00
parent 78291905be
commit 8072d95d3b
169 changed files with 16359 additions and 0 deletions
@@ -0,0 +1,118 @@
import SnapKit
import UIKit
/// 工作台沿用紧凑订单卡;当前任务只改变按钮标题及右上角状态。
final class DroneDockCompactOrderCell: UICollectionViewCell {
/// 返回该订单的拍摄或当前任务入口。
var onShootingTap: (() -> Void)?
/// 返回该订单原素材入口。
var onMaterialsTap: (() -> Void)?
private let customerLabel = DroneDockStyle.label(size: 16, weight: .bold)
private let statusLabel = DroneDockStatusLabel()
private let packageLabel = DroneDockStyle.label(size: 13, color: UIColor(hex: 0x666E7C))
private let countsLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let actionButton = UIButton(type: .system)
private let materialButton = UIButton(type: .system)
private let footer = UIView()
/// 创建紧凑卡片及可选素材栏。
override init(frame: CGRect) {
super.init(frame: frame)
DroneDockStyle.applyCard(to: contentView)
setupUI()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 应用数据,不展示具体点位或航线,也不在卡片自行扣次。
func apply(order: DroneShootingOrder) {
customerLabel.text = order.customerName
statusLabel.apply(title: order.statusTitle, tone: order.statusTone)
packageLabel.text = order.packageSummary
countsLabel.text = "已拍摄 \(order.successfulShootingCount)/\(order.totalShootingCount) 次 · 剩余 \(order.remainingShootingCount) 次"
actionButton.setTitle(order.primaryAction.title, for: .normal)
actionButton.isEnabled = order.primaryActionEnabled
actionButton.accessibilityIdentifier = "drone.home.\(order.id).primary"
footer.isHidden = !order.hasMaterials
var configuration = UIButton.Configuration.plain()
configuration.image = UIImage(systemName: order.materialState.systemImageName)
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 15)
configuration.imagePadding = 6
configuration.title = order.materialState.title
configuration.baseForegroundColor = DroneDockStyle.color(for: order.materialState.tone)
configuration.contentInsets = .zero
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var attributes = attributes
attributes.font = .systemFont(ofSize: 11)
return attributes
}
materialButton.configuration = configuration
materialButton.accessibilityLabel = "查看素材,\(order.materialState.title)"
accessibilityIdentifier = "drone.home.\(order.id)"
}
override func prepareForReuse() {
super.prepareForReuse()
onShootingTap = nil
onMaterialsTap = nil
}
private func setupUI() {
customerLabel.adjustsFontSizeToFitWidth = true
customerLabel.minimumScaleFactor = 0.75
customerLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
let titleRow = UIStackView(arrangedSubviews: [customerLabel, statusLabel])
titleRow.alignment = .center
titleRow.spacing = 8
let labels = UIStackView(arrangedSubviews: [packageLabel, countsLabel])
labels.axis = .vertical
labels.spacing = 9
packageLabel.adjustsFontSizeToFitWidth = true
packageLabel.minimumScaleFactor = 0.8
labels.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
actionButton.backgroundColor = DroneDockStyle.primary
actionButton.setTitleColor(.white, for: .normal)
actionButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium)
actionButton.titleLabel?.adjustsFontSizeToFitWidth = true
actionButton.titleLabel?.minimumScaleFactor = 0.8
actionButton.layer.cornerRadius = 8
actionButton.addTarget(self, action: #selector(shootingTapped), for: .touchUpInside)
actionButton.snp.makeConstraints { make in make.width.equalTo(106); make.height.equalTo(42) }
let body = UIStackView(arrangedSubviews: [labels, actionButton])
body.spacing = 10
body.alignment = .center
let divider = UIView()
divider.backgroundColor = DroneDockStyle.border
footer.addSubview(divider)
footer.addSubview(materialButton)
materialButton.contentHorizontalAlignment = .leading
materialButton.addTarget(self, action: #selector(materialsTapped), for: .touchUpInside)
let viewButton = UIButton(type: .system)
viewButton.setTitle("查看素材 ›", for: .normal)
viewButton.titleLabel?.font = .systemFont(ofSize: 11)
viewButton.tintColor = DroneDockStyle.primary
viewButton.addTarget(self, action: #selector(materialsTapped), for: .touchUpInside)
footer.addSubview(viewButton)
divider.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview(); make.height.equalTo(0.5) }
materialButton.snp.makeConstraints { make in
make.leading.equalToSuperview()
make.bottom.equalToSuperview().priority(999)
make.top.equalTo(divider.snp.bottom).offset(7)
make.height.equalTo(26)
make.trailing.lessThanOrEqualTo(viewButton.snp.leading).offset(-8)
}
viewButton.snp.makeConstraints { make in make.centerY.equalTo(materialButton); make.trailing.equalToSuperview() }
let stack = UIStackView(arrangedSubviews: [titleRow, body, footer])
stack.axis = .vertical
stack.spacing = 12
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.edges.equalToSuperview().inset(16) }
}
@objc private func shootingTapped() { onShootingTap?() }
@objc private func materialsTapped() { onMaterialsTap?() }
}
@@ -0,0 +1,187 @@
import SnapKit
import UIKit
/// 设备遥测卡:只展示设备状态,横向浏览不会选择执行拍摄的无人机。
final class DroneDockDeviceCardView: UIView {
private let nameLabel = DroneDockStyle.label(size: 15, weight: .semibold)
private let statusLabel = DroneDockStatusLabel()
private let batteryView = DroneDockBatteryView()
private let signalValue = DroneDockStyle.label(size: 19, weight: .semibold)
private let satelliteValue = DroneDockStyle.label(size: 19, weight: .semibold)
private let temperatureValue = DroneDockStyle.label(size: 22, weight: .semibold)
private let windValue = DroneDockStyle.label(size: 22, weight: .semibold)
private let rainValue = DroneDockStyle.label(size: 22, weight: .semibold)
/// 创建六项遥测布局。
override init(frame: CGRect) {
super.init(frame: frame)
DroneDockStyle.applyCard(to: self)
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.045
layer.shadowRadius = 8
layer.shadowOffset = CGSize(width: 0, height: 3)
setupUI()
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 未知读数由模型提供破折号,不以零代替未知。
func apply(device: DroneDockDevice) {
nameLabel.text = device.name
statusLabel.apply(title: device.state.title, tone: device.state.tone)
batteryView.apply(telemetry: device.telemetry)
signalValue.text = device.telemetry.signalText
satelliteValue.text = device.telemetry.satelliteText
temperatureValue.text = device.telemetry.temperatureText
windValue.text = device.telemetry.windText
rainValue.text = device.telemetry.rainText
accessibilityIdentifier = "drone.device.\(device.id)"
accessibilityLabel = "\(device.name),\(device.state.title)"
}
private func setupUI() {
[nameLabel, statusLabel, batteryView].forEach(addSubview)
nameLabel.snp.makeConstraints { make in
make.top.leading.equalToSuperview().inset(16)
make.trailing.lessThanOrEqualTo(statusLabel.snp.leading).offset(-8)
}
statusLabel.snp.makeConstraints { make in
make.centerY.equalTo(nameLabel)
make.trailing.equalToSuperview().inset(16)
}
batteryView.snp.makeConstraints { make in
make.leading.equalToSuperview().inset(20)
make.top.equalTo(nameLabel.snp.bottom).offset(16)
make.size.equalTo(102)
}
let signal = telemetryRow(symbol: "antenna.radiowaves.left.and.right", title: "信号状态", value: signalValue)
let satellites = telemetryRow(symbol: "sparkles", title: "搜星状态", value: satelliteValue)
let radioStack = UIStackView(arrangedSubviews: [signal, satellites])
radioStack.axis = .vertical
radioStack.distribution = .fillEqually
radioStack.spacing = 12
addSubview(radioStack)
radioStack.snp.makeConstraints { make in
make.leading.equalTo(batteryView.snp.trailing).offset(20)
make.trailing.equalToSuperview().inset(16)
make.centerY.equalTo(batteryView)
make.height.equalTo(92)
}
let divider = UIView()
divider.backgroundColor = DroneDockStyle.border
addSubview(divider)
divider.snp.makeConstraints { make in
make.top.equalTo(batteryView.snp.bottom).offset(15)
make.leading.trailing.equalToSuperview().inset(16)
make.height.equalTo(0.5)
}
let metrics = UIStackView(arrangedSubviews: [
metric(value: temperatureValue, symbol: "thermometer.medium", title: "环境温度"),
metric(value: windValue, symbol: "wind", title: "风速"),
metric(value: rainValue, symbol: "cloud", title: "雨量")
])
metrics.axis = .horizontal
metrics.distribution = .fillEqually
addSubview(metrics)
metrics.snp.makeConstraints { make in
make.top.equalTo(divider.snp.bottom).offset(13)
make.leading.trailing.equalToSuperview().inset(12)
make.bottom.equalToSuperview().inset(14)
}
}
private func telemetryRow(symbol: String, title: String, value: UILabel) -> UIView {
let icon = UIImageView(image: UIImage(systemName: symbol))
icon.tintColor = DroneDockStyle.secondary
icon.contentMode = .scaleAspectFit
let label = DroneDockStyle.label(title, size: 11, color: DroneDockStyle.secondary)
value.adjustsFontSizeToFitWidth = true
value.minimumScaleFactor = 0.7
value.textAlignment = .right
value.setContentHuggingPriority(.required, for: .horizontal)
let row = UIStackView(arrangedSubviews: [icon, label, value])
row.spacing = 5
row.alignment = .center
icon.snp.makeConstraints { make in make.width.equalTo(16); make.height.equalTo(16) }
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return row
}
private func metric(value: UILabel, symbol: String, title: String) -> UIView {
value.textAlignment = .center
value.adjustsFontSizeToFitWidth = true
value.minimumScaleFactor = 0.6
let icon = UIImageView(image: UIImage(systemName: symbol))
icon.tintColor = DroneDockStyle.secondary
icon.contentMode = .scaleAspectFit
icon.snp.makeConstraints { make in make.size.equalTo(13) }
let caption = UIStackView(arrangedSubviews: [icon, DroneDockStyle.label(title, size: 11, color: DroneDockStyle.secondary)])
caption.spacing = 4
caption.alignment = .center
let column = UIStackView(arrangedSubviews: [value, caption])
column.axis = .vertical
column.alignment = .center
column.spacing = 5
return column
}
}
/// 环形电量组件,未知电量只显示轨道和占位读数。
private final class DroneDockBatteryView: UIView {
private let track = CAShapeLayer()
private let progress = CAShapeLayer()
private let valueLabel = DroneDockStyle.label(size: 28, weight: .semibold)
override init(frame: CGRect) {
super.init(frame: frame)
for layer in [track, progress] {
layer.fillColor = UIColor.clear.cgColor
layer.lineWidth = 7
self.layer.addSublayer(layer)
}
track.strokeColor = DroneDockStyle.border.cgColor
progress.strokeColor = DroneDockStyle.primary.cgColor
progress.lineCap = .round
let caption = DroneDockStyle.label("电池电量", size: 11, color: DroneDockStyle.secondary)
let stack = UIStackView(arrangedSubviews: [valueLabel, caption])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 1
addSubview(stack)
stack.snp.makeConstraints { make in make.center.equalToSuperview() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func layoutSubviews() {
super.layoutSubviews()
let path = UIBezierPath(arcCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: min(bounds.width, bounds.height) / 2 - 5,
startAngle: -.pi / 2, endAngle: .pi * 1.5, clockwise: true).cgPath
track.path = path
progress.path = path
}
func apply(telemetry: DroneDockTelemetry) {
valueLabel.text = telemetry.batteryText
progress.strokeEnd = telemetry.batteryProgress ?? 0
accessibilityLabel = "电池电量 \(telemetry.batteryText)"
isAccessibilityElement = true
}
}
/// 无人机卡片的集合视图容器。
final class DroneDockDeviceCell: UICollectionViewCell {
let cardView = DroneDockDeviceCardView()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(cardView)
cardView.snp.makeConstraints { make in make.edges.equalToSuperview() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
@@ -0,0 +1,27 @@
import UIKit
#if DEBUG
/// 独立的本地预览入口,不伪造登录、权限或真实业务数据。
@MainActor
enum DroneDockPreview {
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
static func navigationController(arguments: [String]) -> UINavigationController? {
guard arguments.contains("--dock-ui-preview") || arguments.contains("--dock-ui-orders-preview") else { return nil }
let store = DroneDockDemoStore()
if let argument = arguments.first(where: { $0.hasPrefix("--dock-ui-scenario=") }),
let scenario = DroneDockDemoScenario(rawValue: String(argument.dropFirst("--dock-ui-scenario=".count))) {
store.applyScenario(scenario)
}
let workbench = DroneDockWorkbenchViewController(viewModel: DroneDockWorkbenchViewModel(store: store))
let navigation = UINavigationController(rootViewController: workbench)
if arguments.contains("--dock-ui-orders-preview") {
let filterArgument = arguments.first { $0.hasPrefix("--dock-ui-filter=") }
let filter = filterArgument.flatMap { DroneShootingOrderFilter(rawValue: String($0.dropFirst("--dock-ui-filter=".count))) } ?? .all
let orders = DroneShootingOrdersViewController(viewModel: DroneShootingOrdersViewModel(store: store, initialFilter: filter))
orders.delegate = workbench
navigation.setViewControllers([workbench, orders], animated: false)
}
return navigation
}
}
#endif
@@ -0,0 +1,73 @@
import SnapKit
import UIKit
/// 机巢新版界面的局部样式,不改变其他业务页面的主题。
enum DroneDockStyle {
static let primary = UIColor(hex: 0x3164FF)
static let background = UIColor(hex: 0xF5F6FA)
static let text = UIColor(hex: 0x172033)
static let secondary = UIColor(hex: 0x8992A3)
static let border = UIColor(hex: 0xE8ECF3)
static let success = UIColor(hex: 0x169B6B)
static let warning = UIColor(hex: 0xD68A28)
/// 将模型的语义色映射为界面颜色。
static func color(for tone: DroneDockStatusTone) -> UIColor {
switch tone {
case .blue: primary
case .green: success
case .orange: warning
case .red: UIColor(hex: 0xD46B62)
case .gray: secondary
}
}
/// 白色圆角卡片的统一装饰。
static func applyCard(to view: UIView) {
view.backgroundColor = .white
view.layer.cornerRadius = 16
view.layer.cornerCurve = .continuous
}
/// 创建常用文字,显式传入字重及颜色。
static func label(_ text: String? = nil, size: CGFloat = 14, weight: UIFont.Weight = .regular,
color: UIColor = DroneDockStyle.text) -> UILabel {
let label = UILabel()
label.text = text
label.font = .systemFont(ofSize: size, weight: weight)
label.textColor = color
return label
}
}
/// 有内边距的状态标签,在两种订单卡和设备卡中保持一致。
final class DroneDockStatusLabel: UILabel {
private let padding = UIEdgeInsets(top: 4, left: 7, bottom: 4, right: 7)
/// 创建自适应文字宽度的浅色标签。
override init(frame: CGRect) {
super.init(frame: frame)
font = .systemFont(ofSize: 11, weight: .medium)
layer.cornerRadius = 6
clipsToBounds = true
setContentHuggingPriority(.required, for: .horizontal)
setContentCompressionResistancePriority(.required, for: .horizontal)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 应用状态文字及对应语义颜色。
func apply(title: String, tone: DroneDockStatusTone) {
text = title
textColor = DroneDockStyle.color(for: tone)
backgroundColor = textColor.withAlphaComponent(0.09)
}
override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + padding.left + padding.right, height: size.height + padding.top + padding.bottom)
}
override func drawText(in rect: CGRect) { super.drawText(in: rect.inset(by: padding)) }
}
@@ -0,0 +1,385 @@
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:
title = order.primaryAction.title
detail = order.activeTask.map { "当前任务:\($0.phase.title)" } ?? "剩余 \(order.remainingShootingCount) 次拍摄"
case .materials:
title = "查看素材"
detail = order.materialState.title
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)
}
@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)
}
}
/// 工作台标题及查看全部入口。
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) }
}
}
@@ -0,0 +1,332 @@
import SnapKit
import UIKit
/// 机巢工作台与拍摄订单共用的订单卡片,展示次数、任务状态与素材入口。
final class DroneShootingOrderCardView: UIView {
/// 用户点击开始、继续或查看当前任务时触发。
var onShootingTap: (() -> Void)?
/// 用户点击素材入口时触发。
var onMaterialsTap: (() -> Void)?
/// 用户点击交付入口时触发;具体交付业务由外部协调。
var onDeliveryTap: (() -> Void)?
private let contentStack = UIStackView()
private let customerLabel = UILabel()
private let statusContainer = UIView()
private let statusLabel = UILabel()
private let metadataLabel = UILabel()
private let packageLabel = UILabel()
private let countsLabel = UILabel()
private let remainingLabel = UILabel()
private let progressView = UIProgressView(progressViewStyle: .bar)
private let materialRow = UIStackView()
private let materialControl = UIControl()
private let materialTitleLabel = UILabel()
private let materialStateLabel = UILabel()
private let materialChevron = UIImageView(image: UIImage(systemName: "chevron.right"))
private let deliveryControl = UIControl()
private let deliveryTitleLabel = UILabel()
private let deliveryStateLabel = UILabel()
private let deliveryChevron = UIImageView(image: UIImage(systemName: "chevron.right"))
private let actionStack = UIStackView()
private let secondaryButton = UIButton(type: .system)
private let primaryButton = UIButton(type: .system)
private var displayedOrder: DroneShootingOrder?
/// 创建可以按内容自行撑高的白色圆角订单卡。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 应用完整订单快照;卡片不推断或修改订单及任务状态。
func apply(order: DroneShootingOrder) {
displayedOrder = order
customerLabel.text = order.customerName
metadataLabel.text = "\(order.orderNumber) · \(order.createdAtText)"
packageLabel.text = order.packageSummary
statusLabel.text = order.statusTitle
countsLabel.attributedText = countsText(order: order)
remainingLabel.attributedText = remainingText(order: order)
progressView.setProgress(Float(order.progress), animated: false)
progressView.accessibilityLabel = "已拍摄 \(order.successfulShootingCount) 次,共 \(order.totalShootingCount) 次"
applyStatusAppearance(order: order)
applyMaterialSummary(order: order)
applyActions(order: order)
accessibilityIdentifier = "drone.order.\(order.id)"
}
private func setupUI() {
DroneDockStyle.applyCard(to: self)
contentStack.axis = .vertical
contentStack.spacing = 15
addSubview(contentStack)
contentStack.snp.makeConstraints { make in
make.edges.equalToSuperview().inset(16)
}
customerLabel.font = .systemFont(ofSize: 18, weight: .bold)
customerLabel.textColor = UIColor(hex: 0x172033)
customerLabel.adjustsFontSizeToFitWidth = true
customerLabel.minimumScaleFactor = 0.85
customerLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
customerLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
customerLabel.accessibilityTraits = .header
statusLabel.font = .systemFont(ofSize: 11, weight: .medium)
statusLabel.setContentHuggingPriority(.required, for: .horizontal)
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
statusContainer.layer.cornerRadius = 6
statusContainer.addSubview(statusLabel)
statusLabel.snp.makeConstraints { make in
make.edges.equalToSuperview().inset(UIEdgeInsets(top: 5, left: 8, bottom: 5, right: 8))
}
let header = UIStackView(arrangedSubviews: [customerLabel, statusContainer])
header.axis = .horizontal
header.alignment = .center
header.spacing = 8
contentStack.addArrangedSubview(header)
metadataLabel.font = .systemFont(ofSize: 11)
metadataLabel.textColor = UIColor(hex: 0x8992A3)
metadataLabel.numberOfLines = 2
contentStack.addArrangedSubview(metadataLabel)
contentStack.setCustomSpacing(17, after: metadataLabel)
packageLabel.font = .systemFont(ofSize: 14)
packageLabel.textColor = UIColor(hex: 0x474D59)
packageLabel.numberOfLines = 0
contentStack.addArrangedSubview(packageLabel)
countsLabel.font = .systemFont(ofSize: 12)
remainingLabel.font = .systemFont(ofSize: 12)
remainingLabel.setContentHuggingPriority(.required, for: .horizontal)
let countsRow = UIStackView(arrangedSubviews: [countsLabel, remainingLabel])
countsRow.axis = .horizontal
countsRow.distribution = .equalSpacing
countsRow.spacing = 8
let progressStack = UIStackView(arrangedSubviews: [countsRow, progressView])
progressStack.axis = .vertical
progressStack.spacing = 9
progressView.tintColor = DroneDockStyle.primary
progressView.trackTintColor = UIColor(hex: 0xE9EBF2)
progressView.layer.cornerRadius = 2
progressView.clipsToBounds = true
progressView.snp.makeConstraints { make in make.height.equalTo(4) }
contentStack.addArrangedSubview(progressStack)
setupSummaryControl(
materialControl, titleLabel: materialTitleLabel,
stateLabel: materialStateLabel, chevron: materialChevron
)
setupSummaryControl(
deliveryControl, titleLabel: deliveryTitleLabel,
stateLabel: deliveryStateLabel, chevron: deliveryChevron
)
materialControl.addTarget(self, action: #selector(materialsTapped), for: .touchUpInside)
deliveryControl.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside)
materialRow.axis = .horizontal
materialRow.spacing = 12
materialRow.distribution = .fillEqually
materialRow.addArrangedSubview(materialControl)
materialRow.addArrangedSubview(deliveryControl)
materialRow.snp.makeConstraints { make in
// 隐藏摘要行时,允许 UIStackView 的零高度约束覆盖该展示高度。
make.height.equalTo(40).priority(999)
}
contentStack.addArrangedSubview(materialRow)
actionStack.axis = .horizontal
actionStack.spacing = 10
actionStack.distribution = .fillEqually
actionStack.addArrangedSubview(secondaryButton)
actionStack.addArrangedSubview(primaryButton)
[secondaryButton, primaryButton].forEach { button in
button.layer.cornerRadius = 10
button.layer.cornerCurve = .continuous
button.titleLabel?.font = .systemFont(ofSize: 14, weight: .semibold)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.minimumScaleFactor = 0.85
button.snp.makeConstraints { make in make.height.equalTo(44) }
}
secondaryButton.backgroundColor = UIColor(hex: 0xECF3FF)
secondaryButton.setTitleColor(DroneDockStyle.primary, for: .normal)
primaryButton.backgroundColor = DroneDockStyle.primary
primaryButton.setTitleColor(.white, for: .normal)
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
contentStack.addArrangedSubview(actionStack)
}
private func setupSummaryControl(
_ control: UIControl,
titleLabel: UILabel,
stateLabel: UILabel,
chevron: UIImageView
) {
titleLabel.font = .systemFont(ofSize: 13, weight: .semibold)
titleLabel.textColor = UIColor(hex: 0x232936)
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
stateLabel.font = .systemFont(ofSize: 11)
stateLabel.textColor = UIColor(hex: 0x8992A3)
stateLabel.numberOfLines = 1
chevron.tintColor = UIColor(hex: 0x5A79B5)
chevron.contentMode = .scaleAspectFit
control.addSubview(titleLabel)
control.addSubview(stateLabel)
control.addSubview(chevron)
titleLabel.snp.makeConstraints { make in
make.top.leading.equalToSuperview()
make.trailing.lessThanOrEqualTo(chevron.snp.leading).offset(-5)
}
chevron.snp.makeConstraints { make in
make.leading.equalTo(titleLabel.snp.trailing).offset(6)
make.centerY.equalTo(titleLabel)
make.width.equalTo(6)
make.height.equalTo(10)
make.trailing.lessThanOrEqualToSuperview()
}
stateLabel.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview()
make.top.equalTo(titleLabel.snp.bottom).offset(6)
}
control.isAccessibilityElement = true
control.accessibilityTraits = .button
}
private func applyStatusAppearance(order: DroneShootingOrder) {
let foreground: UIColor
let background: UIColor
switch order.statusTone {
case .blue:
foreground = DroneDockStyle.primary
background = UIColor(hex: 0xECF3FF)
case .green:
foreground = UIColor(hex: 0x169B6B)
background = UIColor(hex: 0xEDF8F3)
case .gray:
foreground = UIColor(hex: 0x8E97A6)
background = UIColor(hex: 0xF0F2F7)
case .orange:
foreground = UIColor(hex: 0xD68A28)
background = UIColor(hex: 0xFFF6E8)
case .red:
foreground = UIColor(hex: 0xCA5E57)
background = UIColor(hex: 0xFFF0ED)
}
statusLabel.textColor = foreground
statusContainer.backgroundColor = background
}
private func applyMaterialSummary(order: DroneShootingOrder) {
materialRow.isHidden = !order.hasMaterials
let isCompleted = order.fulfillmentState == .completed && order.activeTask == nil
materialTitleLabel.text = isCompleted ? "拍摄素材" : "查看素材"
materialChevron.isHidden = isCompleted
materialStateLabel.text = order.materialState.title
materialStateLabel.textColor = order.materialState == .failed
? UIColor(hex: 0xC26962) : UIColor(hex: 0x8992A3)
materialControl.accessibilityLabel = "\(materialTitleLabel.text ?? "查看素材"),\(order.materialState.title)"
let showsDelivery = order.deliveredVideoCount > 0
deliveryControl.isHidden = !showsDelivery
deliveryTitleLabel.text = order.visitorConfirmationState == .confirmed ? "游客已确认" : "请游客确认"
deliveryStateLabel.text = "已交付 \(order.deliveredVideoCount) 个视频"
deliveryControl.accessibilityLabel = "\(deliveryTitleLabel.text ?? "交付成片"),\(deliveryStateLabel.text ?? "")"
}
private func applyActions(order: DroneShootingOrder) {
let isFinished = order.primaryAction == .none
secondaryButton.setTitle(isFinished ? "查看素材" : "交付成片", for: .normal)
if order.primaryAction == .none {
primaryButton.setTitle("交付成片", for: .normal)
} else {
primaryButton.setTitle(order.primaryAction.title, for: .normal)
}
secondaryButton.accessibilityIdentifier = "drone.order.\(order.id).secondary"
primaryButton.accessibilityIdentifier = "drone.order.\(order.id).primary"
}
private func countsText(order: DroneShootingOrder) -> NSAttributedString {
let text = NSMutableAttributedString(
string: "已拍摄 ", attributes: [.foregroundColor: UIColor(hex: 0x69717F)]
)
text.append(NSAttributedString(
string: "\(order.successfulShootingCount)",
attributes: [.foregroundColor: DroneDockStyle.primary, .font: UIFont.systemFont(ofSize: 12, weight: .medium)]
))
text.append(NSAttributedString(
string: " / \(order.totalShootingCount) 次", attributes: [.foregroundColor: UIColor(hex: 0x69717F)]
))
return text
}
private func remainingText(order: DroneShootingOrder) -> NSAttributedString {
let text = NSMutableAttributedString(
string: "剩余 ", attributes: [.foregroundColor: UIColor(hex: 0x69717F)]
)
text.append(NSAttributedString(
string: "\(order.remainingShootingCount)",
attributes: [.foregroundColor: DroneDockStyle.primary, .font: UIFont.systemFont(ofSize: 12, weight: .medium)]
))
text.append(NSAttributedString(string: " 次", attributes: [.foregroundColor: UIColor(hex: 0x69717F)]))
return text
}
@objc private func secondaryTapped() {
guard let displayedOrder else { return }
if displayedOrder.primaryAction == .none {
onMaterialsTap?()
} else {
onDeliveryTap?()
}
}
@objc private func primaryTapped() {
guard let displayedOrder else { return }
if displayedOrder.primaryAction == .none {
onDeliveryTap?()
} else {
onShootingTap?()
}
}
@objc private func materialsTapped() { onMaterialsTap?() }
@objc private func deliveryTapped() { onDeliveryTap?() }
}
/// Diffable 订单列表使用的自适应高度容器。
final class DroneShootingOrderCell: UICollectionViewCell {
/// UICollectionView 注册与出队标识。
static let reuseIdentifier = "DroneShootingOrderCell"
/// 供页面配置订单与语义明确的动作回调。
let cardView = DroneShootingOrderCardView()
/// 创建完全依赖卡片内容撑高的列表单元格。
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(cardView)
cardView.snp.makeConstraints { make in make.edges.equalToSuperview() }
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 清除上一订单动作,避免复用时调用旧订单。
override func prepareForReuse() {
super.prepareForReuse()
cardView.onShootingTap = nil
cardView.onMaterialsTap = nil
cardView.onDeliveryTap = nil
}
}
@@ -0,0 +1,72 @@
import SnapKit
import UIKit
/// 我的拍摄订单四个等宽筛选 Tab,使用蓝色下划线标识当前履约分类。
final class DroneShootingOrderFilterView: UIView {
/// 用户选择新的订单分类时触发。
var onFilterSelected: ((DroneShootingOrderFilter) -> Void)?
private let stackView = UIStackView()
private var buttons: [DroneShootingOrderFilter: UIButton] = [:]
private var indicators: [DroneShootingOrderFilter: UIView] = [:]
/// 创建全部、待拍摄、进行中与已完成四个筛选入口。
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 按 ViewModel 提供的分类刷新文字与辅助功能选中状态。
func apply(selectedFilter: DroneShootingOrderFilter) {
for filter in DroneShootingOrderFilter.allCases {
let isSelected = filter == selectedFilter
buttons[filter]?.setTitleColor(
isSelected ? DroneDockStyle.primary : DroneDockStyle.secondary, for: .normal
)
buttons[filter]?.titleLabel?.font = .systemFont(ofSize: 14, weight: isSelected ? .semibold : .regular)
buttons[filter]?.accessibilityTraits = isSelected ? [.button, .selected] : .button
indicators[filter]?.isHidden = !isSelected
}
}
private func setupUI() {
backgroundColor = .white
stackView.axis = .horizontal
stackView.distribution = .fillEqually
addSubview(stackView)
stackView.snp.makeConstraints { make in make.edges.equalToSuperview() }
for filter in DroneShootingOrderFilter.allCases {
let itemView = UIView()
let button = UIButton(type: .system)
let indicator = UIView()
button.setTitle(filter.title, for: .normal)
button.accessibilityIdentifier = "drone.orders.filter.\(filter.rawValue)"
button.addAction(UIAction { [weak self] _ in
self?.onFilterSelected?(filter)
}, for: .touchUpInside)
indicator.backgroundColor = DroneDockStyle.primary
indicator.layer.cornerRadius = 1.5
itemView.addSubview(button)
itemView.addSubview(indicator)
button.snp.makeConstraints { make in
make.top.leading.trailing.equalToSuperview()
make.bottom.equalToSuperview().offset(-4)
}
indicator.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.bottom.equalToSuperview()
make.width.equalTo(30)
make.height.equalTo(3)
}
stackView.addArrangedSubview(itemView)
buttons[filter] = button
indicators[filter] = indicator
}
}
}
@@ -0,0 +1,304 @@
import SnapKit
import UIKit
/// 拍摄订单页仅发出导航意图,由工作台协调器处理尚未搭建的下级页面。
@MainActor
protocol DroneShootingOrdersViewControllerDelegate: AnyObject {
/// 用户请求开始、继续、重新准备拍摄,或查看当前任务。
func shootingOrdersViewController(_ controller: DroneShootingOrdersViewController, didSelectShooting order: DroneShootingOrder)
/// 用户请求查看该订单的原素材。
func shootingOrdersViewController(_ controller: DroneShootingOrdersViewController, didSelectMaterials order: DroneShootingOrder)
/// 用户请求交付成片;当前阶段只提供外观及导航回调。
func shootingOrdersViewController(_ controller: DroneShootingOrdersViewController, didSelectDelivery order: DroneShootingOrder)
}
/// 当前用户在当前景区的拍摄订单页面;使用本地 ViewModel 展示四种履约分类。
final class DroneShootingOrdersViewController: BaseViewController {
/// 由入口页协调拍摄、素材和交付导航。
weak var delegate: (any DroneShootingOrdersViewControllerDelegate)?
private let viewModel: DroneShootingOrdersViewModel
private let descriptionLabel = UILabel()
private let filterView = DroneShootingOrderFilterView()
private let refreshControl = UIRefreshControl()
private let emptyView = DroneShootingOrdersEmptyView()
private var collectionView: UICollectionView!
private var dataSource: UICollectionViewDiffableDataSource<Int, String>?
private var ordersByID: [String: DroneShootingOrder] = [:]
/// 注入共享演示数据及初始分类;从支付成功页进入时由 ViewModel 指定待拍摄。
init(viewModel: DroneShootingOrdersViewModel) {
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()
applySnapshot(animatingDifferences: false)
}
override func setupNavigationBar() {
title = "我的拍摄订单"
}
override func setupUI() {
view.backgroundColor = DroneDockStyle.background
descriptionLabel.text = "分配给我的全部订单,含已完成订单"
descriptionLabel.font = .systemFont(ofSize: 12)
descriptionLabel.textColor = UIColor(hex: 0x8992A3)
descriptionLabel.textAlignment = .center
descriptionLabel.backgroundColor = .white
view.addSubview(descriptionLabel)
view.addSubview(filterView)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
collectionView.backgroundColor = .clear
collectionView.alwaysBounceVertical = true
collectionView.showsVerticalScrollIndicator = false
collectionView.accessibilityIdentifier = "drone.orders.list"
collectionView.refreshControl = refreshControl
collectionView.register(DroneShootingOrderCell.self, forCellWithReuseIdentifier: DroneShootingOrderCell.reuseIdentifier)
collectionView.register(
DroneShootingOrdersHeadingView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: DroneShootingOrdersHeadingView.reuseIdentifier
)
collectionView.register(
DroneShootingOrdersFooterView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
withReuseIdentifier: DroneShootingOrdersFooterView.reuseIdentifier
)
view.addSubview(collectionView)
configureDataSource()
}
override func setupConstraints() {
descriptionLabel.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.leading.trailing.equalToSuperview()
make.height.equalTo(32)
}
filterView.snp.makeConstraints { make in
make.top.equalTo(descriptionLabel.snp.bottom)
make.leading.trailing.equalToSuperview()
make.height.equalTo(50)
}
collectionView.snp.makeConstraints { make in
make.top.equalTo(filterView.snp.bottom)
make.leading.trailing.bottom.equalToSuperview()
}
}
override func bindActions() {
filterView.onFilterSelected = { [weak self] filter in
guard let self, filter != self.viewModel.selectedFilter else { return }
self.viewModel.selectFilter(filter)
self.applySnapshot(animatingDifferences: true)
self.collectionView.setContentOffset(.zero, animated: false)
}
refreshControl.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged)
}
private func makeLayout() -> UICollectionViewLayout {
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1), heightDimension: .estimated(280)
))
let group = NSCollectionLayoutGroup.vertical(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(280)),
subitems: [item]
)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 8, trailing: 16)
section.interGroupSpacing = 12
section.boundarySupplementaryItems = [
NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(54)),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top
),
NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(48)),
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom
)
]
return UICollectionViewCompositionalLayout(section: section)
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Int, String>(collectionView: collectionView) { [weak self] list, indexPath, orderID in
guard let self,
let order = self.ordersByID[orderID],
let cell = list.dequeueReusableCell(withReuseIdentifier: DroneShootingOrderCell.reuseIdentifier, for: indexPath) as? DroneShootingOrderCell else {
return nil
}
cell.cardView.apply(order: order)
cell.cardView.onShootingTap = { [weak self] in
guard let self else { return }
self.delegate?.shootingOrdersViewController(self, didSelectShooting: order)
}
cell.cardView.onMaterialsTap = { [weak self] in
guard let self else { return }
self.delegate?.shootingOrdersViewController(self, didSelectMaterials: order)
}
cell.cardView.onDeliveryTap = { [weak self] in
guard let self else { return }
self.delegate?.shootingOrdersViewController(self, didSelectDelivery: order)
}
return cell
}
dataSource?.supplementaryViewProvider = { [weak self] list, kind, indexPath in
guard let self else { return nil }
if kind == UICollectionView.elementKindSectionHeader {
let header = list.dequeueReusableSupplementaryView(
ofKind: kind, withReuseIdentifier: DroneShootingOrdersHeadingView.reuseIdentifier, for: indexPath
) as? DroneShootingOrdersHeadingView
header?.apply(title: self.viewModel.selectedFilter.listTitle, count: self.viewModel.orders.count)
return header
}
let footer = list.dequeueReusableSupplementaryView(
ofKind: kind, withReuseIdentifier: DroneShootingOrdersFooterView.reuseIdentifier, for: indexPath
) as? DroneShootingOrdersFooterView
footer?.apply(count: self.viewModel.orders.count)
return footer
}
}
private func applySnapshot(animatingDifferences: Bool) {
guard isViewLoaded, let dataSource else { return }
let orders = viewModel.orders
ordersByID = Dictionary(uniqueKeysWithValues: orders.map { ($0.id, $0) })
filterView.apply(selectedFilter: viewModel.selectedFilter)
emptyView.apply(filter: viewModel.selectedFilter)
collectionView.backgroundView = orders.isEmpty ? emptyView : nil
let existingIDs = Set(dataSource.snapshot().itemIdentifiers)
var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
if !orders.isEmpty {
snapshot.appendSections([0])
snapshot.appendItems(orders.map(\.id))
snapshot.reconfigureItems(orders.map(\.id).filter { existingIDs.contains($0) })
}
dataSource.apply(snapshot, animatingDifferences: animatingDifferences) { [weak self] in
self?.updateVisibleSupplementaryViews()
}
}
private func updateVisibleSupplementaryViews() {
for case let header as DroneShootingOrdersHeadingView in collectionView.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionHeader) {
header.apply(title: viewModel.selectedFilter.listTitle, count: viewModel.orders.count)
}
for case let footer as DroneShootingOrdersFooterView in collectionView.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionFooter) {
footer.apply(count: viewModel.orders.count)
}
}
@objc private func refreshTriggered() {
viewModel.refresh()
applySnapshot(animatingDifferences: true)
refreshControl.endRefreshing()
}
}
/// 列表上方的订单分类标题与数量。
private final class DroneShootingOrdersHeadingView: UICollectionReusableView {
/// Supplementary view 复用标识。
static let reuseIdentifier = "DroneShootingOrdersHeadingView"
private let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.font = .systemFont(ofSize: 16, weight: .semibold)
titleLabel.accessibilityTraits = .header
addSubview(titleLabel)
titleLabel.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) {
let text = NSMutableAttributedString(string: title, attributes: [.foregroundColor: UIColor(hex: 0x172033)])
text.append(NSAttributedString(
string: " \(count)",
attributes: [.foregroundColor: UIColor(hex: 0x8992A3), .font: UIFont.systemFont(ofSize: 14)]
))
titleLabel.attributedText = text
}
}
/// 演示订单全部展示完成后的底部文案,不伪装接口分页。
private final class DroneShootingOrdersFooterView: UICollectionReusableView {
/// Supplementary view 复用标识。
static let reuseIdentifier = "DroneShootingOrdersFooterView"
private let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
label.font = .systemFont(ofSize: 12)
label.textColor = UIColor(hex: 0xA0A6B2)
label.textAlignment = .center
addSubview(label)
label.snp.makeConstraints { make in make.edges.equalToSuperview() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 显示当前本地快照的订单数量。
func apply(count: Int) { label.text = "已显示全部 \(count) 个订单" }
}
/// 没有订单时保留四个筛选入口,并给出当前分类的空状态。
private final class DroneShootingOrdersEmptyView: UIView {
private let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
let icon = UIImageView(image: UIImage(systemName: "doc.text.magnifyingglass"))
icon.tintColor = UIColor(hex: 0xBBC4D4)
icon.contentMode = .scaleAspectFit
titleLabel.font = .systemFont(ofSize: 16, weight: .medium)
titleLabel.textColor = UIColor(hex: 0x697487)
titleLabel.textAlignment = .center
let subtitle = UILabel()
subtitle.text = "当前景区暂无分配给你的此类订单"
subtitle.font = .systemFont(ofSize: 13)
subtitle.textColor = UIColor(hex: 0xA0A8B7)
subtitle.textAlignment = .center
subtitle.numberOfLines = 0
addSubview(icon)
addSubview(titleLabel)
addSubview(subtitle)
icon.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.centerY.equalToSuperview().offset(-65)
make.size.equalTo(54)
}
titleLabel.snp.makeConstraints { make in
make.top.equalTo(icon.snp.bottom).offset(20)
make.leading.trailing.equalToSuperview().inset(24)
}
subtitle.snp.makeConstraints { make in
make.top.equalTo(titleLabel.snp.bottom).offset(10)
make.leading.trailing.equalToSuperview().inset(24)
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 根据已选分类生成空列表标题。
func apply(filter: DroneShootingOrderFilter) {
titleLabel.text = filter == .all ? "暂无拍摄订单" : "暂无\(filter.title)订单"
}
}
@@ -58,8 +58,19 @@ final class AllFunctionsViewController: BaseViewController {
override func setupNavigationBar() {
title = "全部功能"
#if DEBUG
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "机巢预览", style: .plain, target: self, action: #selector(openDroneDockPreview)
)
#endif
}
#if DEBUG
@objc private func openDroneDockPreview() {
navigationController?.pushViewController(DroneDockWorkbenchViewController(), animated: true)
}
#endif
override func setupUI() {
view.backgroundColor = AppColor.pageBackground