feat(drone-dock): 接入首页真实数据并完善设备卡片

通过 airport/home 读取当前景区和门店的设备与统计,隔离失效会话回包,未知遥测显示破折号。完善状态圆点、分割线和卫星图标;订单详情等待后端测试数据。

验证:iPhone 11 上 49 项相关测试、样式调整后 9 项界面回归,以及测试样例匿名化后 20 项测试均通过。真实联调响应、日志和截图仅保留在本地。
This commit is contained in:
2026-10-27 15:05:51 +08:00
parent 7862d208ce
commit 40060cd883
15 changed files with 1739 additions and 14 deletions
@@ -0,0 +1,375 @@
import SnapKit
import UIKit
/// 正式机巢首页,仅展示 airport/home 的真实快照,不进入本地演示业务。
final class DroneDockHomeViewController: BaseViewController {
/// 与演示数据源隔离的首页状态。
let viewModel: DroneDockHomeViewModel
private var refreshTask: Task<Void, Never>?
private var isRefreshing = false
private var devicePage = 0
private let pageControl = UIPageControl()
/// 首页固定分区;设备与订单的数据结构以实际联调结果为准。
private enum Section: Int, CaseIterable { case context, devices, orders, statistics }
/// 稳定身份确保刷新使用 Diffable 更新。
private enum Item: Hashable { case context, devices, device(Int), orders, statistics }
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
/// 使用当前登录身份及选择的景区、门店构造正式首页。
convenience init() {
self.init(viewModel: DroneDockHomeViewModel(
context: Self.currentContext(),
service: DroneDockAPI(client: NetworkServices.shared.apiClient),
currentContext: { Self.currentContext() }
))
}
/// 注入可测试的数据源,不加载演示数据。
init(viewModel: DroneDockHomeViewModel) {
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 { refreshTask?.cancel() }
override func setupNavigationBar() {
title = "机巢工作台"
let button = UIBarButtonItem(title: "收款码", image: UIImage(systemName: "qrcode"),
target: self, action: #selector(receiptTapped))
button.accessibilityIdentifier = "drone.home.receipt"
navigationItem.rightBarButtonItem = button
navigationItem.backButtonDisplayMode = .minimal
}
override func setupUI() {
view.backgroundColor = DroneDockStyle.background
collectionView.backgroundColor = .clear
collectionView.alwaysBounceVertical = true
collectionView.accessibilityIdentifier = "drone.home.remote.list"
collectionView.register(DroneDockHomeContentCell.self, forCellWithReuseIdentifier: "content")
collectionView.register(DroneDockDeviceCell.self, forCellWithReuseIdentifier: "device")
collectionView.register(DroneDockHomeHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: "header")
collectionView.register(DroneDockHomePageFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
withReuseIdentifier: "pages")
pageControl.currentPageIndicatorTintColor = DroneDockStyle.primary
pageControl.pageIndicatorTintColor = DroneDockStyle.border
pageControl.isUserInteractionEnabled = false
pageControl.accessibilityIdentifier = "drone.home.devicePages"
let refresh = UIRefreshControl()
refresh.tintColor = DroneDockStyle.primary
refresh.addTarget(self, action: #selector(refreshTriggered), 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)
refreshHome()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
refreshTask?.cancel()
isRefreshing = false
viewModel.invalidate()
}
private func refreshHome() {
refreshTask?.cancel()
isRefreshing = true
refreshTask = Task { @MainActor [weak self] in
guard let self else { return }
self.applySnapshot(animated: false)
await self.viewModel.refresh()
guard !Task.isCancelled else { return }
self.isRefreshing = false
self.collectionView.refreshControl?.endRefreshing()
self.applySnapshot(animated: true) { [weak self] in
#if DEBUG
Task { @MainActor [weak self] in await self?.captureHomeIfRequested() }
#endif
}
}
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] collection, path, item in
guard let self else { return nil }
if case .device(let id) = item {
let cell = collection.dequeueReusableCell(withReuseIdentifier: "device", for: path) as! DroneDockDeviceCell
if let airport = self.viewModel.response?.airports.first(where: { $0.id == id }) {
cell.cardView.apply(airport: airport)
}
return cell
}
let cell = collection.dequeueReusableCell(withReuseIdentifier: "content", for: path) as! DroneDockHomeContentCell
switch item {
case .context:
let context = self.viewModel.context
let title = [context.scenicName, context.photographerName].filter { !$0.isEmpty }.joined(separator: " · ")
cell.applyContext(title.isEmpty ? "机巢工作台" : title)
case .statistics:
cell.applyStatistics(self.viewModel.response?.today)
case .devices, .orders:
self.applyDataState(to: cell, isDevice: item == .devices)
case .device: break
}
return cell
}
dataSource.supplementaryViewProvider = { [weak self] collection, kind, path in
guard let self else { return nil }
if kind == UICollectionView.elementKindSectionFooter {
let footer = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "pages", for: path) as! DroneDockHomePageFooter
footer.install(self.pageControl)
return footer
}
let header = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: path) as! DroneDockHomeHeader
let isOrders = Section(rawValue: path.section) == .orders
header.apply(title: isOrders ? "我的拍摄订单" : "今日统计", showsAction: isOrders)
header.onViewAll = { [weak self] in self?.showUnavailable("拍摄订单") }
return header
}
}
private func applyDataState(to cell: DroneDockHomeContentCell, isDevice: Bool) {
if isRefreshing, viewModel.response == nil {
cell.applyMessage(symbol: "arrow.triangle.2.circlepath", title: "正在加载", detail: "正在获取最新数据")
return
}
if let error = viewModel.errorMessage {
cell.applyMessage(symbol: "wifi.exclamationmark", title: "首页加载失败", detail: error + ",请下拉重试")
return
}
guard let response = viewModel.response else {
cell.applyMessage(symbol: "arrow.triangle.2.circlepath", title: "正在加载", detail: "正在获取最新数据")
return
}
let recordCount = isDevice ? response.airports.count : response.orders.count
if recordCount == 0 {
cell.applyMessage(symbol: isDevice ? "airplane" : "doc.text",
title: isDevice ? "暂无无人机" : "暂无待拍摄订单",
detail: isDevice ? "当前景区暂无设备数据" : "当前景区暂无拍摄订单数据")
} else {
// 订单仍等待真实非空样例,不影响已接入的设备卡片。
cell.applyMessage(symbol: "exclamationmark.circle", title: "订单信息暂不可用",
detail: "已获取 \(recordCount) 条数据,暂时无法展示详情")
}
}
private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) {
guard dataSource != nil else { return }
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections(Section.allCases)
snapshot.appendItems([.context], toSection: .context)
let airports = viewModel.response?.airports ?? []
snapshot.appendItems(airports.isEmpty ? [.devices] : airports.map { .device($0.id) }, toSection: .devices)
snapshot.appendItems([.orders], toSection: .orders)
snapshot.appendItems([.statistics], toSection: .statistics)
let old = Set(dataSource.snapshot().itemIdentifiers)
let previousDeviceCount = old.filter { if case .device = $0 { return true }; return false }.count
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { old.contains($0) })
devicePage = min(devicePage, max(0, airports.count - 1))
pageControl.numberOfPages = airports.count
pageControl.currentPage = devicePage
if previousDeviceCount != airports.count {
collectionView.setCollectionViewLayout(makeLayout(), animated: false)
}
dataSource.apply(snapshot, animatingDifferences: animated, completion: completion)
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, environment in
guard let section = Section(rawValue: index) else { return nil }
let deviceCount = self?.viewModel.response?.airports.count ?? 0
let hasDevices = section == .devices && deviceCount > 0
let multipleDevices = section == .devices && deviceCount > 1
let height: NSCollectionLayoutDimension = hasDevices ? .absolute(248) : section == .context ? .estimated(40) : .estimated(132)
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height))
let width: NSCollectionLayoutDimension = multipleDevices ? .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)
if multipleDevices {
layout.interGroupSpacing = 12
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(deviceCount - 1, max(0, Int((offset.x / step).rounded())))
self.devicePage = page
self.pageControl.currentPage = page
}
layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(24)),
elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom)]
}
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 showUnavailable(_ feature: String) {
showAlert(title: feature, message: "该功能暂未开放")
}
@objc private func receiptTapped() { showUnavailable("套餐收款") }
@objc private func refreshTriggered() { refreshHome() }
#if DEBUG
/// 显式联调参数下只保存本应用窗口,不截取用户切换后的其他 App。
private func captureHomeIfRequested() async {
guard ProcessInfo.processInfo.arguments.contains("--dock-home-capture") else { return }
// Diffable 完成回调仍可能处于旧卡片的移除事务内,等下一轮屏幕提交后再取图。
try? await Task.sleep(nanoseconds: 400_000_000)
guard !Task.isCancelled, !isRefreshing, let window = view.window else { return }
window.layoutIfNeeded()
let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in
window.drawHierarchy(in: window.bounds, afterScreenUpdates: true)
}
do {
let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
.appendingPathComponent("AirportHomeDiagnostics", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
try image.pngData()?.write(to: directory.appendingPathComponent("airport-home-real.png"), options: .atomic)
print("[AirportHome] App window screenshot saved")
} catch { print("[AirportHome] Screenshot failed: \(error.localizedDescription)") }
}
#endif
/// 只从现有会话读取身份,不修改登录状态或当前选择。
private static func currentContext() -> DroneDockHomeContext {
let session = AppStore.shared.session
return DroneDockHomeContext(userID: session.userId, accountType: session.accountType.rawValue,
scenicID: session.currentScenicId, scenicName: session.currentScenicName,
storeID: session.currentStoreId, photographerName: session.userName, token: session.token)
}
}
/// 多设备横向轮播的页码容器。
private final class DroneDockHomePageFooter: 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 DroneDockHomeContentCell: UICollectionViewCell {
private var embeddedView: UIView?
/// 展示当前身份与景区。
func applyContext(_ text: String) {
let label = DroneDockStyle.label(text, size: 12, color: DroneDockStyle.secondary)
label.numberOfLines = 2
install(label, insets: UIEdgeInsets(top: 6, left: 0, bottom: 12, right: 0), card: false)
}
/// 展示明确空态或错误,避免将接口失败解释为没有订单。
func applyMessage(symbol: String, title: String, detail: String) {
let image = UIImageView(image: UIImage(systemName: symbol))
image.tintColor = DroneDockStyle.secondary.withAlphaComponent(0.6)
image.contentMode = .scaleAspectFit
image.snp.makeConstraints { $0.size.equalTo(28) }
let titleLabel = DroneDockStyle.label(title, size: 14, weight: .medium)
let detailLabel = DroneDockStyle.label(detail, size: 12, color: DroneDockStyle.secondary)
detailLabel.numberOfLines = 0
detailLabel.textAlignment = .center
let stack = UIStackView(arrangedSubviews: [image, titleLabel, detailLabel])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 9
install(stack, insets: UIEdgeInsets(top: 22, left: 16, bottom: 22, right: 16), card: true)
}
/// 使用服务端 today 字段;缺失数据保持未知,不显示为零。
func applyStatistics(_ today: DroneDockHomeToday?) {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "zh_CN")
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let amount = today?.orderAmount.flatMap { formatter.string(from: NSDecimalNumber(decimal: $0)) }.map { "¥" + $0 } ?? "—"
let values = [(today?.orderCount.map(String.init) ?? "—", "成交订单"),
(amount, "成交金额"), (today?.finishedShoot.map(String.init) ?? "—", "完成拍摄")]
let columns = values.map { value, title in
let label = DroneDockStyle.label(value, size: 23, weight: .semibold)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.6
let stack = UIStackView(arrangedSubviews: [label, DroneDockStyle.label(title, size: 12, color: DroneDockStyle.secondary)])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 9
return stack
}
let stack = UIStackView(arrangedSubviews: columns)
stack.distribution = .fillEqually
install(stack, insets: UIEdgeInsets(top: 23, left: 10, bottom: 23, right: 10), card: true)
}
private func install(_ view: UIView, insets: UIEdgeInsets, card: Bool) {
embeddedView?.removeFromSuperview()
embeddedView = view
if card { DroneDockStyle.applyCard(to: contentView) } else { contentView.backgroundColor = .clear }
contentView.addSubview(view)
view.snp.makeConstraints { $0.edges.equalToSuperview().inset(insets) }
}
}
/// 首页分区标题与后续订单列表入口。
private final class DroneDockHomeHeader: UICollectionReusableView {
/// 用户请求查看完整订单列表。
var onViewAll: (() -> Void)?
private let label = DroneDockStyle.label(size: 17, weight: .semibold)
private let button = UIButton(type: .system)
override init(frame: CGRect) {
super.init(frame: frame)
button.setTitle("查看全部 ›", for: .normal)
button.titleLabel?.font = .systemFont(ofSize: 13)
button.tintColor = DroneDockStyle.primary
button.accessibilityIdentifier = "drone.home.allOrders"
button.addTarget(self, action: #selector(tapped), for: .touchUpInside)
button.snp.makeConstraints { $0.height.equalTo(44) }
let stack = UIStackView(arrangedSubviews: [label, UIView(), button])
stack.alignment = .center
addSubview(stack)
stack.snp.makeConstraints { $0.leading.trailing.centerY.equalToSuperview() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 刷新区块标题和入口可见性。
func apply(title: String, showsAction: Bool) {
label.text = title
button.isHidden = !showsAction
}
@objc private func tapped() { onViewAll?() }
}