import SnapKit import UIKit /// 真实拍摄任务页:进入后仅查询同一任务,展示状态与遥测,不发送飞行控制。 @MainActor final class DroneDockShootingTaskViewController: BaseViewController { /// 入口传入的固定任务身份及只读状态,供导航协调和页面测试检查。 let viewModel: DroneDockShootingTaskViewModel private let topView = UIView() private let summaryView = UIView() private let taskTitleLabel = DroneDockStyle.label(size: 17, weight: .semibold) private let subtitleLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) private let feedPlaceholder = DroneDockTaskFeedPlaceholderView() private let telemetryView = DroneShootingTaskTelemetryView() private let statusView = DroneDockTaskStatusView() private let safetyView = DroneDockTaskSafetyView() private var summaryHeight: Constraint? private var safetyHeight: Constraint? private var compactLayout: Bool? private var bottomInset: CGFloat = -1 private let materialsControllerFactory: @MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController private var refreshTask: Task? private var requestGeneration = 0 private var isPageVisible = false private var isApplicationActive = false private var isRequesting = false /// 构造时只保存依赖,首次 GET 必须等页面完整出现后才发送。 init(viewModel: DroneDockShootingTaskViewModel, materialsControllerFactory: (@MainActor (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController)? = nil) { self.viewModel = viewModel self.materialsControllerFactory = materialsControllerFactory ?? { order, context in DroneDockMaterialsViewController(viewModel: DroneDockMaterialsViewModel( context: context, order: order, service: DroneDockMaterialsAPI(client: NetworkServices.shared.apiClient), currentContext: { DroneDockHomeViewController.currentContext() })) } super.init(nibName: nil, bundle: nil) hidesBottomBarWhenPushed = true } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { refreshTask?.cancel() NotificationCenter.default.removeObserver(self) } /// 使用常规导航返回准备页,不劫持返回手势或自动创建任务。 override func setupNavigationBar() { title = "拍摄任务" navigationItem.backButtonDisplayMode = .minimal let refresh = UIBarButtonItem(image: UIImage(systemName: "arrow.clockwise"), style: .plain, target: self, action: #selector(refreshTriggered)) refresh.accessibilityLabel = "刷新任务状态" refresh.accessibilityIdentifier = "drone.task.remote.navigationRefresh" navigationItem.rightBarButtonItem = refresh } /// 顶部、中间状态和安全控制分开布局,状态切换不影响外部区域大小。 override func setupUI() { view.backgroundColor = .white topView.accessibilityIdentifier = "drone.task.remote.top" summaryView.accessibilityIdentifier = "drone.task.remote.summary" statusView.accessibilityIdentifier = "drone.task.remote.stateContainer" safetyView.accessibilityIdentifier = "drone.task.remote.safety" view.addSubview(topView) view.addSubview(statusView) view.addSubview(safetyView) topView.addSubview(summaryView) summaryView.addSubview(taskTitleLabel) summaryView.addSubview(subtitleLabel) taskTitleLabel.numberOfLines = 1 taskTitleLabel.lineBreakMode = .byTruncatingTail taskTitleLabel.accessibilityIdentifier = "drone.task.remote.title" subtitleLabel.numberOfLines = 1 subtitleLabel.lineBreakMode = .byTruncatingTail subtitleLabel.accessibilityIdentifier = "drone.task.remote.subtitle" topView.addSubview(feedPlaceholder) topView.addSubview(telemetryView) telemetryView.accessibilityIdentifier = "drone.task.remote.telemetry" telemetryView.configureFixedLayout(compact: false) applySnapshot() } /// 图传保持 16:9,底部贴安全区,中间占满剩余空间且没有滚动容器。 override func setupConstraints() { topView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide) make.leading.trailing.equalToSuperview() } summaryView.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview() summaryHeight = make.height.equalTo(60).constraint } taskTitleLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview().inset(16) make.bottom.equalTo(summaryView.snp.centerY).offset(-1) } subtitleLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview().inset(16) make.top.equalTo(summaryView.snp.centerY).offset(2) } feedPlaceholder.snp.makeConstraints { make in make.top.equalTo(summaryView.snp.bottom) make.leading.trailing.equalToSuperview() make.height.equalTo(feedPlaceholder.snp.width).multipliedBy(9.0 / 16.0) } telemetryView.snp.makeConstraints { make in make.top.equalTo(feedPlaceholder.snp.bottom) make.leading.trailing.bottom.equalToSuperview() } safetyView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() safetyHeight = make.height.equalTo(104).constraint } statusView.snp.makeConstraints { make in make.top.equalTo(topView.snp.bottom) make.bottom.equalTo(safetyView.snp.top) make.leading.trailing.equalToSuperview() } } /// 只按设备可用尺寸调整固定区域,数据、错误和加载状态不会改变它们的高度。 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let availableHeight = view.bounds.height - view.safeAreaInsets.top - view.safeAreaInsets.bottom let compact = availableHeight < 680 let inset = view.safeAreaInsets.bottom guard compactLayout != compact || bottomInset != inset else { return } compactLayout = compact bottomInset = inset summaryHeight?.update(offset: compact ? 44 : 60) safetyHeight?.update(offset: (compact ? 90 : 104) + inset) telemetryView.configureFixedLayout(compact: compact) safetyView.configure(compact: compact) taskTitleLabel.font = .systemFont(ofSize: compact ? 16 : 17, weight: .semibold) } /// 仅绑定读取、详情和已有素材入口;本轮不发送飞控指令。 override func bindActions() { statusView.onPrimaryAction = { [weak self] in self?.primaryActionTriggered() } statusView.onDetails = { [weak self] in self?.showStatusDetails() } 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 viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) isPageVisible = true isApplicationActive = UIApplication.shared.applicationState == .active refreshTaskIfVisible() } /// 离页立即取消未完成的读取,使迟到响应失效。 override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isPageVisible = false cancelRefresh() } private func applySnapshot() { guard isViewLoaded else { return } let loading = isRequesting || viewModel.isLoading taskTitleLabel.text = viewModel.title subtitleLabel.text = viewModel.subtitle let telemetry = viewModel.telemetry telemetryView.apply(values: [telemetry.batteryText, telemetry.temperatureText, telemetry.windText, telemetry.rainText, telemetry.signalText, telemetry.satelliteText], isStale: loading || viewModel.isTelemetryStale, accessibilityPrefix: "drone.task.remote.metric") let value = loading ? DroneDockTaskPresentation( phase: .loading, title: "正在获取任务状态", message: "正在读取当前拍摄任务", deviceStatus: "—", action: .none, actionTitle: nil, isActionEnabled: false) : viewModel.presentation statusView.apply(value) statusView.isUserInteractionEnabled = isPageVisible && isApplicationActive && !loading navigationItem.rightBarButtonItem?.isEnabled = isPageVisible && isApplicationActive && !loading } private func primaryActionTriggered() { guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return } let state = viewModel.presentation guard state.isActionEnabled else { return } switch state.action { case .refresh: refreshTaskIfVisible() case .materials: guard let navigationController, navigationController.topViewController === self else { return } navigationController.pushViewController(materialsControllerFactory(viewModel.order, viewModel.context), animated: true) case .start, .resume, .none: break } } private func showStatusDetails() { guard isPageVisible, isApplicationActive, presentedViewController == nil else { return } let state = viewModel.presentation let texts = [state.title, state.message, state.deviceStatus].filter { !$0.isEmpty && $0 != "—" } var distinct: [String] = [] for text in texts where !distinct.contains(text) { distinct.append(text) } let alert = UIAlertController(title: "任务状态详情", message: distinct.joined(separator: "\n\n"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: "关闭", style: .cancel)) present(alert, animated: true) } /// 页面进入、回到前台或手动刷新时各读一次,请求结束后不安排下一次读取。 private func refreshTaskIfVisible() { guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return } requestGeneration &+= 1 let generation = requestGeneration isRequesting = true applySnapshot() refreshTask = Task { @MainActor [weak self] in guard let self else { return } await self.viewModel.refresh() guard self.isPageVisible, self.isApplicationActive, self.requestGeneration == generation, !Task.isCancelled else { return } self.refreshTask = nil self.isRequesting = false self.applySnapshot() } } private func cancelRefresh() { requestGeneration &+= 1 refreshTask?.cancel() refreshTask = nil isRequesting = false viewModel.invalidate() applySnapshot() } @objc private func refreshTriggered() { guard isPageVisible, isApplicationActive, !isRequesting, !viewModel.isLoading else { return } refreshTaskIfVisible() } @objc private func applicationWillResignActive() { isApplicationActive = false cancelRefresh() } @objc private func applicationDidBecomeActive() { guard !isApplicationActive else { return } isApplicationActive = true refreshTaskIfVisible() } } /// 固定底部的安全控制占位,尚未接入控制接口时不提供可执行的飞控动作。 @MainActor private final class DroneDockTaskSafetyView: UIView { private let header = DroneDockStyle.label("安全控制", size: 11, color: DroneDockStyle.secondary) private let pauseButton = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: UIColor(hex: 0xEC982A), filled: true) private let returnButton = DroneShootingTaskSafetyButton(symbol: "arrow.uturn.backward", color: UIColor(hex: 0xD85762), filled: false) private let buttons = UIStackView() private var headerTop: Constraint? private var headerHeight: Constraint? private var buttonGap: Constraint? private var buttonHeight: Constraint? /// 复用安全按钮样式,按钮始终保留占位与明确的不可用状态。 override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white let divider = UIView() divider.backgroundColor = DroneDockStyle.border addSubview(divider) divider.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview() make.height.equalTo(0.5) } header.textAlignment = .center addSubview(header) buttons.axis = .horizontal buttons.spacing = 8 buttons.distribution = .fillEqually buttons.addArrangedSubview(pauseButton) buttons.addArrangedSubview(returnButton) addSubview(buttons) pauseButton.accessibilityIdentifier = "drone.task.remote.pause" returnButton.accessibilityIdentifier = "drone.task.remote.return" pauseButton.apply(title: "紧急暂停", subtitle: "暂不可用", enabled: false) returnButton.apply(title: "立即返航", subtitle: "暂不可用", enabled: false) header.snp.makeConstraints { make in headerTop = make.top.equalToSuperview().offset(10).constraint make.leading.trailing.equalToSuperview().inset(16) headerHeight = make.height.equalTo(14).constraint } buttons.snp.makeConstraints { make in buttonGap = make.top.equalTo(header.snp.bottom).offset(8).constraint make.leading.trailing.equalToSuperview().inset(16) buttonHeight = make.height.equalTo(62).constraint } } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 高度仅依设备空间切换,不随任务状态、按钮文案或网络响应变化。 func configure(compact: Bool) { headerTop?.update(offset: compact ? 8 : 10) headerHeight?.update(offset: compact ? 12 : 14) buttonGap?.update(offset: compact ? 6 : 8) buttonHeight?.update(offset: compact ? 56 : 62) } } /// 真实图传尚未接入时的中性占位,不使用演示图片、播放进度或虚假连接状态。 @MainActor private final class DroneDockTaskFeedPlaceholderView: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(hex: 0x172033) accessibilityIdentifier = "drone.task.remote.feedPlaceholder" let icon = UIImageView(image: UIImage(systemName: "video.slash")) icon.contentMode = .scaleAspectFit icon.tintColor = UIColor.white.withAlphaComponent(0.6) let title = DroneDockStyle.label("图传暂未接入", size: 15, weight: .medium, color: .white) let detail = DroneDockStyle.label("任务状态将在下方更新", size: 12, color: .white.withAlphaComponent(0.65)) let stack = UIStackView(arrangedSubviews: [icon, title, detail]) stack.axis = .vertical stack.spacing = 9 stack.alignment = .center addSubview(stack) icon.snp.makeConstraints { make in make.size.equalTo(31) } stack.snp.makeConstraints { make in make.center.equalToSuperview() make.leading.greaterThanOrEqualToSuperview().offset(20) make.trailing.lessThanOrEqualToSuperview().offset(-20) } isAccessibilityElement = true accessibilityLabel = "图传暂未接入,任务状态将在下方更新" } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }