feat: 自动刷新订单交付确认状态

This commit is contained in:
2026-11-04 10:33:11 +08:00
parent 082ecf96f2
commit 7a63ea3432
5 changed files with 212 additions and 36 deletions
@@ -13,23 +13,28 @@ final class DroneDockConfirmationViewController: BaseViewController {
/// 刷新状态时重配置现有内容,避免二维码和旧数据闪空。
private enum Item: Hashable { case summary, state, statistics, code, receipt, manifest, film(Int), note, error }
/// 用户操作期间禁止再次提交相同请求。
private enum Operation { case refresh, status, generate }
private enum Operation { case refresh, status, generate, poll }
private let imageLoader: any DroneDockPaymentImageLoading
private let allowsRemoteMedia: Bool
private let thumbnailProvider: ((DroneDockMaterialTask) -> UIImage?)?
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
private let statusPollDelay: @MainActor (UInt64) async throws -> Void
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private let footer = DroneDeliveryReviewFooterView()
private var requestTask: Task<Void, Never>?
private var pollDelayTask: Task<Void, Never>?
private var operation: Operation?
private var hasAppeared = false
private var isPageVisible = false
private var isApplicationActive = false
private var isShowingDeliverySheet = false
private var needsImmediateStatusCheck = false
private var imageURL: URL?
private var codeImage: UIImage?
private var imageError: String?
private var imageGeneration = 0
private var foregroundObserver: NSObjectProtocol?
private var isManifestExpanded = false
/// 复用原尺寸小程序码图片加载器;模拟测试可替换图片来源并关闭远程素材。
@@ -37,11 +42,13 @@ final class DroneDockConfirmationViewController: BaseViewController {
imageLoader: (any DroneDockPaymentImageLoading)? = nil,
allowsRemoteMedia: Bool = true,
thumbnailProvider: ((DroneDockMaterialTask) -> UIImage?)? = nil,
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil) {
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil,
statusPollDelay: @escaping @MainActor (UInt64) async throws -> Void = { try await Task.sleep(nanoseconds: $0) }) {
self.viewModel = viewModel
self.imageLoader = imageLoader ?? DroneDockPaymentImageLoader()
self.allowsRemoteMedia = allowsRemoteMedia
self.thumbnailProvider = thumbnailProvider
self.statusPollDelay = statusPollDelay
self.deliveryControllerFactory = deliveryControllerFactory ?? { order, context, taskID in
DroneDockDeliveryEntry.makeController(order: order, context: context, taskID: taskID)
}
@@ -54,7 +61,7 @@ final class DroneDockConfirmationViewController: BaseViewController {
deinit {
requestTask?.cancel()
if let foregroundObserver { NotificationCenter.default.removeObserver(foregroundObserver) }
pollDelayTask?.cancel()
}
override func setupNavigationBar() {
@@ -86,14 +93,11 @@ final class DroneDockConfirmationViewController: BaseViewController {
view.addSubview(footer)
configureDataSource()
applySnapshot()
foregroundObserver = NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification,
object: nil, queue: .main) { [weak self] _ in
Task { @MainActor [weak self] in
guard let self, self.viewIfLoaded?.window != nil,
self.navigationController?.topViewController === self else { return }
self.run(self.viewModel.detail == nil ? .refresh : .status)
}
}
isApplicationActive = UIApplication.shared.applicationState == .active
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 setupConstraints() {
@@ -117,10 +121,23 @@ final class DroneDockConfirmationViewController: BaseViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
run(hasAppeared && viewModel.code != nil ? .status : .refresh)
if !hasAppeared || !viewModel.isAwaitingConfirmation { run(.refresh) }
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
isPageVisible = true
if hasAppeared { resumeStatusChecks() }
else { scheduleStatusCheck() }
hasAppeared = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
isPageVisible = false
pauseStatusChecks()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isMovingFromParent || navigationController == nil || navigationController?.isBeingDismissed == true {
@@ -131,6 +148,7 @@ final class DroneDockConfirmationViewController: BaseViewController {
}
private var filmTasks: [DroneDockMaterialTask] { viewModel.tasks.filter { $0.film != nil } }
private var isShowingOperation: Bool { operation != nil && operation != .poll }
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, environment in
@@ -282,12 +300,12 @@ final class DroneDockConfirmationViewController: BaseViewController {
let existing = Set(dataSource.snapshot().itemIdentifiers)
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
dataSource.apply(snapshot, animatingDifferences: false)
navigationItem.rightBarButtonItem?.isEnabled = operation == nil
navigationItem.rightBarButtonItem?.isEnabled = !isShowingOperation
updateFooter()
}
private func updateFooter() {
let busy = operation != nil
let busy = isShowingOperation
let needsReload = viewModel.detail == nil || !viewModel.hasLoadedTasks || viewModel.tasksErrorMessage != nil
let title: String
if viewModel.isCompleted { title = "返回订单列表" }
@@ -308,20 +326,28 @@ final class DroneDockConfirmationViewController: BaseViewController {
private func run(_ action: Operation) {
guard operation == nil else { return }
cancelPollDelay()
operation = action
applySnapshot()
if action != .poll { applySnapshot() }
requestTask = Task { @MainActor [weak self] in
guard let self else { return }
let hadCode = self.viewModel.code != nil
let wasCompleted = self.viewModel.isCompleted
let previousDetail = self.viewModel.detail
let previousCode = self.viewModel.code
let previousError = self.viewModel.errorMessage
switch action {
case .refresh: await self.viewModel.refresh()
case .status: await self.viewModel.refreshStatus()
case .generate: await self.viewModel.generateCode()
case .poll: await self.viewModel.refreshStatus(silently: true)
}
guard !Task.isCancelled else { return }
self.operation = nil
let stageChanged = (!hadCode && self.viewModel.code != nil) || (!wasCompleted && self.viewModel.isCompleted)
self.requestTask = nil
defer { self.scheduleStatusCheck() }
guard !Task.isCancelled else { return }
if action == .poll, previousDetail == self.viewModel.detail, previousCode == self.viewModel.code,
previousError == self.viewModel.errorMessage { return }
let stageChanged = (previousCode == nil && self.viewModel.code != nil)
|| (previousDetail?.order.orderStatus != 30 && self.viewModel.isCompleted)
if stageChanged { self.isManifestExpanded = false }
if self.viewModel.code?.imageURL != self.imageURL { self.loadCodeImage(forceRefresh: false) }
self.applySnapshot()
@@ -331,6 +357,56 @@ final class DroneDockConfirmationViewController: BaseViewController {
}
}
private var canPollStatus: Bool {
isPageVisible && isApplicationActive && !isShowingDeliverySheet && viewIfLoaded?.window != nil
&& viewModel.isAwaitingConfirmation
}
private func scheduleStatusCheck() {
guard canPollStatus, operation == nil, pollDelayTask == nil else { return }
if needsImmediateStatusCheck {
needsImmediateStatusCheck = false
run(.poll)
return
}
let delay = statusPollDelay
pollDelayTask = Task { @MainActor [weak self] in
do { try await delay(5_000_000_000) } catch { return }
guard !Task.isCancelled, let self else { return }
self.pollDelayTask = nil
if self.canPollStatus { self.run(.poll) }
}
}
private func resumeStatusChecks() {
guard canPollStatus else { return }
needsImmediateStatusCheck = true
cancelPollDelay()
scheduleStatusCheck()
}
private func pauseStatusChecks() {
needsImmediateStatusCheck = false
cancelPollDelay()
if operation == .poll { requestTask?.cancel() }
}
private func cancelPollDelay() {
pollDelayTask?.cancel()
pollDelayTask = nil
}
@objc private func applicationWillResignActive() {
isApplicationActive = false
pauseStatusChecks()
}
@objc private func applicationDidBecomeActive() {
guard !isApplicationActive else { return }
isApplicationActive = true
resumeStatusChecks()
}
private func performPrimaryAction() {
guard operation == nil else { return }
if viewModel.isCompleted { navigationController?.popViewController(animated: true) }
@@ -341,20 +417,28 @@ final class DroneDockConfirmationViewController: BaseViewController {
}
private func performSecondaryAction() {
guard operation == nil, presentedViewController == nil else { return }
guard !isShowingOperation, presentedViewController == nil else { return }
guard viewModel.code == nil, !viewModel.isCompleted, viewModel.detail != nil else {
navigationController?.popViewController(animated: true)
return
}
guard operation == nil else { return }
guard viewModel.validateContext() else { applySnapshot(); return }
viewModel.setReviewed(false)
applySnapshot()
let sheet = DroneDockDeliveryEntry.makeMethodSheet(order: viewModel.order, context: viewModel.context,
controllerFactory: deliveryControllerFactory, onDidCloseCloud: { [weak self] in self?.run(.refresh) })
controllerFactory: deliveryControllerFactory, onDidDismiss: { [weak self] openedCloud in
guard let self else { return }
self.isShowingDeliverySheet = false
if openedCloud { self.run(.refresh) }
else { self.resumeStatusChecks() }
})
isShowingDeliverySheet = true
pauseStatusChecks()
present(sheet, animated: true)
}
@objc private func refreshTapped() { run(viewModel.code != nil || viewModel.isCompleted ? .status : .refresh) }
@objc private func refreshTapped() { run(viewModel.isAwaitingConfirmation || viewModel.isCompleted ? .status : .refresh) }
private func clearImage() {
guard imageURL != nil || codeImage != nil || imageError != nil else { return }
@@ -395,6 +479,7 @@ final class DroneDockConfirmationViewController: BaseViewController {
guard allowsRemoteMedia else { showToast("本地模拟成片,不加载远程视频"); return }
guard let url = film.previewURL else { showToast("成片播放地址暂不可用"); return }
let controller = AVPlayerViewController()
controller.modalPresentationStyle = .fullScreen
controller.player = AVPlayer(url: url)
present(controller, animated: true) { controller.player?.play() }
}
@@ -7,11 +7,13 @@ enum DroneDockDeliveryEntry {
static func makeMethodSheet(order: DroneDockHomeOrder, context: DroneDockHomeContext,
taskID: Int? = nil,
controllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController,
onDidDismiss: ((Bool) -> Void)? = nil,
onDidCloseCloud: @escaping () -> Void = {}) -> UINavigationController {
let methods = DroneDockDeliveryMethodViewController(customerTitle: order.touristTitle)
let navigation = DroneDockDeliverySheetNavigationController(rootViewController: methods)
navigation.modalPresentationStyle = .pageSheet
navigation.onDidCloseCloud = onDidCloseCloud
navigation.onDidDismiss = onDidDismiss
methods.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
methods.onNearbyTransfer = { [weak navigation, weak methods] in
guard let navigation, let methods, navigation.topViewController === methods else { return }
@@ -63,6 +65,8 @@ private final class DroneDockDeliverySheetNavigationController: UINavigationCont
var didOpenCloud = false
/// 不因仅查看交付方式而刷新订单。
var onDidCloseCloud: (() -> Void)?
/// 关闭方式弹窗后通知来源页,并传回是否曾打开云端交付。
var onDidDismiss: ((Bool) -> Void)?
private var didNotifyClose = false
override func viewDidLoad() {
@@ -82,5 +86,6 @@ private final class DroneDockDeliverySheetNavigationController: UINavigationCont
guard !didNotifyClose else { return }
didNotifyClose = true
if didOpenCloud { onDidCloseCloud?() }
onDidDismiss?(didOpenCloud)
}
}