import SnapKit import UIKit /// 展示准备信息并提交召唤;业务成功后携同一任务 ID 进入真实拍摄任务页。 @MainActor final class DroneDockRemotePreparationViewController: BaseViewController { /// 当前订单、准备信息及任务创建状态。 let viewModel: DroneDockPreparationViewModel /// 点位与航线沿用原准备页顺序,状态区单独承载加载和错误说明。 private enum Section: Int, CaseIterable { case order, points, routes, status, creationResult, shootResult } /// 点位与航线使用后端稳定 ID,刷新时保留有效选择。 private enum Item: Hashable { case order, point(Int), route(Int), emptyPoints, emptyRoutes, status, creationResult, shootResult } private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout()) private var dataSource: UICollectionViewDiffableDataSource! private let footerView = DronePreparationFooterView() private let refreshControl = UIRefreshControl() private var refreshTask: Task? private var planeStatusTask: Task? private var creationTask: Task? private var isStartingCreation = false private let planeStatusPollDelay: @Sendable (UInt64) async throws -> Void private var isRefreshing = false private var isPageVisible = false private var isApplicationActive = false private var automaticallyOpenedTaskID: Int? private let taskControllerFactory: @MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController private let simulationRecordsProvider: (@MainActor () -> String)? /// 注入准备页业务状态和轮询等待,便于验证任务创建及页面生命周期。 init(viewModel: DroneDockPreparationViewModel, taskControllerFactory: (@MainActor (Int, DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil, simulationRecordsProvider: (@MainActor () -> String)? = nil, planeStatusPollDelay: @escaping @Sendable (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) { self.viewModel = viewModel self.simulationRecordsProvider = simulationRecordsProvider self.taskControllerFactory = taskControllerFactory ?? { taskID, order, context in DroneDockShootingTaskEntry.makeController(taskID: taskID, order: order, context: context) } self.planeStatusPollDelay = planeStatusPollDelay super.init(nibName: nil, bundle: nil) hidesBottomBarWhenPushed = true } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { refreshTask?.cancel() planeStatusTask?.cancel() creationTask?.cancel() NotificationCenter.default.removeObserver(self) } override func setupNavigationBar() { title = simulationRecordsProvider == nil ? "拍摄准备" : "拍摄准备 · 本地模拟" navigationItem.backButtonDisplayMode = .minimal if simulationRecordsProvider != nil { let records = UIBarButtonItem(image: UIImage(systemName: "doc.text"), style: .plain, target: self, action: #selector(showSimulationRecords)) records.accessibilityLabel = "查看模拟接口回执" records.accessibilityIdentifier = "drone.preparation.mock.recordsButton" navigationItem.rightBarButtonItem = records } #if DEBUG if simulationRecordsProvider == nil, DeviceCommandDebugPolicy.blocksLiveRequests, viewModel.isTaskSubmissionBlocked { let simulation = UIBarButtonItem(title: "本地模拟", style: .plain, target: self, action: #selector(openLocalSimulation)) simulation.accessibilityIdentifier = "drone.preparation.mock.entry" navigationItem.rightBarButtonItem = simulation } #endif } #if DEBUG /// 打开独立模拟订单,不沿用真实会话、服务或当前订单创建任务。 @objc private func openLocalSimulation() { guard !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning, let navigationController, navigationController.topViewController === self, let controller = DroneDockStartShootSimulation.makePreparationController() else { return } navigationController.pushViewController(controller, animated: true) } #endif /// 显示内存传输记录,并明确说明其不是后端真实回执。 @objc private func showSimulationRecords() { guard let simulationRecordsProvider, presentedViewController == nil, !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning else { return } let controller = DroneDockSimulationRecordsViewController(records: simulationRecordsProvider()) present(UINavigationController(rootViewController: controller), animated: true) } override func setupUI() { view.backgroundColor = .white collectionView.backgroundColor = .white collectionView.alwaysBounceVertical = true collectionView.showsVerticalScrollIndicator = false collectionView.delegate = self collectionView.accessibilityIdentifier = "drone.preparation.remote.list" collectionView.register(DronePreparationOrderCell.self, forCellWithReuseIdentifier: "order") collectionView.register(DronePreparationPointCell.self, forCellWithReuseIdentifier: "point") collectionView.register(DronePreparationRouteCell.self, forCellWithReuseIdentifier: "route") collectionView.register(DronePreparationEmptyCell.self, forCellWithReuseIdentifier: "message") collectionView.register(DroneDockTaskCreationResultCell.self, forCellWithReuseIdentifier: "creationResult") collectionView.register(DronePreparationHeadingView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "heading") refreshControl.tintColor = DroneDockStyle.primary collectionView.refreshControl = refreshControl view.addSubview(collectionView) view.addSubview(footerView) configureDataSource() applySnapshot(animated: false) } override func setupConstraints() { collectionView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide) make.leading.trailing.equalToSuperview() make.bottom.equalTo(footerView.snp.top) } footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() } } override func bindActions() { refreshControl.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged) footerView.onRefreshTap = { [weak self] in self?.refreshPreparation() } footerView.onPrimaryTap = { [weak self] in self?.createSelectedTask() } NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isPageVisible = true isApplicationActive = UIApplication.shared.applicationState == .active refreshPreparation() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isPageVisible = false stopPlaneStatusPolling() refreshTask?.cancel() creationTask?.cancel() isStartingCreation = false isRefreshing = false refreshControl.endRefreshing() viewModel.invalidate() } private func refreshPreparation() { guard !isStartingCreation, !viewModel.isCreatingTask, !viewModel.isSummoning else { refreshControl.endRefreshing(); return } startPlaneStatusPolling() guard !isRefreshing else { return } isRefreshing = true refreshTask = Task { @MainActor [weak self] in guard let self else { return } let isInitialLoad = self.viewModel.projectInfo == nil self.applySnapshot(animated: false) await self.viewModel.refresh() guard !Task.isCancelled else { return } self.isRefreshing = false self.refreshControl.endRefreshing() self.applySnapshot(animated: true) { [weak self] in guard let self else { return } if isInitialLoad { self.collectionView.layoutIfNeeded() self.collectionView.setContentOffset(CGPoint(x: 0, y: -self.collectionView.adjustedContentInset.top), animated: false) } #if DEBUG Task { @MainActor [weak self] in await self?.capturePreparationIfRequested() } #endif } } } /// 首次创建并召唤;成功后进入原任务,再次查看不经过创建或召唤接口。 private func createSelectedTask() { DroneDockDiagnostics.event("preparation.confirm_tapped", taskID: viewModel.createdTask?.taskID, fields: [ "order_number": viewModel.order.orderNumber as Any? ?? NSNull(), "scenic_id": viewModel.context.scenicID, "spot_id": viewModel.selectedSpotID as Any? ?? NSNull(), "air_line_id": viewModel.selectedRouteID as Any? ?? NSNull(), "enabled": viewModel.isPrimaryActionEnabled, "blocked": viewModel.isTaskSubmissionBlocked ]) guard !isRefreshing, !isStartingCreation else { return } if viewModel.canOpenShootingTask { _ = openShootingTask(automatically: false) return } guard viewModel.isPrimaryActionEnabled else { return } isStartingCreation = true applySnapshot(animated: false) creationTask = Task { @MainActor [weak self] in guard let self else { return } await self.viewModel.prepareAndSummon { [weak self] in self?.applySnapshot(animated: false) } guard !Task.isCancelled else { return } self.isStartingCreation = false if self.openShootingTask(automatically: true) { return } self.applySnapshot(animated: true) { [weak self] in guard let self, let path = self.dataSource.indexPath(for: .shootResult) ?? self.dataSource.indexPath(for: .creationResult) else { return } self.collectionView.scrollToItem(at: path, at: .top, animated: true) self.showFilingFailureIfNeeded() } } } /// 报备问题在明确提交失败后提示一次,后台及设备轮询不会反复弹窗。 private func showFilingFailureIfNeeded() { guard isPageVisible, isApplicationActive, presentedViewController == nil, let failure = viewModel.summonFailure ?? viewModel.creationFailure, failure.requiresFiling else { return } let alert = UIAlertController(title: failure.title, message: failure.message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "我知道了", style: .default)) present(alert, animated: true) } /// 成功后自动导航一次;失败的已结束任务只在用户明确点击时查看原任务。 @discardableResult private func openShootingTask(automatically: Bool) -> Bool { guard isPageVisible, isApplicationActive, viewModel.canOpenShootingTask, let taskID = viewModel.createdTask?.taskID, let navigationController, navigationController.topViewController === self, !automatically || (viewModel.shootResponse != nil && automaticallyOpenedTaskID != taskID) else { return false } DroneDockDiagnostics.event("navigation.open_task", taskID: taskID) automaticallyOpenedTaskID = taskID let controller = taskControllerFactory(taskID, viewModel.order, viewModel.context) navigationController.pushViewController(controller, animated: true) return true } /// 设备请求与购买快照各自更新,轮询不重载列表或改变点位、航线选择。 private func startPlaneStatusPolling() { guard isPageVisible, isApplicationActive else { return } stopPlaneStatusPolling() let delay = planeStatusPollDelay planeStatusTask = Task { @MainActor [weak self] in while !Task.isCancelled { guard let interval = await self?.refreshPlaneStatusIfVisible() else { return } do { try await delay(interval) } catch { return } } } } private func refreshPlaneStatusIfVisible() async -> UInt64? { guard isPageVisible, isApplicationActive, !Task.isCancelled else { return nil } await viewModel.refreshPlaneStatus() guard isPageVisible, isApplicationActive, !Task.isCancelled else { return nil } if viewModel.errorMessage != nil { applySnapshot(animated: false) } else { footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation, isLocalSimulation: simulationRecordsProvider != nil) } return viewModel.pollIntervalNanoseconds } private func stopPlaneStatusPolling() { planeStatusTask?.cancel() planeStatusTask = nil viewModel.invalidatePlaneStatus() } @objc private func applicationWillResignActive() { isApplicationActive = false stopPlaneStatusPolling() footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation, isLocalSimulation: simulationRecordsProvider != nil) } @objc private func applicationDidBecomeActive() { isApplicationActive = true startPlaneStatusPolling() } private func configureDataSource() { dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { [weak self] list, path, item in guard let self else { return nil } switch item { case .order: let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: path) as! DronePreparationOrderCell cell.apply(homeOrder: self.viewModel.order, summary: self.viewModel.latestOrderSummary, usesHomeSnapshot: self.viewModel.projectInfo == nil && self.viewModel.errorMessage == nil) return cell case .point(let id): let cell = list.dequeueReusableCell(withReuseIdentifier: "point", for: path) as! DronePreparationPointCell if let spot = self.viewModel.spots.first(where: { $0.id == id }) { cell.apply(spot: spot, selected: self.viewModel.selectedSpotID == id) } return cell case .route(let id): let cell = list.dequeueReusableCell(withReuseIdentifier: "route", for: path) as! DronePreparationRouteCell if let route = self.viewModel.routes.first(where: { $0.id == id }) { cell.apply(route: route, selected: self.viewModel.selectedRouteID == id) } return cell case .creationResult: let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell if let failure = self.viewModel.creationFailure { cell.apply(failure: failure, identifier: "drone.preparation.creationResponse") } return cell case .shootResult: let cell = list.dequeueReusableCell(withReuseIdentifier: "creationResult", for: path) as! DroneDockTaskCreationResultCell if let failure = self.viewModel.summonFailure { cell.apply(failure: failure, identifier: "drone.preparation.shootResponse") } return cell case .emptyPoints, .emptyRoutes, .status: let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: path) as! DronePreparationEmptyCell if item == .status { self.applyStatus(to: cell) } else if item == .emptyPoints { cell.apply(title: "暂无可用拍摄点", detail: "当前套餐暂无已购拍摄点,请刷新重试") } else if self.viewModel.selectedSpot == nil { cell.apply(title: "请选择拍摄点", detail: "选择拍摄点后查看对应航线") } else { cell.apply(title: "暂无可用航线", detail: "请选择其他拍摄点,或稍后刷新重试") } return cell } } dataSource.supplementaryViewProvider = { [weak self] list, kind, path in guard let self else { return nil } let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "heading", for: path) as! DronePreparationHeadingView self.applyHeading(header, section: Section(rawValue: path.section)) return header } } private func applyStatus(to cell: DronePreparationEmptyCell) { if isRefreshing, viewModel.projectInfo == nil { cell.apply(title: "正在加载", detail: "正在获取已购套餐、拍摄点和航线") } else if let error = viewModel.errorMessage { cell.apply(title: "准备信息加载失败", detail: error + ",请下拉或点击刷新状态重试") } else { cell.apply(title: "正在加载", detail: "正在获取拍摄准备信息") } } private func applySnapshot(animated: Bool, completion: (() -> Void)? = nil) { navigationItem.rightBarButtonItem?.isEnabled = !isStartingCreation && !viewModel.isCreatingTask && !viewModel.isSummoning guard dataSource != nil else { return } let previous = dataSource.snapshot() let existing = Set(previous.itemIdentifiers) var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections(Section.allCases) snapshot.appendItems([.order], toSection: .order) if viewModel.projectInfo != nil, viewModel.errorMessage == nil { snapshot.appendItems(viewModel.spots.isEmpty ? [.emptyPoints] : viewModel.spots.map { .point($0.id) }, toSection: .points) if !viewModel.spots.isEmpty { snapshot.appendItems(viewModel.routes.isEmpty ? [.emptyRoutes] : viewModel.routes.map { .route($0.id) }, toSection: .routes) } } else { snapshot.appendItems([.status], toSection: .status) } if viewModel.creationFailure != nil { snapshot.appendItems([.creationResult], toSection: .creationResult) } if viewModel.summonFailure != nil { snapshot.appendItems([.shootResult], toSection: .shootResult) } snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) }) footerView.apply(preparationViewModel: viewModel, isRefreshing: isRefreshing || isStartingCreation, isLocalSimulation: simulationRecordsProvider != nil) let previousPointCount = previous.sectionIdentifiers.contains(.points) ? previous.numberOfItems(inSection: .points) : 0 let previousRouteCount = previous.sectionIdentifiers.contains(.routes) ? previous.numberOfItems(inSection: .routes) : 0 let layoutChanged = previousPointCount != snapshot.numberOfItems(inSection: .points) || previous.itemIdentifiers.contains(.emptyPoints) != snapshot.itemIdentifiers.contains(.emptyPoints) || previous.itemIdentifiers.contains(.emptyRoutes) != snapshot.itemIdentifiers.contains(.emptyRoutes) || previousRouteCount != snapshot.numberOfItems(inSection: .routes) if layoutChanged || viewModel.projectInfo != nil { collectionView.collectionViewLayout.invalidateLayout() } dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in guard let self else { return } let kind = UICollectionView.elementKindSectionHeader for path in self.collectionView.indexPathsForVisibleSupplementaryElements(ofKind: kind) { if let header = self.collectionView.supplementaryView(forElementKind: kind, at: path) as? DronePreparationHeadingView { self.applyHeading(header, section: Section(rawValue: path.section)) } } completion?() } } private func makeLayout() -> UICollectionViewLayout { UICollectionViewCompositionalLayout { [weak self] index, environment in guard let self, let section = Section(rawValue: index) else { return nil } let height: NSCollectionLayoutDimension let width: NSCollectionLayoutDimension switch section { case .order: height = .estimated(100); width = .fractionalWidth(1) case .points: height = .absolute(self.viewModel.spots.isEmpty ? 150 : DronePreparationPointCell.preferredHeight( names: self.viewModel.spots.map(\.name), width: 200)) width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(200) case .routes: height = self.viewModel.routes.isEmpty ? .absolute(160) : .estimated(64) width = .fractionalWidth(1) case .status: height = .absolute(160); width = .fractionalWidth(1) case .creationResult, .shootResult: height = .estimated(100); width = .fractionalWidth(1) } let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: height)) let group = NSCollectionLayoutGroup.vertical(layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item]) let layout = NSCollectionLayoutSection(group: group) layout.contentInsets = NSDirectionalEdgeInsets(top: section == .shootResult ? 12 : 0, leading: 16, bottom: section == .status ? 12 : 0, trailing: 16) if section == .points, !self.viewModel.spots.isEmpty { layout.orthogonalScrollingBehavior = .continuous layout.interGroupSpacing = 8 } let showsHeading = self.viewModel.projectInfo != nil && self.viewModel.errorMessage == nil && (section == .points || (section == .routes && !self.viewModel.spots.isEmpty)) if showsHeading { layout.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem( layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .points ? 46 : DronePreparationHeadingView.preferredHeight( title: self.viewModel.selectedSpot.map { "\($0.name)的航线" } ?? "拍摄航线", detail: "共 \(self.viewModel.routes.count) 条", width: environment.container.effectiveContentSize.width - 32))), elementKind: UICollectionView.elementKindSectionHeader, alignment: .top)] } return layout } } private func applyHeading(_ header: DronePreparationHeadingView, section: Section?) { switch section { case .points: header.apply(title: "拍摄点", detail: nil) case .routes: header.apply(title: viewModel.selectedSpot.map { "\($0.name)的航线" } ?? "拍摄航线", detail: "共 \(viewModel.routes.count) 条") default: header.apply(title: "", detail: nil) } } @objc private func refreshTriggered() { refreshPreparation() } #if DEBUG /// 显式联调时只保存本应用窗口,不截取其他应用内容。 private func capturePreparationIfRequested() async { guard ProcessInfo.processInfo.arguments.contains("--dock-preparation-capture") else { return } 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("DronePreparationDiagnostics", isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) try image.pngData()?.write(to: directory.appendingPathComponent("preparation-real.png"), options: .atomic) print("[DronePreparation] App window screenshot saved") } catch { print("[DronePreparation] Screenshot failed: \(error.localizedDescription)") } } #endif } extension DroneDockRemotePreparationViewController: UICollectionViewDelegate { /// 点位和航线只在当前成功快照中选择,刷新期间不切换旧配置。 func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { guard !isRefreshing, !isStartingCreation, !viewModel.isCreatingTask, viewModel.createdTask == nil, !viewModel.taskCreationOutcomeUnknown, viewModel.projectInfo != nil, viewModel.errorMessage == nil, let item = dataSource.itemIdentifier(for: indexPath) else { return false } switch item { case .point(let id): return viewModel.spots.first { $0.id == id }?.available == true case .route(let id): return viewModel.routes.first { $0.id == id }?.available == true default: return false } } /// 更新本地点位、航线及底部摘要,不创建拍摄任务。 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard !isRefreshing, !isStartingCreation, !viewModel.isCreatingTask, viewModel.createdTask == nil, !viewModel.taskCreationOutcomeUnknown, let item = dataSource.itemIdentifier(for: indexPath) else { return } switch item { case .point(let id): viewModel.selectSpot(id: id) case .route(let id): viewModel.selectRoute(id: id) default: return } applySnapshot(animated: true) } }