feat(drone-dock): 完成交付成片UI及首页入口适配

包含全部剩余改动:交付上传与游客确认流程、相关真机测试、drone_dock入口、后端接口与原型复核文档、截图及周报。
This commit is contained in:
2026-10-26 15:43:27 +08:00
parent c13282c7bc
commit 7862d208ce
49 changed files with 4578 additions and 53 deletions
@@ -0,0 +1,253 @@
import Foundation
/// 演示视频选择器中的本地示例,不读取设备相册。
struct DroneDeliveryVideo: Hashable, Sendable {
/// 本地示例的稳定标识,用于同一点位成功上传去重。
let id: String
/// 选择器中的视频名称。
let title: String
/// 队列展示的文件名。
let fileName: String
/// 本地封面图片名称。
let previewAssetName: String
/// 可播放的本地示例文件,缺失时为 nil。
let previewURL: URL?
/// 真实本地示例时长,不冒充实际拍摄时长。
let durationText: String
/// 演示文件大小展示值。
let sizeText: String
/// 映射到已有只读预览页面使用的素材快照。
var previewMaterial: DroneMaterial {
DroneMaterial(id: id, title: title, kind: .video, previewAssetName: previewAssetName,
previewURL: previewURL, durationText: durationText)
}
}
/// 成片上传的单文件状态,成功项永远不由重试或继续重新上传。
enum DroneDeliveryUploadState: Hashable, Sendable {
case uploading(progress: Double), paused, failed(message: String), completed
/// 列表状态文字,全部结果都属于本地演示。
var title: String {
switch self {
case .uploading: "演示上传中"
case .paused: "上传已暂停"
case .failed: "演示上传失败"
case .completed: "演示交付完成"
}
}
/// 是否为明确成功,不能从百分比或暂停推断。
var isCompleted: Bool { self == .completed }
/// 是否为明确失败,生命周期暂停不属于失败。
var isFailed: Bool {
if case .failed = self { return true }
return false
}
}
/// 单个上传任务保留稳定文件身份,执行令牌则归批次管理。
struct DroneDeliveryUploadItem: Hashable, Sendable {
/// 本次新增作品的稳定身份。
let id: String
/// 开始上传时冻结的视频快照。
let video: DroneDeliveryVideo
/// 最新明确回执或暂停状态。
var state: DroneDeliveryUploadState
}
/// 上传暂停的明确生命周期入口。
enum DroneDeliveryPauseReason: Hashable, Sendable {
case background, locked, leavingPage
}
/// 一批固定点位、固定视频的上传任务。
struct DroneDeliveryUploadBatch: Hashable, Sendable {
/// 执行令牌,暂停、继续与重试都会更换以拒绝旧回执。
let id: UUID
/// 本批作品归属的点位,不随后续浏览改变。
let pointID: String
/// 批次创建时的点位名称。
let pointName: String
/// 固定的视频队列与逐项状态。
var items: [DroneDeliveryUploadItem]
/// 是否等待用户手动继续。
var isPaused: Bool
/// 最近一次暂停原因。
var pauseReason: DroneDeliveryPauseReason?
}
/// 上传底栏使用的批次阶段。
enum DroneDeliveryUploadPhase: Hashable, Sendable {
case idle, uploading, paused, partialFailure, completed
}
/// 可由本地演示驱动注入的明确回执,不包含真实上传服务。
enum DroneDeliveryUploadEvent: Hashable, Sendable {
case progress(Double), succeeded, failed(message: String)
}
/// 本机演示上传成功的作品,与原素材、拍摄记录和次数独立。
struct DroneDeliveryWork: Hashable, Sendable {
/// 作品稳定身份,对同一上传成功回执去重。
let id: String
/// 原本地示例视频标识。
let sourceVideoID: String
/// 作品归属点位。
let pointID: String
/// 上传时的点位名称。
let pointName: String
/// 作品展示名称。
let title: String
/// 本地示例文件名。
let fileName: String
/// 本地封面资源。
let previewAssetName: String
/// 本地示例视频文件,缺失时只显示封面。
let previewURL: URL?
/// 本地示例时长。
let durationText: String
/// 演示文件大小。
let sizeText: String
/// 本机演示成功的时间,不作为真实云端凭证。
let deliveredAt: Date
/// 当前始终为 true,避免将演示作品冒充真实交付。
let isSimulation: Bool
/// 通过既有素材预览组件打开本地示例。
var previewMaterial: DroneMaterial {
DroneMaterial(id: id, title: title, kind: .video, previewAssetName: previewAssetName,
previewURL: previewURL, durationText: durationText)
}
}
/// 整单清单按点位汇总,包含各次成功上传的作品。
struct DroneDeliveryWorkGroup: Hashable, Sendable {
/// 分组稳定身份。
var id: String { pointID }
/// 所属点位。
let pointID: String
/// 点位展示名称。
let pointName: String
/// 本点全部成功作品或某次确认快照中的作品。
let works: [DroneDeliveryWork]
}
/// 商家核对和游客演示确认的不同阶段,不由刷新推断推进。
enum DroneDeliveryConfirmationPhase: Hashable, Sendable {
case review, awaitingConfirmation, viewing, feedback, confirmed
/// 确认区域展示名称。
var title: String {
switch self {
case .review: "请先核对整单交付"
case .awaitingConfirmation: "待游客确认 · 演示"
case .viewing: "演示查看中"
case .feedback: "成片问题待处理 · 演示"
case .confirmed: "游客已确认 · 演示"
}
}
}
/// 原型中的四类成片问题,反馈不等于确认收货。
enum DroneDeliveryFeedbackKind: String, CaseIterable, Hashable, Sendable {
case missingVideo, unplayable, quality, other
/// 问题选项标题。
var title: String {
switch self {
case .missingVideo: "视频缺失"
case .unplayable: "无法播放"
case .quality: "成片效果有异议"
case .other: "其他问题"
}
}
}
/// 本机演示反馈记录,不发送真实消息。
struct DroneDeliveryFeedback: Hashable, Sendable {
/// 选择的问题类型。
let kind: DroneDeliveryFeedbackKind
/// 可选补充说明。
let note: String
/// 本机演示提交时间。
let createdAt: Date
}
/// 某一交付版本的确认会话,作品清单一经创建便不可替换。
struct DroneDeliveryConfirmationSession: Hashable, Sendable {
/// 单次确认令牌,其他订单和旧版本回执不能复用。
let id: UUID
/// 确认创建时的整单作品版本。
let revision: Int
/// 创建会话时的订单身份快照。
let orderID: String
/// 可见订单号快照。
let orderNumber: String
/// 创建时游客脱敏名称,不随后续资料改变。
let visitorName: String
/// 发起整单核对的工作人员名称快照。
let operatorName: String
/// 创建会话时的景区名称。
let scenicName: String
/// 创建时全部作品的值类型快照,追加作品不改变此清单。
let works: [DroneDeliveryWork]
/// 商家完成核对并创建会话的本机时间。
let createdAt: Date
/// 只有明确 Debug 事件才推进状态。
var status: DroneDeliveryConfirmationPhase
/// 明确模拟主动确认回执的时间。
var confirmedAt: Date?
/// 最近一次演示问题反馈。
var feedback: DroneDeliveryFeedback?
/// 本次演示查看中是否主动勾选已核对全部作品。
var visitorAcknowledged: Bool
/// 供本机占位码使用的演示文本,不是网页链接或真实收货凭据。
var demoCodeText: String { "SUIXINKAN-DEMO-\(id.uuidString)" }
}
/// 游客状态仅由显式 Debug 模拟回执产生,不实现游客原生网页。
enum DroneDeliveryConfirmationEvent: Hashable, Sendable {
case viewing, confirmed, feedback(kind: DroneDeliveryFeedbackKind, note: String)
}
/// 订单交付共享内存状态,景区及工作人员范围由缓存键隔离。
struct DroneDeliveryLibraryState {
/// 整单成功作品,各批次追加而不互相覆盖。
var works: [DroneDeliveryWork] = []
/// 每次新增成功作品递增,避免旧核对覆盖新清单。
var revision: Int = 0
/// 当前点位上传队列。
var batch: DroneDeliveryUploadBatch?
/// 商家明确核对的版本,新作品追加时失效。
var merchantReviewedRevision: Int?
/// 所有历史确认会话,旧清单和已确认记录保留。
var sessions: [DroneDeliveryConfirmationSession] = []
/// 当前版本的确认会话身份,新作品追加时清空。
var currentSessionID: UUID?
}
#if DEBUG
/// 交付流程的本地显式验收场景。
enum DroneDeliveryScenario: String, CaseIterable, Hashable {
case empty, ready, uploading, paused, partialFailure, completed, awaitingConfirmation, viewing, feedback, confirmed
/// 场景菜单名称。
var title: String {
switch self {
case .empty: "暂无交付作品"
case .ready: "点位与演示视频选择"
case .uploading: "成片上传中"
case .paused: "上传暂停待继续"
case .partialFailure: "部分上传失败"
case .completed: "本批演示交付完成"
case .awaitingConfirmation: "整单待游客确认"
case .viewing: "演示查看中"
case .feedback: "成片问题反馈"
case .confirmed: "已确认的演示记录"
}
}
}
#endif
@@ -207,7 +207,7 @@ enum DroneShootingMaterialState: Hashable, Sendable {
}
}
/// 新版卡片中游客确认摘要的静态展示状态;本期不实现交付流程。
/// 订单卡中的游客确认摘要,与交付清单及确认会话快照分别保存。
enum DroneVisitorConfirmationState: Hashable, Sendable {
case none, awaitingConfirmation, confirmed
@@ -0,0 +1,433 @@
import Foundation
/// 本地成片上传与整单确认规则;不访问网络、系统相册或真实游客服务。
final class DroneDeliveryViewModel {
/// 与机巢、订单及原素材页面共享的数据源。
let store: DroneDockDemoStore
/// 固定入口订单,避免列表位置变化后操作其他订单。
let orderID: String
/// 用户为下一批明确选择的点位;整单入口初始不自动选点。
private(set) var selectedPointID: String?
/// 用户选择的本地示例视频,不读取相册。
private(set) var selectedVideoIDs: Set<String> = []
private let context: DroneDockContext
private let now: () -> Date
/// 当前景区、工作人员范围内可访问的入口订单。
var order: DroneShootingOrder? { isCurrentContext ? store.shootingOrder(id: orderID) : nil }
/// 配置允许选择的点位,上传不受拍摄距离约束。
var points: [DroneShootingPoint] { order != nil ? store.shootingPreparations[key]?.points ?? [] : [] }
/// 当前明确选择的有效点位。
var selectedPoint: DroneShootingPoint? { points.first { $0.id == selectedPointID } }
/// 本点尚未成功交付的四个本地视频样例。
var availableVideos: [DroneDeliveryVideo] {
guard let point = selectedPoint else { return [] }
let uploadedSources = Set(works.filter { $0.pointID == point.id }.map(\.sourceVideoID))
return Self.demoVideos(pointName: point.name).filter { !uploadedSources.contains($0.id) }
}
/// 当前人工选择的视频数量。
var selectedVideoCount: Int { selectedVideoIDs.count }
/// 上传队列未清除前冻结点位与选择,包括失败结果页。
var isUploadLocked: Bool { batch != nil }
/// 点位和至少一个视频均已明确选择才可开始。
var canStartUpload: Bool { order != nil && batch == nil && selectedPoint != nil && selectedVideoCount > 0 }
/// 当前共享上传队列及执行令牌。
var batch: DroneDeliveryUploadBatch? { library?.batch }
/// 本批成功项数,不代表整单交齐或游客确认。
var uploadedCount: Int { batch?.items.filter { $0.state.isCompleted }.count ?? 0 }
/// 本批明确失败项数。
var failedCount: Int { batch?.items.filter { $0.state.isFailed }.count ?? 0 }
/// 本批仍需继续的文件数,不包括明确失败项。
var pendingCount: Int { batch?.items.filter { !$0.state.isCompleted && !$0.state.isFailed }.count ?? 0 }
/// 本批固定文件总数。
var totalUploadCount: Int { batch?.items.count ?? 0 }
/// 完成文件数量占比,不从虚构网络数据推断交付成功。
var uploadProgress: Double { totalUploadCount == 0 ? 0 : Double(uploadedCount) / Double(totalUploadCount) }
/// 上传底栏使用的阶段。
var uploadPhase: DroneDeliveryUploadPhase {
guard let batch else { return .idle }
if batch.isPaused && pendingCount > 0 { return .paused }
if batch.items.contains(where: { if case .uploading = $0.state { return true }; return false }) { return .uploading }
if failedCount > 0 { return .partialFailure }
return uploadedCount == totalUploadCount ? .completed : .idle
}
/// 所有批次成功交付的本机演示作品。
var works: [DroneDeliveryWork] { library?.works ?? [] }
/// 当前整单成功作品按点位汇总。
var workGroups: [DroneDeliveryWorkGroup] { Self.groups(works) }
/// 当前版本是否由商家明确勾选交齐,新作品成功追加会清除此勾选。
var isAllDeliveredReviewed: Bool {
guard let state = library else { return false }
return !state.works.isEmpty && state.merchantReviewedRevision == state.revision
}
/// 有成功作品、没有未结束上传且明确勾选交齐后才可创建整单确认。
var canCreateConfirmation: Bool { canReviewCurrentWorks && isAllDeliveredReviewed }
/// 当前作品版本的有效确认会话,旧清单仍保留在历史中。
var confirmationSession: DroneDeliveryConfirmationSession? {
guard let state = library, let id = state.currentSessionID else { return nil }
return state.sessions.first { $0.id == id && $0.revision == state.revision }
}
/// 核对、等待、查看、反馈和确认保持独立,不由刷新自动推进。
var confirmationPhase: DroneDeliveryConfirmationPhase { confirmationSession?.status ?? .review }
/// 当前确认会话冻结清单按点位分组。
var confirmationGroups: [DroneDeliveryWorkGroup] { Self.groups(confirmationSession?.works ?? []) }
/// 历次已明确模拟确认的记录,追加作品后原快照仍保留。
var confirmationRecords: [DroneDeliveryConfirmationSession] {
(library?.sessions ?? []).enumerated().filter { $0.element.status == .confirmed }.sorted {
let firstDate = $0.element.confirmedAt ?? $0.element.createdAt
let secondDate = $1.element.confirmedAt ?? $1.element.createdAt
return firstDate == secondDate ? $0.offset > $1.offset : firstDate > secondDate
}.map(\.element)
}
/// 最近一次已确认的本机演示凭据,不冒充真实收货证明。
var latestReceipt: DroneDeliveryConfirmationSession? { confirmationRecords.first }
/// 最近已确认快照的分点清单。
var receiptGroups: [DroneDeliveryWorkGroup] { Self.groups(latestReceipt?.works ?? []) }
private var isCurrentContext: Bool { store.context == context }
private var key: DroneShootingSessionKey { DroneShootingSessionKey(context: context, orderID: orderID) }
private var library: DroneDeliveryLibraryState? { order != nil ? store.deliveryLibraries[key] : nil }
private var canReviewCurrentWorks: Bool { order != nil && !works.isEmpty && pendingCount == 0 && failedCount == 0 }
/// 指定入口订单和可选预选点位,时钟可注入以测试确认时间。
init(store: DroneDockDemoStore, orderID: String, pointID: String? = nil, now: @escaping () -> Date = Date.init) {
self.store = store
self.orderID = orderID
selectedPointID = pointID
context = store.context
self.now = now
refresh()
}
/// 主动读取共享状态;已存在交付摘要首次生成相应作品及确认快照。
func refresh() {
guard isCurrentContext, let order else {
pauseStoredUpload(reason: .leavingPage)
selectedVideoIDs = []
return
}
store.ensureShootingPreparation(orderID: orderID)
if store.deliveryLibraries[key] == nil {
store.deliveryLibraries[key] = initialState(order: order)
}
if let batch { selectedPointID = batch.pointID }
else if !points.contains(where: { $0.id == selectedPointID }) { selectedPointID = nil }
if batch == nil { selectedVideoIDs.formIntersection(Set(availableVideos.map(\.id))) }
projectOrderSummary()
}
/// 点位改变清空旧视频勾选,进行中的固定批次不能改点。
func selectPoint(id: String) {
guard !isUploadLocked, points.contains(where: { $0.id == id }), selectedPointID != id else { return }
selectedPointID = id
selectedVideoIDs = []
}
/// 独立切换本点仍可上传的视频选择。
func toggleVideo(id: String) {
guard !isUploadLocked, availableVideos.contains(where: { $0.id == id }) else { return }
if !selectedVideoIDs.insert(id).inserted { selectedVideoIDs.remove(id) }
}
/// 开始本地演示批次,只冻结已选文件,不表示真实云端已上传。
@discardableResult
func startUpload() -> Bool {
guard canStartUpload, let point = selectedPoint, var state = library else { return false }
let videos = availableVideos.filter { selectedVideoIDs.contains($0.id) }
guard !videos.isEmpty else { return false }
state.batch = DroneDeliveryUploadBatch(id: UUID(), pointID: point.id, pointName: point.name,
items: videos.map { DroneDeliveryUploadItem(id: UUID().uuidString, video: $0, state: .uploading(progress: 0)) },
isPaused: false, pauseReason: nil)
store.deliveryLibraries[key] = state
return true
}
/// 后台、锁屏或离页停止未完成执行,已成功作品始终保留。
func pauseUpload(reason: DroneDeliveryPauseReason) {
guard isCurrentContext else { return }
pauseStoredUpload(reason: reason)
}
/// 用户手动继续仅处理未完成项,失败项需单独重试。
@discardableResult
func continueUpload() -> Bool {
guard var state = library, let old = state.batch, old.isPaused, pendingCount > 0 else { return false }
let items = old.items.map { item -> DroneDeliveryUploadItem in
var item = item
if item.state == .paused { item.state = .uploading(progress: 0) }
return item
}
state.batch = renewedBatch(old, items: items, isPaused: false, reason: nil)
store.deliveryLibraries[key] = state
return true
}
/// 仅重试明确失败的文件;已成功作品不会再次加入或上传。
@discardableResult
func retryFailedUploads() -> Bool {
guard var state = library, let old = state.batch, pendingCount == 0, failedCount > 0 else { return false }
let items = old.items.map { item -> DroneDeliveryUploadItem in
var item = item
if item.state.isFailed { item.state = .uploading(progress: 0) }
return item
}
state.batch = renewedBatch(old, items: items, isPaused: false, reason: nil)
store.deliveryLibraries[key] = state
return true
}
/// 明确结束已完成或失败的批次后继续同一点追加;成功作品不受影响。
func clearUploadBatch() {
guard var state = library, state.batch != nil, pendingCount == 0 else { return }
state.batch = nil
store.deliveryLibraries[key] = state
selectedVideoIDs = []
}
/// 接收本地上传回执,校验上下文、批次令牌及单项状态后才追加作品。
func receiveUpload(_ event: DroneDeliveryUploadEvent, itemID: String, batchID: UUID) {
guard var state = library, var batch = state.batch, batch.id == batchID, !batch.isPaused,
let index = batch.items.firstIndex(where: { $0.id == itemID }),
case .uploading(let previous) = batch.items[index].state else { return }
let item = batch.items[index]
switch event {
case .progress(let value):
guard value.isFinite else { return }
batch.items[index].state = .uploading(progress: max(previous, min(1, max(0, value))))
case .failed(let message): batch.items[index].state = .failed(message: message)
case .succeeded:
batch.items[index].state = .completed
if !state.works.contains(where: { $0.id == item.id || ($0.pointID == batch.pointID && $0.sourceVideoID == item.video.id) }) {
state.works.append(Self.work(item: item, pointID: batch.pointID, pointName: batch.pointName, date: now()))
state.revision += 1
state.merchantReviewedRevision = nil
state.currentSessionID = nil
}
}
state.batch = batch
store.deliveryLibraries[key] = state
projectOrderSummary()
}
/// 商家明确核对本版本全部成功作品,不由上传完成自动勾选。
func setAllDeliveredReviewed(_ checked: Bool) {
guard var state = library else { return }
state.merchantReviewedRevision = checked && canReviewCurrentWorks ? state.revision : nil
store.deliveryLibraries[key] = state
}
/// 为当前整单清单创建不可替换的本机演示确认会话,重复点击复用同一会话。
@discardableResult
func createConfirmationSession() -> Bool {
guard canCreateConfirmation, var state = library, let order else { return false }
if confirmationSession != nil { return true }
let session = makeSession(works: state.works, revision: state.revision, order: order)
state.sessions.append(session)
state.currentSessionID = session.id
store.deliveryLibraries[key] = state
projectOrderSummary()
return true
}
/// 只刷新共享状态,不推断游客已经查看或已经确认。
func refreshConfirmation() { refresh() }
/// 明确回到商家核对并废弃当前令牌,历史清单与已确认记录仍保留。
func beginNewReview() {
guard var state = library else { return }
state.currentSessionID = nil
state.merchantReviewedRevision = nil
store.deliveryLibraries[key] = state
projectOrderSummary()
}
private func pauseStoredUpload(reason: DroneDeliveryPauseReason) {
guard var state = store.deliveryLibraries[key], let old = state.batch,
old.items.contains(where: { !$0.state.isCompleted && !$0.state.isFailed }) else { return }
let items = old.items.map { item -> DroneDeliveryUploadItem in
var item = item
if case .uploading = item.state { item.state = .paused }
return item
}
state.batch = renewedBatch(old, items: items, isPaused: true, reason: reason)
store.deliveryLibraries[key] = state
}
private func renewedBatch(_ old: DroneDeliveryUploadBatch, items: [DroneDeliveryUploadItem],
isPaused: Bool, reason: DroneDeliveryPauseReason?) -> DroneDeliveryUploadBatch {
DroneDeliveryUploadBatch(id: UUID(), pointID: old.pointID, pointName: old.pointName,
items: items, isPaused: isPaused, pauseReason: reason)
}
private func projectOrderSummary() {
guard let state = library, let order else { return }
let confirmation: DroneVisitorConfirmationState
if state.works.isEmpty { confirmation = .none }
else if confirmationSession?.status == .confirmed { confirmation = .confirmed }
else { confirmation = state.sessions.isEmpty ? .none : .awaitingConfirmation }
store.replaceShootingOrder(order.replacingDeliverySummary(count: state.works.count, confirmation: confirmation))
}
private func initialState(order: DroneShootingOrder) -> DroneDeliveryLibraryState {
var state = DroneDeliveryLibraryState()
guard order.deliveredVideoCount > 0 else { return state }
state.works = seededWorks(count: order.deliveredVideoCount)
state.revision = 1
if order.visitorConfirmationState != .none {
var session = makeSession(works: state.works, revision: state.revision, order: order)
if order.visitorConfirmationState == .confirmed {
session.status = .confirmed
session.visitorAcknowledged = true
session.confirmedAt = now()
}
state.sessions = [session]
state.currentSessionID = session.id
state.merchantReviewedRevision = state.revision
}
return state
}
private func makeSession(works: [DroneDeliveryWork], revision: Int, order: DroneShootingOrder) -> DroneDeliveryConfirmationSession {
DroneDeliveryConfirmationSession(id: UUID(), revision: revision, orderID: order.id,
orderNumber: order.orderNumber, visitorName: order.customerName, operatorName: context.photographerName,
scenicName: context.scenicName, works: works, createdAt: now(), status: .awaitingConfirmation,
confirmedAt: nil, feedback: nil, visitorAcknowledged: false)
}
private func seededWorks(count: Int) -> [DroneDeliveryWork] {
guard count > 0 else { return [] }
let knownPoints = points
return (0..<count).map { index in
let point = knownPoints.isEmpty ? nil : knownPoints[min(index / 2, knownPoints.count - 1)]
let video = Self.demoVideos(pointName: point?.name ?? "三皇寨")[index % 4]
let item = DroneDeliveryUploadItem(id: "\(orderID)-existing-work-\(index + 1)",
video: DroneDeliveryVideo(id: "existing-source-\(index + 1)", title: video.title, fileName: video.fileName,
previewAssetName: video.previewAssetName, previewURL: video.previewURL,
durationText: video.durationText, sizeText: video.sizeText), state: .completed)
return Self.work(item: item, pointID: point?.id ?? "point-sanhuang", pointName: point?.name ?? "三皇寨",
date: Date(timeIntervalSince1970: 1_792_723_000 + Double(index)))
}
}
private static func work(item: DroneDeliveryUploadItem, pointID: String, pointName: String, date: Date) -> DroneDeliveryWork {
DroneDeliveryWork(id: item.id, sourceVideoID: item.video.id, pointID: pointID, pointName: pointName,
title: item.video.title, fileName: item.video.fileName, previewAssetName: item.video.previewAssetName,
previewURL: item.video.previewURL, durationText: item.video.durationText, sizeText: item.video.sizeText,
deliveredAt: date, isSimulation: true)
}
private static func groups(_ works: [DroneDeliveryWork]) -> [DroneDeliveryWorkGroup] {
var pointIDs: [String] = []
var grouped: [String: [DroneDeliveryWork]] = [:]
for work in works {
if grouped[work.pointID] == nil { pointIDs.append(work.pointID) }
grouped[work.pointID, default: []].append(work)
}
return pointIDs.compactMap { id in
guard let items = grouped[id], let first = items.first else { return nil }
return DroneDeliveryWorkGroup(pointID: id, pointName: first.pointName, works: items)
}
}
private static func demoVideos(pointName: String) -> [DroneDeliveryVideo] {
let url = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
let assets = ["drone_demo_tourists", "drone_demo_mountain", "drone_demo_pagoda", "drone_demo_tourists"]
return (1...4).map { index in
let number = String(format: "%02d", index)
return DroneDeliveryVideo(id: "demo-video-\(index)", title: "成片视频 \(number)",
fileName: "\(pointName)_成片\(number).mp4", previewAssetName: assets[index - 1],
previewURL: url, durationText: "00:03", sizeText: "本地演示文件")
}
}
#if DEBUG
/// 演示游客主动勾选当前冻结清单,关闭或刷新不会代为勾选。
func setVisitorAcknowledged(_ checked: Bool) {
guard var state = library, let session = confirmationSession, session.status == .viewing,
let index = state.sessions.firstIndex(where: { $0.id == session.id }) else { return }
state.sessions[index].visitorAcknowledged = checked
store.deliveryLibraries[key] = state
}
/// 只在 Debug 注入游客演示回执,旧会话或旧作品版本永不修改当前确认结果。
func receiveConfirmation(_ event: DroneDeliveryConfirmationEvent, sessionID: UUID) {
guard var state = library, let session = confirmationSession, session.id == sessionID,
session.status != .confirmed,
let index = state.sessions.firstIndex(where: { $0.id == sessionID }) else { return }
switch event {
case .viewing:
guard session.status == .awaitingConfirmation || session.status == .feedback else { return }
state.sessions[index].status = .viewing
state.sessions[index].visitorAcknowledged = false
case .confirmed:
guard session.status == .viewing, session.visitorAcknowledged else { return }
state.sessions[index].status = .confirmed
state.sessions[index].confirmedAt = now()
case .feedback(let kind, let note):
guard session.status == .viewing else { return }
let trimmed = String(note.trimmingCharacters(in: .whitespacesAndNewlines).prefix(500))
guard kind != .other || !trimmed.isEmpty else { return }
state.sessions[index].status = .feedback
state.sessions[index].visitorAcknowledged = false
state.sessions[index].feedback = DroneDeliveryFeedback(kind: kind, note: trimmed, createdAt: now())
}
store.deliveryLibraries[key] = state
projectOrderSummary()
}
/// 仅本地替换交付验收状态,保留拍摄额度、任务、原素材和订单归类。
func applyScenario(_ scenario: DroneDeliveryScenario) {
guard let order else { return }
var state = library ?? initialState(order: order)
state.batch = nil
if scenario == .empty { state = DroneDeliveryLibraryState() }
store.deliveryLibraries[key] = state
selectedVideoIDs = []
switch scenario {
case .empty, .ready: break
case .uploading, .paused, .partialFailure, .completed:
if selectedPoint == nil { selectedPointID = points.first?.id }
let chosen = Array(availableVideos.prefix(2))
selectedVideoIDs = Set(chosen.map(\.id))
guard startUpload(), let batch else { projectOrderSummary(); return }
if scenario == .uploading { break }
if let first = batch.items.first { receiveUpload(.succeeded, itemID: first.id, batchID: batch.id) }
if scenario == .paused { pauseUpload(reason: .background) }
else {
for item in batch.items.dropFirst() {
receiveUpload(scenario == .partialFailure ? .failed(message: "演示连接中断") : .succeeded,
itemID: item.id, batchID: batch.id)
}
}
case .awaitingConfirmation, .viewing, .feedback, .confirmed:
if state.works.isEmpty {
state.works = seededWorks(count: 3)
state.revision += 1
store.deliveryLibraries[key] = state
}
beginNewReview()
setAllDeliveredReviewed(true)
guard createConfirmationSession(), let session = confirmationSession else { return }
if scenario != .awaitingConfirmation { receiveConfirmation(.viewing, sessionID: session.id) }
if scenario == .feedback { receiveConfirmation(.feedback(kind: .unplayable, note: "演示:有一个视频无法播放"), sessionID: session.id) }
if scenario == .confirmed {
setVisitorAcknowledged(true)
receiveConfirmation(.confirmed, sessionID: session.id)
}
}
projectOrderSummary()
}
#endif
}
/// 复制订单交付摘要,拍摄次数、当前任务和原素材状态原样保留。
extension DroneShootingOrder {
/// 只更新成功作品数和游客确认标签,不改变订单履约归类。
func replacingDeliverySummary(count: Int, confirmation: DroneVisitorConfirmationState) -> DroneShootingOrder {
DroneShootingOrder(id: id, scenicID: scenicID, assignedUserID: assignedUserID, customerName: customerName,
orderNumber: orderNumber, createdAtText: createdAtText, packageName: packageName,
totalShootingCount: totalShootingCount, successfulShootingCount: successfulShootingCount,
activeTask: activeTask, needsRepreparation: needsRepreparation, materialState: materialState,
deliveredVideoCount: max(0, count), visitorConfirmationState: confirmation)
}
}
@@ -14,6 +14,8 @@ final class DroneDockDemoStore {
var shootingSessions: [DroneShootingSessionKey: DroneShootingSession] = [:]
/// 原素材和本机演示下载结果按上下文、订单隔离,页面重进时仍可读取。
var materialLibraries: [DroneShootingSessionKey: DroneMaterialLibraryState] = [:]
/// 成片上传和整单确认快照按上下文、订单隔离,不与原素材下载共用状态。
var deliveryLibraries: [DroneShootingSessionKey: DroneDeliveryLibraryState] = [:]
#if DEBUG
/// 预览切换前的订单,恢复正常场景时不累计演示扣次。
var shootingScenarioBaselines: [DroneShootingSessionKey: DroneShootingOrder] = [:]
@@ -81,6 +83,7 @@ final class DroneDockDemoStore {
shootingSessions = shootingSessions.filter { $0.key.context != context }
shootingScenarioBaselines = shootingScenarioBaselines.filter { $0.key.context != context }
materialLibraries = materialLibraries.filter { $0.key.context != context }
deliveryLibraries = deliveryLibraries.filter { $0.key.context != context }
var orders = DroneDockDemoData.orders(context: context)
var devices = DroneDockDemoData.devices()
switch scenario {
@@ -36,6 +36,7 @@ enum HomeMenuCatalog {
HomeMenuItem(uri: "photographer_invite", title: "邀请摄影师", iconName: "envelope.open.fill"),
HomeMenuItem(uri: "invite_record", title: "邀请记录", iconName: "list.bullet.rectangle.fill"),
HomeMenuItem(uri: "store", title: "店铺管理", iconName: "building.2.fill"),
HomeMenuItem(uri: "drone_dock", title: "机巢工作台", iconName: "airplane.circle.fill"),
HomeMenuItem(uri: "fly", title: "飞行管理", iconName: "paperplane.fill"),
HomeMenuItem(uri: "pilot_cert", title: "飞手认证", iconName: "paperplane.fill"),
HomeMenuItem(uri: "pilot_controller", title: "飞控", iconName: "paperplane.fill"),
@@ -68,6 +68,8 @@ enum HomeRouteHandler {
viewController.navigationController?.pushViewController(InviteRecordViewController(), animated: true)
case "/scenic-queue":
viewController.navigationController?.pushViewController(ScenicQueueViewController(), animated: true)
case "drone_dock":
viewController.navigationController?.pushViewController(DroneDockWorkbenchViewController(), animated: true)
case "task_management", "task_management_editor":
viewController.navigationController?.pushViewController(TaskAddViewController(), animated: true)
case "travel_album":
@@ -0,0 +1,51 @@
import Foundation
/// 本地成片上传的 UI 演示驱动;不访问云存储、不读取相册或真实文件内容。
@MainActor
final class DroneDeliveryDemoUploadDriver {
private var task: Task<Void, Never>?
private var runningBatchID: UUID?
/// 推进固定批次的明确演示回执,已成功和失败项不重复处理。
func start(viewModel: DroneDeliveryViewModel, onTransferUpdate: @escaping () -> Void) {
guard let batch = viewModel.batch, viewModel.uploadPhase == .uploading else { return }
guard runningBatchID != batch.id || task == nil else { return }
stop()
let batchID = batch.id
runningBatchID = batchID
task = Task { @MainActor [weak self, weak viewModel] in
guard let self, let viewModel else { return }
defer {
if self.runningBatchID == batchID {
self.task = nil
self.runningBatchID = nil
}
}
for item in batch.items {
guard self.isCurrent(viewModel, batchID: batchID) else { return }
guard case .uploading = item.state else { continue }
for progress in [0.2, 0.45, 0.7, 1.0] {
do { try await Task.sleep(nanoseconds: 240_000_000) } catch { return }
guard self.isCurrent(viewModel, batchID: batchID) else { return }
viewModel.receiveUpload(.progress(progress), itemID: item.id, batchID: batchID)
onTransferUpdate()
}
guard self.isCurrent(viewModel, batchID: batchID) else { return }
viewModel.receiveUpload(.succeeded, itemID: item.id, batchID: batchID)
onTransferUpdate()
}
}
}
/// 停止后续回执;生命周期处理方同时暂停 ViewModel,使旧令牌失效。
func stop() {
task?.cancel()
task = nil
runningBatchID = nil
}
private func isCurrent(_ viewModel: DroneDeliveryViewModel, batchID: UUID) -> Bool {
!Task.isCancelled && runningBatchID == batchID && viewModel.batch?.id == batchID
&& viewModel.uploadPhase == .uploading
}
}
@@ -0,0 +1,436 @@
import SnapKit
import UIKit
/// 核对页与确认记录共用的整单抬头,不把拍摄履约状态混入成片确认。
@MainActor
final class DroneDeliveryReviewOrderCell: UICollectionViewCell {
private let nameLabel = DroneDockStyle.label(size: 18, weight: .semibold)
private let numberLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let badgeLabel = DroneDockStatusLabel()
override init(frame: CGRect) {
super.init(frame: frame)
badgeLabel.apply(title: "整单确认", tone: .blue)
let row = UIStackView(arrangedSubviews: [nameLabel, UIView(), badgeLabel])
row.alignment = .center
row.spacing = 10
let stack = UIStackView(arrangedSubviews: [row, numberLabel])
stack.axis = .vertical
stack.spacing = 7
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.leading.trailing.equalToSuperview(); make.top.bottom.equalToSuperview().inset(18) }
let divider = UIView()
divider.backgroundColor = DroneDockStyle.border
contentView.addSubview(divider)
divider.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(1) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 展示订单身份,整单确认不按入口点位缩小清单。
func apply(customer: String, orderNumber: String) {
nameLabel.text = customer
numberLabel.text = orderNumber
accessibilityIdentifier = "drone.delivery.review.order"
}
}
/// 核对提示、清单标题和演示说明共用的文字单元。
@MainActor
final class DroneDeliveryReviewTextCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let iconView = UIImageView()
private let row = UIStackView()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.numberOfLines = 0
detailLabel.numberOfLines = 0
iconView.tintColor = DroneDockStyle.primary
iconView.contentMode = .scaleAspectFit
iconView.backgroundColor = DroneDockStyle.primary.withAlphaComponent(0.06)
iconView.layer.cornerRadius = 10
iconView.snp.makeConstraints { make in make.size.equalTo(42).priority(999) }
let texts = UIStackView(arrangedSubviews: [titleLabel, detailLabel])
texts.axis = .vertical
texts.spacing = 5
row.addArrangedSubview(iconView)
row.addArrangedSubview(texts)
row.alignment = .center
row.spacing = 12
contentView.addSubview(row)
row.snp.makeConstraints { make in make.leading.trailing.equalToSuperview(); make.top.bottom.equalToSuperview().inset(14) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 应用语义明确的标题和说明,可选图标仅用于核对引导。
func apply(title: String?, detail: String?, symbol: String? = nil) {
titleLabel.text = title
titleLabel.isHidden = title == nil
detailLabel.text = detail
detailLabel.isHidden = detail == nil
iconView.isHidden = symbol == nil
iconView.image = symbol.flatMap { UIImage(systemName: $0, withConfiguration: UIImage.SymbolConfiguration(pointSize: 23)) }
}
}
/// 整单已交付作品与覆盖点位数量,统计范围由 ViewModel 提供。
@MainActor
final class DroneDeliveryReviewStatisticsCell: UICollectionViewCell {
private let countLabel = UILabel()
private let pointLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = DroneDockStyle.primary.withAlphaComponent(0.055)
contentView.layer.cornerRadius = 11
countLabel.numberOfLines = 0
pointLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
let row = UIStackView(arrangedSubviews: [countLabel, UIView(), pointLabel])
row.alignment = .center
row.spacing = 8
contentView.addSubview(row)
row.snp.makeConstraints { make in make.edges.equalToSuperview().inset(15) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 显示整单所有上传批次的作品数量,不以本次上传数代替。
func apply(workCount: Int, pointCount: Int) {
let text = NSMutableAttributedString(string: "本订单已交付 ", attributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: DroneDockStyle.secondary])
text.append(NSAttributedString(string: "\(workCount)", attributes: [.font: UIFont.systemFont(ofSize: 25, weight: .semibold), .foregroundColor: DroneDockStyle.primary]))
text.append(NSAttributedString(string: " 个成片", attributes: [.font: UIFont.systemFont(ofSize: 12, weight: .medium), .foregroundColor: DroneDockStyle.primary]))
countLabel.attributedText = text
pointLabel.text = "覆盖 \(pointCount) 个打卡点"
accessibilityIdentifier = "drone.delivery.review.statistics"
accessibilityLabel = "本订单已交付\(workCount)个成片,覆盖\(pointCount)个打卡点"
}
}
/// 单个打卡点的成片分组标题,核对页和冻结记录复用同一布局。
@MainActor
final class DroneDeliveryReviewPointHeader: UICollectionReusableView {
private let titleLabel = DroneDockStyle.label(size: 14, weight: .semibold)
private let countLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
let row = UIStackView(arrangedSubviews: [titleLabel, UIView(), countLabel])
row.alignment = .center
row.spacing = 8
addSubview(row)
row.snp.makeConstraints { make in make.leading.trailing.equalToSuperview(); make.centerY.equalToSuperview() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 只显示当前分组快照的名称与作品数。
func apply(pointName: String, workCount: Int) {
titleLabel.text = pointName
countLabel.text = "\(workCount) 个视频"
}
}
/// 两列成片封面,点击仅提出预览请求,不修改核对或游客确认状态。
@MainActor
final class DroneDeliveryReviewWorkCell: UICollectionViewCell {
/// 点击封面或文件名时请求只读预览。
var onPreviewTap: (() -> Void)?
private let imageView = UIImageView()
private let durationLabel = UILabel()
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
private let fileLabel = DroneDockStyle.label(size: 10, color: DroneDockStyle.secondary)
private let previewButton = UIButton(type: .custom)
override init(frame: CGRect) {
super.init(frame: frame)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.cornerRadius = 7
imageView.backgroundColor = DroneDockStyle.background
durationLabel.font = .monospacedDigitSystemFont(ofSize: 10, weight: .medium)
durationLabel.textColor = .white
durationLabel.backgroundColor = UIColor.black.withAlphaComponent(0.48)
durationLabel.layer.cornerRadius = 3
durationLabel.clipsToBounds = true
durationLabel.textAlignment = .center
titleLabel.numberOfLines = 1
fileLabel.numberOfLines = 1
fileLabel.lineBreakMode = .byTruncatingMiddle
[imageView, durationLabel, titleLabel, fileLabel, previewButton].forEach(contentView.addSubview)
imageView.snp.makeConstraints { make in make.leading.trailing.top.equalToSuperview(); make.height.equalTo(imageView.snp.width).multipliedBy(0.57) }
durationLabel.snp.makeConstraints { make in make.bottom.trailing.equalTo(imageView).inset(5); make.width.greaterThanOrEqualTo(38); make.height.equalTo(19) }
titleLabel.snp.makeConstraints { make in make.top.equalTo(imageView.snp.bottom).offset(7); make.leading.trailing.equalToSuperview() }
fileLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(4); make.leading.trailing.equalToSuperview(); make.bottom.lessThanOrEqualToSuperview().inset(2) }
previewButton.snp.makeConstraints { make in make.edges.equalToSuperview() }
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func prepareForReuse() {
super.prepareForReuse()
onPreviewTap = nil
}
/// 本地封面与时长始终明确属于演示作品。
func apply(id: String, title: String, fileName: String, previewAssetName: String, durationText: String) {
imageView.image = UIImage(named: previewAssetName)
titleLabel.text = title
fileLabel.text = fileName
durationLabel.text = durationText
previewButton.accessibilityIdentifier = "drone.delivery.review.preview.\(id)"
previewButton.accessibilityLabel = "预览\(title),本地演示成片"
}
@objc private func previewTapped() { onPreviewTap?() }
}
/// 订单确认码演示面板;图案没有编码任何游客地址,不提供真实扫码服务。
@MainActor
final class DroneDeliveryConfirmationCodeCell: UICollectionViewCell {
private let statusLabel = DroneDockStatusLabel()
private let titleLabel = DroneDockStyle.label(size: 21, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
private let codeView = DroneDeliveryDemoCodeView()
private let countLabel = DroneDockStyle.label(size: 13, weight: .medium)
private let explanationLabel = DroneDockStyle.label("扫描不等于收货,需游客本人主动确认", size: 11, color: DroneDockStyle.secondary)
private let demoLabel = DroneDockStyle.label("仅供本机交互演示 · 不连接游客手机", size: 12, weight: .medium, color: DroneDockStyle.primary)
private let feedbackLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.warning)
override init(frame: CGRect) {
super.init(frame: frame)
contentView.layer.cornerRadius = 15
contentView.layer.borderWidth = 1
contentView.layer.borderColor = DroneDockStyle.border.cgColor
contentView.backgroundColor = DroneDockStyle.primary.withAlphaComponent(0.025)
[titleLabel, detailLabel, countLabel, explanationLabel, demoLabel, feedbackLabel].forEach { $0.textAlignment = .center; $0.numberOfLines = 0 }
let stack = UIStackView(arrangedSubviews: [statusLabel, titleLabel, detailLabel, codeView, countLabel, explanationLabel, demoLabel, feedbackLabel])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 13
stack.setCustomSpacing(20, after: detailLabel)
codeView.snp.makeConstraints { make in make.size.equalTo(202) }
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.edges.equalToSuperview().inset(20) }
[titleLabel, detailLabel, countLabel, explanationLabel, demoLabel, feedbackLabel].forEach { label in
label.snp.makeConstraints { make in make.width.equalTo(stack) }
}
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 仅展示当前确认快照数量;刷新状态不代替游客本人主动确认。
func apply(status: String, tone: DroneDockStatusTone, workCount: Int, pointCount: Int, feedback: String?) {
statusLabel.apply(title: status, tone: tone)
titleLabel.text = feedback == nil ? "请游客扫码确认收货" : "游客反馈待处理"
detailLabel.text = "查看本订单全部成片后,一次确认"
countLabel.text = "\(workCount) 个成片 · \(pointCount) 个打卡点"
feedbackLabel.text = feedback
feedbackLabel.isHidden = feedback == nil
accessibilityIdentifier = "drone.delivery.confirmation.code"
}
}
/// 不可扫码的本地演示图案,刻意不生成二维码数据或有效游客链接。
@MainActor
private final class DroneDeliveryDemoCodeView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
layer.cornerRadius = 12
layer.borderWidth = 1
layer.borderColor = DroneDockStyle.border.cgColor
isAccessibilityElement = true
accessibilityLabel = "订单确认演示图案,不支持真实扫码"
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else { return }
let gridCount = 25
let module = min(bounds.width, bounds.height) / 31
let origin = CGPoint(x: (bounds.width - CGFloat(gridCount) * module) / 2, y: (bounds.height - CGFloat(gridCount) * module) / 2)
context.setFillColor(UIColor.black.cgColor)
for row in 0..<gridCount {
for column in 0..<gridCount {
let inFinder = (row < 8 && column < 8) || (row < 8 && column > 16) || (row > 16 && column < 8)
guard !inFinder, (row * 13 + column * 7 + row * column) % 5 < 2 else { continue }
context.fill(CGRect(x: origin.x + CGFloat(column) * module, y: origin.y + CGFloat(row) * module, width: module, height: module))
}
}
for position in [CGPoint.zero, CGPoint(x: 18, y: 0), CGPoint(x: 0, y: 18)] {
let outer = CGRect(x: origin.x + position.x * module, y: origin.y + position.y * module, width: 7 * module, height: 7 * module)
context.setFillColor(UIColor.black.cgColor)
context.fill(outer)
context.setFillColor(UIColor.white.cgColor)
context.fill(outer.insetBy(dx: module, dy: module))
context.setFillColor(UIColor.black.cgColor)
context.fill(outer.insetBy(dx: 2 * module, dy: 2 * module))
}
let badge = CGRect(x: 10, y: bounds.midY - 24, width: bounds.width - 20, height: 48)
context.setFillColor(UIColor.white.cgColor)
context.fill(badge)
let text = "演示 · 不可扫码" as NSString
let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 15, weight: .semibold), .foregroundColor: DroneDockStyle.primary]
let size = text.size(withAttributes: attributes)
text.draw(at: CGPoint(x: bounds.midX - size.width / 2, y: bounds.midY - size.height / 2), withAttributes: attributes)
}
}
/// 游客确认回执的固定快照摘要,人员与时间由确认记录提供。
@MainActor
final class DroneDeliveryReceiptCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label("游客已确认收货", size: 21, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary)
private let metadataStack = UIStackView()
private let statementLabel = DroneDockStyle.label("我已查看本订单交付清单,确认收到上述全部成片。", size: 12, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
let icon = UIImageView(image: UIImage(systemName: "checkmark.circle.fill"))
icon.tintColor = DroneDockStyle.success
icon.contentMode = .scaleAspectFit
icon.snp.makeConstraints { make in make.size.equalTo(38) }
titleLabel.textAlignment = .center
detailLabel.textAlignment = .center
detailLabel.numberOfLines = 0
metadataStack.axis = .vertical
metadataStack.spacing = 14
let panel = UIView()
panel.backgroundColor = DroneDockStyle.background
panel.layer.cornerRadius = 10
panel.addSubview(metadataStack)
metadataStack.snp.makeConstraints { make in make.edges.equalToSuperview().inset(14) }
statementLabel.numberOfLines = 0
let statementTitle = DroneDockStyle.label("游客确认内容", size: 13, weight: .semibold)
let stack = UIStackView(arrangedSubviews: [icon, titleLabel, detailLabel, panel, statementTitle, statementLabel])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 14
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.leading.trailing.equalToSuperview(); make.top.bottom.equalToSuperview().inset(20) }
[panel, statementTitle, statementLabel].forEach { view in view.snp.makeConstraints { make in make.width.equalTo(stack) } }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 这些值来自确认时的记录,不读取当前追加后的作品数量或人员。
func apply(workCount: Int, pointCount: Int, visitor: String, confirmedAt: String, operatorName: String) {
detailLabel.text = "本订单一次确认,共 \(workCount) 个成片\n本机演示记录 · 并非真实收货凭据"
metadataStack.arrangedSubviews.forEach { metadataStack.removeArrangedSubview($0); $0.removeFromSuperview() }
for (label, value) in [("确认人", visitor), ("确认时间", confirmedAt), ("交付工作人员", operatorName), ("确认范围", "\(pointCount) 个打卡点 · \(workCount) 个成片")] {
let key = DroneDockStyle.label(label, size: 12, color: DroneDockStyle.secondary)
key.snp.makeConstraints { make in make.width.equalTo(86) }
let content = DroneDockStyle.label(value, size: 12)
content.numberOfLines = 0
content.textAlignment = .right
let row = UIStackView(arrangedSubviews: [key, content])
row.alignment = .top
row.spacing = 10
metadataStack.addArrangedSubview(row)
}
accessibilityIdentifier = "drone.delivery.confirmation.receipt"
}
}
/// 核对、确认码与确认记录共用的固定底部操作区,所有按钮至少 44 点高。
@MainActor
final class DroneDeliveryReviewFooterView: UIView {
/// 核对勾选变化由 Controller 主动同步到 ViewModel。
var onAcknowledgementTap: (() -> Void)?
/// 主操作随页面阶段变化。
var onPrimaryTap: (() -> Void)?
/// 次操作用于继续交付、稍后返回或回到当前核对。
var onSecondaryTap: (() -> Void)?
private let noteLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let acknowledgementButton = UIButton(type: .system)
private let primaryButton = UIButton(type: .system)
private let secondaryButton = UIButton(type: .system)
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.leading.trailing.top.equalToSuperview(); make.height.equalTo(1) }
noteLabel.textAlignment = .center
noteLabel.numberOfLines = 2
acknowledgementButton.contentHorizontalAlignment = .leading
acknowledgementButton.tintColor = DroneDockStyle.primary
acknowledgementButton.addTarget(self, action: #selector(acknowledgementTapped), for: .touchUpInside)
primaryButton.layer.cornerRadius = 9
primaryButton.backgroundColor = DroneDockStyle.primary
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(UIColor.white.withAlphaComponent(0.85), for: .disabled)
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
primaryButton.titleLabel?.adjustsFontSizeToFitWidth = true
primaryButton.titleLabel?.minimumScaleFactor = 0.8
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
secondaryButton.setTitleColor(DroneDockStyle.secondary, for: .normal)
secondaryButton.titleLabel?.font = .systemFont(ofSize: 13)
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
let stack = UIStackView(arrangedSubviews: [noteLabel, acknowledgementButton, primaryButton, secondaryButton])
stack.axis = .vertical
stack.spacing = 5
addSubview(stack)
stack.snp.makeConstraints { make in
make.leading.trailing.equalToSuperview().inset(16)
make.top.equalToSuperview().offset(9)
make.bottom.equalTo(safeAreaLayoutGuide).inset(4)
}
acknowledgementButton.snp.makeConstraints { make in make.height.equalTo(44).priority(999) }
primaryButton.snp.makeConstraints { make in make.height.equalTo(48) }
secondaryButton.snp.makeConstraints { make in make.height.equalTo(44).priority(999) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 根据明确页面状态配置操作;未核对时不能展示确认码。
func apply(acknowledged: Bool?, note: String?, primaryTitle: String, primaryIdentifier: String, primaryEnabled: Bool,
secondaryTitle: String?, secondaryIdentifier: String) {
noteLabel.text = note
noteLabel.isHidden = note == nil
acknowledgementButton.isHidden = acknowledged == nil
if let acknowledged {
var configuration = UIButton.Configuration.plain()
configuration.title = "我已核对,本订单成片已全部交齐"
configuration.image = UIImage(systemName: acknowledged ? "checkmark.square.fill" : "square")
configuration.imagePadding = 7
configuration.contentInsets = .zero
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var attributes = attributes
attributes.font = .systemFont(ofSize: 12)
return attributes
}
acknowledgementButton.configuration = configuration
acknowledgementButton.accessibilityTraits = acknowledged ? [.button, .selected] : .button
}
acknowledgementButton.accessibilityIdentifier = "drone.delivery.review.acknowledge"
primaryButton.setTitle(primaryTitle, for: .normal)
primaryButton.accessibilityIdentifier = primaryIdentifier
primaryButton.isEnabled = primaryEnabled
primaryButton.backgroundColor = primaryEnabled ? DroneDockStyle.primary : DroneDockStyle.primary.withAlphaComponent(0.2)
secondaryButton.setTitle(secondaryTitle, for: .normal)
secondaryButton.accessibilityIdentifier = secondaryIdentifier
secondaryButton.isHidden = secondaryTitle == nil
}
@objc private func acknowledgementTapped() { onAcknowledgementTap?() }
@objc private func primaryTapped() { onPrimaryTap?() }
@objc private func secondaryTapped() { onSecondaryTap?() }
}
@@ -0,0 +1,437 @@
import SnapKit
import UIKit
/// 整单核对页的导航请求由机巢入口处理,不在这里打开游客网页或执行上传。
@MainActor
protocol DroneDeliveryReviewViewControllerDelegate: AnyObject {
/// 商家尚未交齐或需要追加成片时继续交付。
func deliveryReviewViewControllerDidRequestUpload(_ controller: DroneDeliveryReviewViewController)
/// 只读预览当前核对清单或历史确认快照中的成片。
func deliveryReviewViewController(_ controller: DroneDeliveryReviewViewController, didRequestPreview work: DroneDeliveryWork)
}
/// 商家侧整单交付核对、演示确认码与冻结确认记录;刷新不会模拟游客主动确认。
@MainActor
final class DroneDeliveryReviewViewController: BaseViewController {
/// 交付与确认状态的唯一业务来源,核对范围始终为整单全部点位。
let viewModel: DroneDeliveryViewModel
/// 成片上传和本地预览的跨页面导航。
weak var delegate: DroneDeliveryReviewViewControllerDelegate?
/// 当前实际呈现清单的只读预览范围;历史记录不会夹带后来追加的作品。
var previewMaterials: [DroneMaterial] { displayedGroups.flatMap(\.works).map(\.previewMaterial) }
/// 页面阶段只决定呈现,不改变确认会话。
private enum Stage: Equatable {
case review, code, receipt
}
/// 辅助内容与每个点位采用稳定的 Diffable 分区身份。
private enum Section: Hashable {
case order, introduction, statistics, code, receipt, manifestTitle, point(String), note
}
/// 素材身份与可变的确认状态分离,刷新时重配置现有项。
private enum Item: Hashable {
case order, introduction, statistics, code, receipt, manifestTitle, work(String), note
}
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private let footerView = DroneDeliveryReviewFooterView()
private var displayedReceipt: DroneDeliveryConfirmationSession?
private var groupsByID: [String: DroneDeliveryWorkGroup] = [:]
private var worksByID: [String: DroneDeliveryWork] = [:]
private var activeReceipt: DroneDeliveryConfirmationSession? {
displayedReceipt ?? (viewModel.confirmationPhase == .confirmed ? viewModel.latestReceipt : nil)
}
private var stage: Stage {
if activeReceipt != nil { return .receipt }
return viewModel.confirmationPhase == .review ? .review : .code
}
private var displayedGroups: [DroneDeliveryWorkGroup] {
if let receipt = activeReceipt { return Self.groups(for: receipt.works) }
return stage == .code ? viewModel.confirmationGroups : viewModel.workGroups
}
/// 从任意商家订单入口打开整单核对,不继承上传页面的点位筛选。
init(viewModel: DroneDeliveryViewModel) {
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)
refreshDeliveryState()
}
/// 成片上传弹层结束后显式刷新本地快照,不推进游客确认状态。
func refreshDeliveryState() {
viewModel.refresh()
if dataSource != nil { applySnapshot(animated: false) }
}
override func setupNavigationBar() {
title = "订单交付确认"
navigationItem.backButtonDisplayMode = .minimal
let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(backTapped))
back.accessibilityIdentifier = "drone.delivery.review.back"
back.accessibilityLabel = "返回"
navigationItem.leftBarButtonItem = back
updateNavigationActions()
}
override func setupUI() {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = true
collectionView.showsVerticalScrollIndicator = false
collectionView.accessibilityIdentifier = "drone.delivery.review.list"
collectionView.register(DroneDeliveryReviewOrderCell.self, forCellWithReuseIdentifier: "order")
collectionView.register(DroneDeliveryReviewTextCell.self, forCellWithReuseIdentifier: "text")
collectionView.register(DroneDeliveryReviewStatisticsCell.self, forCellWithReuseIdentifier: "statistics")
collectionView.register(DroneDeliveryReviewWorkCell.self, forCellWithReuseIdentifier: "work")
collectionView.register(DroneDeliveryConfirmationCodeCell.self, forCellWithReuseIdentifier: "code")
collectionView.register(DroneDeliveryReceiptCell.self, forCellWithReuseIdentifier: "receipt")
collectionView.register(DroneDeliveryReviewPointHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "point")
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() {
footerView.onAcknowledgementTap = { [weak self] in
guard let self, self.stage == .review else { return }
self.viewModel.setAllDeliveredReviewed(!self.viewModel.isAllDeliveredReviewed)
self.applySnapshot(animated: true)
}
footerView.onPrimaryTap = { [weak self] in self?.performPrimaryAction() }
footerView.onSecondaryTap = { [weak self] in self?.performSecondaryAction() }
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] index, environment in
guard let self, self.dataSource != nil else { return nil }
let sections = self.dataSource.snapshot().sectionIdentifiers
guard sections.indices.contains(index) else { return nil }
if case .point = sections[index] {
let width = (environment.container.effectiveContentSize.width - 44) / 2
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1)))
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 0.57 + 49)),
repeatingSubitem: item, count: 2
)
group.interItemSpacing = .fixed(12)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 12
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 18, trailing: 16)
section.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(40)),
elementKind: UICollectionView.elementKindSectionHeader, alignment: .top
)]
return section
}
let estimate: CGFloat
switch sections[index] {
case .code: estimate = 450
case .receipt: estimate = 360
case .statistics: estimate = 66
default: estimate = 70
}
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(estimate)))
let group = NSCollectionLayoutGroup.vertical(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(estimate)), subitems: [item]
)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(top: sections[index] == .code ? 18 : 0, leading: 16, bottom: sections[index] == .statistics ? 8 : 0, trailing: 16)
return section
}
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, indexPath, item in
guard let self else { return nil }
switch item {
case .order:
let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: indexPath) as! DroneDeliveryReviewOrderCell
cell.apply(customer: self.activeReceipt?.visitorName ?? self.viewModel.order?.customerName ?? "订单暂不可用",
orderNumber: self.activeReceipt?.orderNumber ?? self.viewModel.order?.orderNumber ?? "请返回订单重新进入")
return cell
case .statistics:
let cell = list.dequeueReusableCell(withReuseIdentifier: "statistics", for: indexPath) as! DroneDeliveryReviewStatisticsCell
cell.apply(workCount: self.viewModel.works.count, pointCount: self.viewModel.workGroups.count)
return cell
case .work(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "work", for: indexPath) as! DroneDeliveryReviewWorkCell
if let work = self.worksByID[id] {
cell.apply(id: work.id, title: work.title, fileName: work.fileName, previewAssetName: work.previewAssetName, durationText: work.durationText)
cell.onPreviewTap = { [weak self] in
guard let self, let current = self.worksByID[id] else { return }
self.delegate?.deliveryReviewViewController(self, didRequestPreview: current)
}
}
return cell
case .code:
let cell = list.dequeueReusableCell(withReuseIdentifier: "code", for: indexPath) as! DroneDeliveryConfirmationCodeCell
let session = self.viewModel.confirmationSession
let feedback = self.viewModel.confirmationPhase == .feedback
? session?.feedback.map { "\($0.kind.title):\($0.note.isEmpty ? "请与游客核对成片清单" : $0.note)" } : nil
cell.apply(status: self.viewModel.confirmationPhase.title,
tone: self.viewModel.confirmationPhase == .feedback ? .orange : .blue,
workCount: session?.works.count ?? 0, pointCount: self.viewModel.confirmationGroups.count, feedback: feedback)
return cell
case .receipt:
let cell = list.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath) as! DroneDeliveryReceiptCell
if let receipt = self.activeReceipt {
cell.apply(workCount: receipt.works.count, pointCount: Self.groups(for: receipt.works).count,
visitor: receipt.visitorName, confirmedAt: Self.dateText(receipt.confirmedAt), operatorName: receipt.operatorName)
}
return cell
case .introduction, .manifestTitle, .note:
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: indexPath) as! DroneDeliveryReviewTextCell
switch item {
case .introduction:
cell.apply(title: "先核对,再请游客确认", detail: "一次确认整单,不按打卡点逐次确认。", symbol: "checkmark.shield")
case .manifestTitle:
let title = self.stage == .receipt ? "已确认的成片清单" : (self.stage == .code ? "本次整单确认清单" : "整单交付清单")
cell.apply(title: title, detail: self.stage == .review ? "含所有上传批次" : "确认时的固定作品清单")
case .note:
let message: String
switch self.stage {
case .review:
message = self.viewModel.works.isEmpty ? "暂无已交付成片。请先完成成片交付,再核对整单作品。" : "请核对约定交付的全部作品。单次上传完成,不代表整单已交齐。"
case .code:
message = "演示图案没有有效游客链接,不提供真实扫码收货服务。刷新仅同步本机状态,不会代替游客主动确认。"
case .receipt:
message = "当前为本机演示记录,并非真实收货凭据。新增成片不会覆盖这份确认清单。"
}
cell.apply(title: nil, detail: message)
default: break
}
return cell
}
}
dataSource.supplementaryViewProvider = { [weak self] list, kind, indexPath in
guard let self else { return nil }
let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "point", for: indexPath) as! DroneDeliveryReviewPointHeader
self.applyPointHeader(header, sectionIndex: indexPath.section)
return header
}
}
private func applyPointHeader(_ header: DroneDeliveryReviewPointHeader, sectionIndex: Int) {
let sections = dataSource.snapshot().sectionIdentifiers
guard sections.indices.contains(sectionIndex), case .point(let id) = sections[sectionIndex], let group = groupsByID[id] else { return }
header.apply(pointName: group.pointName, workCount: group.works.count)
}
private func applySnapshot(animated: Bool) {
guard isViewLoaded, dataSource != nil else { return }
let groups = displayedGroups
groupsByID = Dictionary(uniqueKeysWithValues: groups.map { ($0.id, $0) })
worksByID = Dictionary(uniqueKeysWithValues: groups.flatMap(\.works).map { ($0.id, $0) })
let previous = dataSource.snapshot()
let existing = Set(previous.itemIdentifiers)
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
snapshot.appendSections([.order])
snapshot.appendItems([.order], toSection: .order)
switch stage {
case .review:
snapshot.appendSections([.introduction, .statistics])
snapshot.appendItems([.introduction], toSection: .introduction)
snapshot.appendItems([.statistics], toSection: .statistics)
case .code:
snapshot.appendSections([.code])
snapshot.appendItems([.code], toSection: .code)
case .receipt:
snapshot.appendSections([.receipt])
snapshot.appendItems([.receipt], toSection: .receipt)
}
snapshot.appendSections([.manifestTitle])
snapshot.appendItems([.manifestTitle], toSection: .manifestTitle)
for group in groups {
let section = Section.point(group.id)
snapshot.appendSections([section])
snapshot.appendItems(group.works.map { .work($0.id) }, toSection: section)
}
snapshot.appendSections([.note])
snapshot.appendItems([.note], toSection: .note)
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
applyFooter()
updateNavigationActions()
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) {
guard let header = self.collectionView.supplementaryView(forElementKind: kind, at: path) as? DroneDeliveryReviewPointHeader else { continue }
self.applyPointHeader(header, sectionIndex: path.section)
}
}
if previous.sectionIdentifiers != snapshot.sectionIdentifiers { collectionView.collectionViewLayout.invalidateLayout() }
}
private func applyFooter() {
switch stage {
case .review:
footerView.apply(acknowledged: viewModel.isAllDeliveredReviewed, note: "本机交互演示 · 无真实游客链接",
primaryTitle: "已交齐,展示订单确认码", primaryIdentifier: "drone.delivery.review.showCode", primaryEnabled: viewModel.canCreateConfirmation,
secondaryTitle: "还未交齐,继续交付", secondaryIdentifier: "drone.delivery.review.continueUpload")
case .code:
let feedback = viewModel.confirmationPhase == .feedback
footerView.apply(acknowledged: nil, note: "本机演示状态,不代表真实收货",
primaryTitle: feedback ? "重新核对整单" : "刷新确认状态", primaryIdentifier: feedback ? "drone.delivery.review.restart" : "drone.delivery.confirmation.refresh", primaryEnabled: true,
secondaryTitle: feedback ? "继续补充交付" : "稍后确认,返回订单", secondaryIdentifier: feedback ? "drone.delivery.review.continueUpload" : "drone.delivery.confirmation.later")
case .receipt:
let hasCurrentReview = displayedReceipt != nil && viewModel.confirmationPhase != .confirmed
footerView.apply(acknowledged: nil, note: "仅确认交付清单,不代表对拍摄效果无异议",
primaryTitle: hasCurrentReview ? "返回当前整单核对" : "返回订单", primaryIdentifier: hasCurrentReview ? "drone.delivery.review.current" : "drone.delivery.confirmation.backToOrders", primaryEnabled: true,
secondaryTitle: hasCurrentReview ? nil : "追加成片,开始新核对", secondaryIdentifier: "drone.delivery.review.continueUpload")
}
}
private func performPrimaryAction() {
switch stage {
case .review:
guard viewModel.createConfirmationSession() else { return }
case .code:
if viewModel.confirmationPhase == .feedback { viewModel.beginNewReview() }
else { viewModel.refreshConfirmation() }
case .receipt:
if displayedReceipt != nil && viewModel.confirmationPhase != .confirmed { displayedReceipt = nil }
else { closePage(); return }
}
applySnapshot(animated: true)
collectionView.setContentOffset(CGPoint(x: 0, y: -collectionView.adjustedContentInset.top), animated: false)
}
private func performSecondaryAction() {
switch stage {
case .review, .receipt:
displayedReceipt = nil
delegate?.deliveryReviewViewControllerDidRequestUpload(self)
case .code:
if viewModel.confirmationPhase == .feedback { delegate?.deliveryReviewViewControllerDidRequestUpload(self) }
else { closePage() }
}
}
private func updateNavigationActions() {
var actions: [UIBarButtonItem] = []
if !viewModel.confirmationRecords.isEmpty {
let records = viewModel.confirmationRecords.map { record in
UIAction(title: "\(Self.dateText(record.confirmedAt)) · \(record.works.count)个成片",
state: self.activeReceipt?.id == record.id ? .on : .off) { [weak self] _ in
guard let self else { return }
self.displayedReceipt = record
self.applySnapshot(animated: true)
self.collectionView.setContentOffset(CGPoint(x: 0, y: -self.collectionView.adjustedContentInset.top), animated: false)
}
}
let history = UIBarButtonItem(image: UIImage(systemName: "clock.arrow.circlepath"), menu: UIMenu(title: "本机演示确认记录", children: records))
history.accessibilityIdentifier = "drone.delivery.confirmation.history"
history.accessibilityLabel = "查看确认记录"
actions.append(history)
}
#if DEBUG
let viewing = UIAction(title: "模拟游客查看中", image: UIImage(systemName: "eye")) { [weak self] _ in self?.simulateViewing() }
let confirmed = UIAction(title: "模拟游客主动确认", image: UIImage(systemName: "checkmark.circle")) { [weak self] _ in self?.simulateConfirmed() }
let feedback = DroneDeliveryFeedbackKind.allCases.map { kind in
UIAction(title: kind.title) { [weak self] _ in self?.simulateFeedback(kind) }
}
let scenarios: [DroneDeliveryScenario] = [.empty, .completed, .awaitingConfirmation, .viewing, .feedback, .confirmed]
let fixtures = scenarios.map { scenario in
UIAction(title: scenario.title) { [weak self] _ in
guard let self else { return }
self.displayedReceipt = nil
self.viewModel.applyScenario(scenario)
self.applySnapshot(animated: true)
}
}
let menu = UIMenu(title: "本机确认演示,不连接游客", children: [
UIMenu(options: .displayInline, children: [viewing, confirmed]),
UIMenu(title: "模拟游客反馈", children: feedback),
UIMenu(title: "载入演示状态", children: fixtures)
])
let debug = UIBarButtonItem(image: UIImage(systemName: "slider.horizontal.3"), menu: menu)
debug.accessibilityIdentifier = "drone.delivery.review.scenarios"
debug.accessibilityLabel = "交付确认演示状态"
actions.append(debug)
#endif
navigationItem.rightBarButtonItems = actions
}
#if DEBUG
private func simulateViewing() {
guard let session = viewModel.confirmationSession else { showToast("请先核对整单并展示确认码"); return }
displayedReceipt = nil
viewModel.receiveConfirmation(.viewing, sessionID: session.id)
applySnapshot(animated: true)
}
private func simulateConfirmed() {
guard let session = viewModel.confirmationSession else { showToast("请先核对整单并展示确认码"); return }
displayedReceipt = nil
viewModel.receiveConfirmation(.viewing, sessionID: session.id)
viewModel.setVisitorAcknowledged(true)
viewModel.receiveConfirmation(.confirmed, sessionID: session.id)
applySnapshot(animated: true)
collectionView.setContentOffset(CGPoint(x: 0, y: -collectionView.adjustedContentInset.top), animated: false)
}
private func simulateFeedback(_ kind: DroneDeliveryFeedbackKind) {
guard let session = viewModel.confirmationSession else { showToast("请先核对整单并展示确认码"); return }
displayedReceipt = nil
viewModel.receiveConfirmation(.viewing, sessionID: session.id)
viewModel.receiveConfirmation(.feedback(kind: kind, note: "本机演示反馈,请核对成片清单。"), sessionID: session.id)
applySnapshot(animated: true)
}
#endif
private func closePage() {
if let navigationController, navigationController.viewControllers.first !== self { navigationController.popViewController(animated: true) }
else { dismiss(animated: true) }
}
@objc private func backTapped() {
if displayedReceipt != nil && viewModel.confirmationPhase != .confirmed {
displayedReceipt = nil
applySnapshot(animated: true)
} else { closePage() }
}
/// 按快照首次出现顺序呈现点位,不以当前作品库重新计算历史确认范围。
private static func groups(for works: [DroneDeliveryWork]) -> [DroneDeliveryWorkGroup] {
var order: [String] = []
var names: [String: String] = [:]
var values: [String: [DroneDeliveryWork]] = [:]
for work in works {
if values[work.pointID] == nil { order.append(work.pointID); names[work.pointID] = work.pointName }
values[work.pointID, default: []].append(work)
}
return order.map { DroneDeliveryWorkGroup(pointID: $0, pointName: names[$0] ?? "打卡点", works: values[$0] ?? []) }
}
private static func dateText(_ date: Date?) -> String {
guard let date else { return "—" }
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
return formatter.string(from: date)
}
}
@@ -0,0 +1,389 @@
import SnapKit
import UIKit
/// 交付 Sheet 的标题、订单摘要及 44 点关闭按钮。
@MainActor
final class DroneDeliveryUploadHeaderView: UIView {
/// 关闭当前交付流程。
var onCloseTap: (() -> Void)?
private let titleLabel = DroneDockStyle.label(size: 19, weight: .semibold)
private let customerLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let closeButton = UIButton(type: .system)
private let debugButton = UIButton(type: .system)
override init(frame: CGRect) {
super.init(frame: frame)
closeButton.setImage(UIImage(systemName: "xmark", withConfiguration: UIImage.SymbolConfiguration(pointSize: 14)), for: .normal)
closeButton.tintColor = DroneDockStyle.secondary
closeButton.accessibilityLabel = "关闭成片交付"
closeButton.accessibilityIdentifier = "drone.delivery.upload.close"
closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
debugButton.setImage(UIImage(systemName: "slider.horizontal.3"), for: .normal)
debugButton.tintColor = DroneDockStyle.secondary
debugButton.showsMenuAsPrimaryAction = true
debugButton.isHidden = true
debugButton.accessibilityIdentifier = "drone.delivery.upload.scenarios"
debugButton.accessibilityLabel = "成片交付演示状态"
[titleLabel, customerLabel, detailLabel, closeButton, debugButton].forEach(addSubview)
titleLabel.accessibilityTraits = .header
titleLabel.snp.makeConstraints { make in make.top.equalToSuperview().offset(16); make.leading.equalToSuperview().offset(20); make.trailing.lessThanOrEqualTo(closeButton.snp.leading) }
customerLabel.snp.makeConstraints { make in make.leading.equalTo(titleLabel); make.top.equalTo(titleLabel.snp.bottom).offset(20); make.trailing.lessThanOrEqualTo(closeButton.snp.leading).offset(-4) }
detailLabel.snp.makeConstraints { make in make.leading.equalTo(titleLabel); make.top.equalTo(customerLabel.snp.bottom).offset(6); make.trailing.equalToSuperview().inset(20); make.bottom.equalToSuperview().inset(12) }
closeButton.snp.makeConstraints { make in make.trailing.equalToSuperview().inset(8); make.centerY.equalTo(customerLabel); make.size.equalTo(44) }
debugButton.snp.makeConstraints { make in make.trailing.equalTo(closeButton); make.centerY.equalTo(titleLabel); make.size.equalTo(44) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 阶段变化时只更新标题与上下文,不修改业务状态。
func apply(title: String, customer: String, detail: String) {
titleLabel.text = title
customerLabel.text = customer
detailLabel.text = detail
}
/// 在本地演示版本显示显式验收菜单。
func setDebugMenu(_ menu: UIMenu) {
debugButton.menu = menu
debugButton.isHidden = false
}
@objc private func closeTapped() { onCloseTap?() }
}
/// 面对面闪传或云端上传的整卡入口。
@MainActor
final class DroneDeliveryUploadMethodCell: UICollectionViewCell {
private let iconView = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let arrowView = UIImageView(image: UIImage(systemName: "chevron.right"))
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = UIColor(hex: 0xF9FAFD)
contentView.layer.cornerRadius = 12
contentView.layer.borderWidth = 1
contentView.layer.borderColor = DroneDockStyle.border.cgColor
iconView.tintColor = DroneDockStyle.primary
iconView.backgroundColor = DroneDockStyle.primary.withAlphaComponent(0.06)
iconView.layer.cornerRadius = 10
iconView.contentMode = .center
arrowView.tintColor = DroneDockStyle.secondary
arrowView.contentMode = .scaleAspectFit
[iconView, titleLabel, detailLabel, arrowView].forEach(contentView.addSubview)
iconView.snp.makeConstraints { make in make.leading.equalToSuperview().offset(14); make.centerY.equalToSuperview(); make.size.equalTo(44) }
titleLabel.snp.makeConstraints { make in make.leading.equalTo(iconView.snp.trailing).offset(12); make.top.equalToSuperview().offset(21); make.trailing.lessThanOrEqualTo(arrowView.snp.leading).offset(-8) }
detailLabel.snp.makeConstraints { make in make.leading.equalTo(titleLabel); make.top.equalTo(titleLabel.snp.bottom).offset(6); make.trailing.lessThanOrEqualTo(arrowView.snp.leading).offset(-8) }
arrowView.snp.makeConstraints { make in make.trailing.equalToSuperview().inset(15); make.centerY.equalToSuperview(); make.width.equalTo(8); make.height.equalTo(13) }
isAccessibilityElement = true
accessibilityTraits = .button
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 展示可观察的方式说明,不暗示闪传已经接入。
func apply(title: String, detail: String, symbol: String, identifier: String) {
titleLabel.text = title
detailLabel.text = detail
iconView.image = UIImage(systemName: symbol, withConfiguration: UIImage.SymbolConfiguration(pointSize: 23))
accessibilityLabel = "\(title),\(detail)"
accessibilityIdentifier = identifier
}
}
/// 云端交付目标点位的单选行。
@MainActor
final class DroneDeliveryUploadPointCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 16)
private let checkmark = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
checkmark.contentMode = .scaleAspectFit
let line = UIView()
line.backgroundColor = DroneDockStyle.border
[titleLabel, checkmark, line].forEach(contentView.addSubview)
titleLabel.snp.makeConstraints { make in make.leading.centerY.equalToSuperview(); make.trailing.lessThanOrEqualTo(checkmark.snp.leading).offset(-12) }
checkmark.snp.makeConstraints { make in make.trailing.centerY.equalToSuperview(); make.size.equalTo(21) }
line.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 已选点位仍可再次点击,不通过 UI 取消单选。
func apply(point: DroneShootingPoint, selected: Bool, locked: Bool) {
titleLabel.text = point.name
titleLabel.textColor = selected ? DroneDockStyle.primary : DroneDockStyle.text
checkmark.image = UIImage(systemName: selected ? "checkmark.circle" : "circle")
checkmark.tintColor = selected ? DroneDockStyle.primary : DroneDockStyle.secondary
contentView.alpha = locked ? 0.5 : 1
accessibilityIdentifier = "drone.delivery.upload.point.\(point.id)"
accessibilityLabel = point.name
var traits: UIAccessibilityTraits = .button
if selected { traits.insert(.selected) }
if locked { traits.insert(.notEnabled) }
accessibilityTraits = traits
}
}
/// 本地演示视频缩略图;整卡选择与预览按钮分开,避免打开预览时改变勾选。
@MainActor
final class DroneDeliveryUploadVideoCell: UICollectionViewCell {
/// 点击整卡选择区域时仅切换当前视频。
var onSelectionTap: (() -> Void)?
/// 点击独立预览按钮时通知控制器。
var onPreviewTap: (() -> Void)?
private let thumbnail = UIImageView()
private let checkmark = UIImageView()
private let durationLabel = DroneDockStyle.label(size: 10, color: .white)
private let titleLabel = DroneDockStyle.label(size: 12, weight: .medium)
private let previewButton = UIButton(type: .system)
private let selectionButton = UIButton(type: .custom)
override init(frame: CGRect) {
super.init(frame: frame)
thumbnail.contentMode = .scaleAspectFill
thumbnail.clipsToBounds = true
thumbnail.layer.cornerRadius = 7
thumbnail.layer.borderWidth = 2
checkmark.contentMode = .scaleAspectFit
durationLabel.backgroundColor = UIColor.black.withAlphaComponent(0.5)
durationLabel.textAlignment = .center
durationLabel.layer.cornerRadius = 3
durationLabel.clipsToBounds = true
previewButton.setImage(UIImage(systemName: "play.circle.fill", withConfiguration: UIImage.SymbolConfiguration(pointSize: 22)), for: .normal)
previewButton.tintColor = .white
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
[thumbnail, checkmark, durationLabel, titleLabel, selectionButton, previewButton].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(thumbnail.snp.width).multipliedBy(0.56) }
checkmark.snp.makeConstraints { make in make.top.equalTo(thumbnail).offset(7); make.trailing.equalTo(thumbnail).inset(7); make.size.equalTo(22) }
durationLabel.snp.makeConstraints { make in make.bottom.trailing.equalTo(thumbnail).inset(6); make.width.equalTo(44); make.height.equalTo(18) }
previewButton.snp.makeConstraints { make in make.leading.bottom.equalTo(thumbnail); make.size.equalTo(44) }
titleLabel.snp.makeConstraints { make in make.leading.trailing.equalToSuperview(); make.top.equalTo(thumbnail.snp.bottom).offset(8); make.bottom.lessThanOrEqualToSuperview() }
selectionButton.snp.makeConstraints { make in make.edges.equalToSuperview() }
contentView.isAccessibilityElement = false
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 图片及预览均来自本地示例,不读取手机文件。
func apply(video: DroneDeliveryVideo, selected: Bool) {
thumbnail.image = UIImage(named: video.previewAssetName)
thumbnail.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor
checkmark.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
checkmark.tintColor = selected ? DroneDockStyle.primary : .white
titleLabel.text = video.title
durationLabel.text = video.durationText
selectionButton.accessibilityIdentifier = "drone.delivery.upload.video.\(video.id)"
selectionButton.accessibilityLabel = "选择\(video.title),\(video.durationText)"
selectionButton.accessibilityTraits = selected ? [.button, .selected] : .button
isAccessibilityElement = false
previewButton.accessibilityIdentifier = "drone.delivery.upload.preview.\(video.id)"
previewButton.accessibilityLabel = "预览\(video.title)"
}
@objc private func previewTapped() { onPreviewTap?() }
@objc private func selectionTapped() { onSelectionTap?() }
}
/// 上传队列的一条视频记录,文件描述、逐项进度与演示结果分别展示。
@MainActor
final class DroneDeliveryUploadQueueCell: UICollectionViewCell {
private let iconView = UIImageView(image: UIImage(systemName: "play.rectangle"))
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let statusLabel = DroneDockStyle.label(size: 11)
private let progressView = UIProgressView(progressViewStyle: .default)
override init(frame: CGRect) {
super.init(frame: frame)
iconView.tintColor = DroneDockStyle.secondary
iconView.contentMode = .scaleAspectFit
progressView.progressTintColor = DroneDockStyle.primary
progressView.trackTintColor = UIColor(hex: 0xEDF1F8)
let line = UIView()
line.backgroundColor = DroneDockStyle.border
[iconView, titleLabel, detailLabel, statusLabel, progressView, line].forEach(contentView.addSubview)
iconView.snp.makeConstraints { make in make.leading.equalToSuperview(); make.centerY.equalToSuperview().offset(-4); make.size.equalTo(24) }
statusLabel.snp.makeConstraints { make in make.trailing.equalToSuperview(); make.centerY.equalTo(iconView); make.width.lessThanOrEqualTo(100) }
titleLabel.lineBreakMode = .byTruncatingMiddle
titleLabel.snp.makeConstraints { make in make.leading.equalTo(iconView.snp.trailing).offset(12); make.top.equalToSuperview().offset(17); make.trailing.lessThanOrEqualTo(statusLabel.snp.leading).offset(-10) }
detailLabel.snp.makeConstraints { make in make.leading.equalTo(titleLabel); make.top.equalTo(titleLabel.snp.bottom).offset(5); make.trailing.lessThanOrEqualTo(statusLabel.snp.leading).offset(-10) }
progressView.snp.makeConstraints { make in make.leading.equalTo(titleLabel); make.trailing.equalToSuperview(); make.bottom.equalToSuperview().inset(9); make.height.equalTo(2) }
line.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(1 / UIScreen.main.scale) }
isAccessibilityElement = true
accessibilityTraits = .button
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 队列成功只展示演示交付,不向游客发送作品。
func apply(item: DroneDeliveryUploadItem) {
titleLabel.text = item.video.fileName
detailLabel.text = "\(item.video.durationText) · \(item.video.sizeText)"
let progress: Double?
switch item.state {
case .uploading(let value):
statusLabel.text = "上传中 \(Int(value * 100))%"
statusLabel.textColor = DroneDockStyle.primary
progress = value
case .paused:
statusLabel.text = "已暂停"
statusLabel.textColor = DroneDockStyle.warning
progress = nil
case .failed:
statusLabel.text = "上传失败"
statusLabel.textColor = DroneDockStyle.color(for: .red)
progress = nil
case .completed:
statusLabel.text = "演示交付成功"
statusLabel.textColor = DroneDockStyle.success
progress = nil
}
progressView.isHidden = progress == nil
progressView.setProgress(Float(progress ?? 0), animated: true)
accessibilityIdentifier = "drone.delivery.upload.item.\(item.id)"
accessibilityLabel = [item.video.fileName, detailLabel.text, statusLabel.text, "点按预览"].compactMap { $0 }.joined(separator: ",")
}
}
/// 闪传待确认、无点位与无可选视频等状态的说明。
@MainActor
final class DroneDeliveryUploadMessageCell: UICollectionViewCell {
private let iconView = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 16, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
override init(frame: CGRect) {
super.init(frame: frame)
iconView.tintColor = DroneDockStyle.primary
iconView.contentMode = .scaleAspectFit
titleLabel.textAlignment = .center
detailLabel.textAlignment = .center
detailLabel.numberOfLines = 0
let stack = UIStackView(arrangedSubviews: [iconView, titleLabel, detailLabel])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 15
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.centerY.equalToSuperview(); make.leading.trailing.equalToSuperview().inset(8) }
iconView.snp.makeConstraints { make in make.size.equalTo(34) }
isAccessibilityElement = true
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 展示不包含真实设备连接或传输动作的说明。
func apply(title: String, detail: String, symbol: String) {
titleLabel.text = title
detailLabel.text = detail
iconView.image = UIImage(systemName: symbol)
accessibilityLabel = "\(title),\(detail)"
}
}
/// 队列摘要与查看已交付作品入口。
@MainActor
final class DroneDeliveryUploadSummaryCell: UICollectionViewCell {
/// 查看当前订单的演示交付作品。
var onReviewTap: (() -> Void)?
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let reviewButton = UIButton(type: .system)
override init(frame: CGRect) {
super.init(frame: frame)
reviewButton.setTitle("查看作品", for: .normal)
reviewButton.titleLabel?.font = .systemFont(ofSize: 11)
reviewButton.tintColor = DroneDockStyle.primary
reviewButton.accessibilityIdentifier = "drone.delivery.upload.review"
reviewButton.addTarget(self, action: #selector(reviewTapped), for: .touchUpInside)
[titleLabel, detailLabel, reviewButton].forEach(contentView.addSubview)
titleLabel.snp.makeConstraints { make in make.leading.equalToSuperview(); make.centerY.equalToSuperview().offset(-10) }
detailLabel.snp.makeConstraints { make in make.leading.equalTo(titleLabel); make.top.equalTo(titleLabel.snp.bottom).offset(6) }
reviewButton.snp.makeConstraints { make in make.trailing.centerY.equalToSuperview(); make.width.equalTo(68); make.height.equalTo(44) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 计数仅统计当前演示批次成功回执。
func apply(completed: Int, detail: String) {
titleLabel.text = "本次演示交付 \(completed) 个作品"
detailLabel.text = detail
reviewButton.isHidden = completed == 0
}
@objc private func reviewTapped() { onReviewTap?() }
}
/// 交付各阶段共用的主按钮、补充说明和返回或完成入口。
@MainActor
final class DroneDeliveryUploadFooterView: UIView {
/// 执行当前阶段的主操作。
var onPrimaryTap: (() -> Void)?
/// 返回上一阶段或完成本次流程。
var onSecondaryTap: (() -> Void)?
private let primaryButton = UIButton(type: .system)
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let secondaryButton = UIButton(type: .system)
private let stack = UIStackView()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
stack.axis = .vertical
stack.spacing = 9
primaryButton.layer.cornerRadius = 8
primaryButton.layer.cornerCurve = .continuous
primaryButton.tintColor = .white
primaryButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
detailLabel.textAlignment = .center
detailLabel.numberOfLines = 2
secondaryButton.titleLabel?.font = .systemFont(ofSize: 12)
secondaryButton.tintColor = DroneDockStyle.secondary
secondaryButton.addTarget(self, action: #selector(secondaryTapped), for: .touchUpInside)
[primaryButton, detailLabel, secondaryButton].forEach(stack.addArrangedSubview)
addSubview(stack)
stack.snp.makeConstraints { make in make.leading.trailing.equalToSuperview().inset(20); make.top.equalToSuperview().offset(14); make.bottom.equalTo(safeAreaLayoutGuide).inset(12) }
primaryButton.snp.makeConstraints { make in make.height.equalTo(44).priority(999) }
secondaryButton.snp.makeConstraints { make in make.height.equalTo(44).priority(999) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 不同阶段提供明确动作;上传中的按钮保留可见但不可重复提交。
func apply(primaryTitle: String?, enabled: Bool, identifier: String, detail: String, secondaryTitle: String?) {
UIView.performWithoutAnimation {
primaryButton.setTitle(primaryTitle, for: .normal)
primaryButton.setTitle(primaryTitle, for: .disabled)
primaryButton.isHidden = primaryTitle == nil
primaryButton.isEnabled = enabled
primaryButton.backgroundColor = enabled ? DroneDockStyle.primary : UIColor(hex: 0xE7EEFF)
primaryButton.setTitleColor(.white, for: .normal)
primaryButton.setTitleColor(DroneDockStyle.primary.withAlphaComponent(0.6), for: .disabled)
primaryButton.accessibilityIdentifier = identifier
detailLabel.text = detail
detailLabel.isHidden = detail.isEmpty
secondaryButton.setTitle(secondaryTitle, for: .normal)
secondaryButton.isHidden = secondaryTitle == nil
secondaryButton.accessibilityIdentifier = "drone.delivery.upload.secondary"
primaryButton.layoutIfNeeded()
}
}
@objc private func primaryTapped() { onPrimaryTap?() }
@objc private func secondaryTapped() { onSecondaryTap?() }
}
@@ -0,0 +1,412 @@
import SnapKit
import UIKit
/// 交付 Sheet 只请求完成、查看记录与本地视频预览,跨页面导航由入口统一处理。
@MainActor
protocol DroneDeliveryUploadViewControllerDelegate: AnyObject {
/// 关闭交付流程并刷新入口的本地演示摘要。
func deliveryUploadViewControllerDidFinish(_ controller: DroneDeliveryUploadViewController)
/// 进入当前订单的已交付作品记录。
func deliveryUploadViewControllerDidRequestReview(_ controller: DroneDeliveryUploadViewController)
/// 预览本地示例视频,保持现有上传状态与勾选。
func deliveryUploadViewController(_ controller: DroneDeliveryUploadViewController, didRequestPreview video: DroneDeliveryVideo)
}
/// 成片交付的本地演示:选择方式、点位与视频,逐项展示前台上传及结果。
@MainActor
final class DroneDeliveryUploadViewController: BaseViewController {
/// 订单、目标点位、选择及演示上传队列的业务状态来源。
let viewModel: DroneDeliveryViewModel
/// 将完成与预览导航交回入口。
weak var delegate: DroneDeliveryUploadViewControllerDelegate?
/// 页面阶段只管理展示导航,不参与上传成功或拍摄次数计算。
private enum Phase: Equatable { case method, nearby, point, picker, queue }
/// 队列摘要与主体使用独立分区。
private enum Section: Hashable { case summary, content }
/// 每一项依靠稳定业务身份更新,选择与进度不改变 Diffable 标识。
private enum Item: Hashable {
case nearbyMethod, cloudMethod, nearbyMessage, point(String), video(String), upload(String), summary, empty
}
private var phase: Phase
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private let headerView = DroneDeliveryUploadHeaderView()
private let footerView = DroneDeliveryUploadFooterView()
private let uploadDriver = DroneDeliveryDemoUploadDriver()
private var videosByID: [String: DroneDeliveryVideo] = [:]
private var uploadItemsByID: [String: DroneDeliveryUploadItem] = [:]
private var didRequestFinish = false
/// 重新进入有未完成批次时直接恢复队列展示,仍需手动继续上传。
init(viewModel: DroneDeliveryViewModel) {
self.viewModel = viewModel
phase = viewModel.batch == nil ? .method : .queue
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .pageSheet
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 返回前台或结束预览后只刷新本地状态,不自动启动暂停队列。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.refresh()
if dataSource != nil { applySnapshot(animated: false) }
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
navigationController?.presentationController?.delegate = self
if navigationController == nil { presentationController?.delegate = self }
}
/// 真正关闭交付 Sheet 时暂停未完成项;全屏预览覆盖页面不改变上传状态。
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true {
if let coordinator = transitionCoordinator, coordinator.isInteractive {
coordinator.animate(alongsideTransition: nil) { [weak self] context in
if !context.isCancelled { self?.pauseForLeaving() }
}
} else {
pauseForLeaving()
}
}
}
override func setupNavigationBar() {
navigationController?.setNavigationBarHidden(true, animated: false)
}
override func setupUI() {
view.backgroundColor = .white
collectionView.backgroundColor = .white
collectionView.alwaysBounceVertical = false
collectionView.showsVerticalScrollIndicator = false
collectionView.accessibilityIdentifier = "drone.delivery.upload.list"
collectionView.delegate = self
collectionView.register(DroneDeliveryUploadMethodCell.self, forCellWithReuseIdentifier: "method")
collectionView.register(DroneDeliveryUploadPointCell.self, forCellWithReuseIdentifier: "point")
collectionView.register(DroneDeliveryUploadVideoCell.self, forCellWithReuseIdentifier: "video")
collectionView.register(DroneDeliveryUploadQueueCell.self, forCellWithReuseIdentifier: "upload")
collectionView.register(DroneDeliveryUploadMessageCell.self, forCellWithReuseIdentifier: "message")
collectionView.register(DroneDeliveryUploadSummaryCell.self, forCellWithReuseIdentifier: "summary")
[headerView, collectionView, footerView].forEach(view.addSubview)
configureDataSource()
configureDebugMenu()
applySnapshot(animated: false)
}
override func setupConstraints() {
headerView.snp.makeConstraints { make in make.top.equalTo(view.safeAreaLayoutGuide); make.leading.trailing.equalToSuperview() }
collectionView.snp.makeConstraints { make in
make.top.equalTo(headerView.snp.bottom)
make.leading.trailing.equalToSuperview()
make.bottom.equalTo(footerView.snp.top)
}
footerView.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
}
override func bindActions() {
headerView.onCloseTap = { [weak self] in self?.finish() }
footerView.onPrimaryTap = { [weak self] in self?.primaryTapped() }
footerView.onSecondaryTap = { [weak self] in self?.secondaryTapped() }
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive),
name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification, object: nil)
}
private func makeLayout() -> UICollectionViewLayout {
UICollectionViewCompositionalLayout { [weak self] sectionIndex, environment in
guard let self, let dataSource = self.dataSource else { return nil }
let sections = dataSource.snapshot().sectionIdentifiers
guard sections.indices.contains(sectionIndex) else { return nil }
let section = sections[sectionIndex]
if section == .summary { return self.listSection(height: 58) }
if self.phase == .picker, !self.viewModel.availableVideos.isEmpty {
let width = max(1, (environment.container.effectiveContentSize.width - 54) / 2)
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1)
))
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(width * 0.56 + 32)),
repeatingSubitem: item, count: 2
)
group.interItemSpacing = .fixed(14)
let layoutSection = NSCollectionLayoutSection(group: group)
layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 4, leading: 20, bottom: 6, trailing: 20)
layoutSection.interGroupSpacing = 14
return layoutSection
}
let height: CGFloat
switch self.phase {
case .method: height = 88
case .nearby: height = 170
case .point: height = self.viewModel.points.isEmpty ? 180 : 52
case .picker: height = 180
case .queue: height = self.viewModel.batch?.items.isEmpty == false ? 82 : 180
}
return self.listSection(height: height, spacing: self.phase == .method ? 12 : 0)
}
}
private func listSection(height: CGFloat, spacing: CGFloat = 0) -> NSCollectionLayoutSection {
let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)
))
let group = NSCollectionLayoutGroup.vertical(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(height)), subitems: [item]
)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(top: 4, leading: 20, bottom: 4, trailing: 20)
section.interGroupSpacing = spacing
return section
}
private func configureDataSource() {
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, indexPath, item in
guard let self else { return nil }
switch item {
case .nearbyMethod, .cloudMethod:
let cell = list.dequeueReusableCell(withReuseIdentifier: "method", for: indexPath) as! DroneDeliveryUploadMethodCell
if item == .nearbyMethod {
cell.apply(title: "面对面闪传", detail: "近距离传给游客 · 流程待确认", symbol: "wifi",
identifier: "drone.delivery.upload.method.nearby")
} else {
cell.apply(title: "云端上传", detail: "选择打卡点,演示上传成片", symbol: "icloud.and.arrow.up",
identifier: "drone.delivery.upload.method.cloud")
}
return cell
case .point(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "point", for: indexPath) as! DroneDeliveryUploadPointCell
if let point = self.viewModel.points.first(where: { $0.id == id }) {
cell.apply(point: point, selected: self.viewModel.selectedPointID == id, locked: self.viewModel.isUploadLocked)
}
return cell
case .video(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "video", for: indexPath) as! DroneDeliveryUploadVideoCell
if let video = self.videosByID[id] {
cell.apply(video: video, selected: self.viewModel.selectedVideoIDs.contains(id))
cell.onSelectionTap = { [weak self] in
guard let self else { return }
self.viewModel.toggleVideo(id: id)
self.applySnapshot(animated: true)
}
cell.onPreviewTap = { [weak self] in
guard let self else { return }
self.delegate?.deliveryUploadViewController(self, didRequestPreview: video)
}
}
return cell
case .upload(let id):
let cell = list.dequeueReusableCell(withReuseIdentifier: "upload", for: indexPath) as! DroneDeliveryUploadQueueCell
if let item = self.uploadItemsByID[id] { cell.apply(item: item) }
return cell
case .summary:
let cell = list.dequeueReusableCell(withReuseIdentifier: "summary", for: indexPath) as! DroneDeliveryUploadSummaryCell
cell.apply(completed: self.viewModel.uploadedCount, detail: self.queueSummary)
cell.onReviewTap = { [weak self] in
guard let self else { return }
self.pauseForLeaving()
self.delegate?.deliveryUploadViewControllerDidRequestReview(self)
}
return cell
case .nearbyMessage, .empty:
let cell = list.dequeueReusableCell(withReuseIdentifier: "message", for: indexPath) as! DroneDeliveryUploadMessageCell
if item == .nearbyMessage {
cell.apply(title: "闪传流程待确认", detail: "热点连接与游客接收流程暂未接入。\n现在可以先体验云端演示上传。", symbol: "wifi")
} else if self.phase == .point {
cell.apply(title: "暂无可交付点位", detail: "当前订单没有可用点位,请稍后重试。", symbol: "mappin.slash.circle")
} else if self.phase == .picker {
cell.apply(title: "暂无可选演示视频", detail: "本点位的示例视频已交付,可返回选择其他点位。", symbol: "video.slash")
} else {
cell.apply(title: "暂无上传队列", detail: "请选择视频后开始演示上传。", symbol: "icloud.and.arrow.up")
}
return cell
}
}
}
private var queueSummary: String {
switch viewModel.uploadPhase {
case .idle: "请选择视频后开始演示上传"
case .uploading: "\(viewModel.pendingCount)个上传中 · 仅在本地演示"
case .paused: "上传已暂停,请手动继续"
case .partialFailure: "\(viewModel.failedCount)个上传失败"
case .completed: "全部演示上传成功 · 未向游客发送"
}
}
private func applySnapshot(animated: Bool) {
guard isViewLoaded, dataSource != nil else { return }
videosByID = Dictionary(uniqueKeysWithValues: viewModel.availableVideos.map { ($0.id, $0) })
let uploadItems = viewModel.batch?.items ?? []
uploadItemsByID = Dictionary(uniqueKeysWithValues: uploadItems.map { ($0.id, $0) })
let oldItems = Set(dataSource.snapshot().itemIdentifiers)
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
if phase == .queue {
snapshot.appendSections([.summary])
snapshot.appendItems([.summary], toSection: .summary)
}
snapshot.appendSections([.content])
let items: [Item]
switch phase {
case .method: items = [.nearbyMethod, .cloudMethod]
case .nearby: items = [.nearbyMessage]
case .point: items = viewModel.points.isEmpty ? [.empty] : viewModel.points.map { .point($0.id) }
case .picker: items = viewModel.availableVideos.isEmpty ? [.empty] : viewModel.availableVideos.map { .video($0.id) }
case .queue: items = uploadItems.isEmpty ? [.empty] : uploadItems.map { .upload($0.id) }
}
snapshot.appendItems(items, toSection: .content)
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { oldItems.contains($0) })
applyHeaderAndFooter()
dataSource.apply(snapshot, animatingDifferences: animated)
collectionView.collectionViewLayout.invalidateLayout()
}
private func applyHeaderAndFooter() {
let customer = viewModel.order?.customerName ?? "订单信息暂不可用"
let pointName = viewModel.batch?.pointName ?? viewModel.selectedPoint?.name
let context = pointName.map { "\(customer) · \($0)" } ?? customer
switch phase {
case .method:
headerView.apply(title: "交付成片", customer: customer, detail: "请选择本次交付方式")
footerView.apply(primaryTitle: nil, enabled: false, identifier: "", detail: "可分批演示交付多个作品,不影响拍摄次数", secondaryTitle: nil)
case .nearby:
headerView.apply(title: "面对面闪传", customer: customer, detail: "本次仅展示交付入口")
footerView.apply(primaryTitle: "改用云端上传", enabled: true, identifier: "drone.delivery.upload.useCloud", detail: "", secondaryTitle: "返回交付方式")
case .point:
headerView.apply(title: "选择打卡点", customer: customer, detail: "云端上传 · 请选择本批成片对应的打卡点")
footerView.apply(primaryTitle: "去演示相册选视频", enabled: viewModel.selectedPoint != nil && !viewModel.isUploadLocked,
identifier: "drone.delivery.upload.openPicker", detail: "可选择一个或多个视频,上传与交付仅在本地演示", secondaryTitle: "返回交付方式")
case .picker:
headerView.apply(title: "选择视频", customer: context, detail: "演示相册 · 不读取手机文件")
footerView.apply(primaryTitle: "开始演示上传(\(viewModel.selectedVideoIDs.count))", enabled: viewModel.canStartUpload,
identifier: "drone.delivery.upload.start", detail: "选择后体验演示上传,不执行真实云端上传", secondaryTitle: "返回选择点位")
case .queue:
headerView.apply(title: "成片上传", customer: context, detail: "本地演示 · 不执行真实上传或游客发送")
switch viewModel.uploadPhase {
case .idle:
footerView.apply(primaryTitle: "返回选择视频", enabled: true, identifier: "drone.delivery.upload.pickMore", detail: "", secondaryTitle: "完成")
case .uploading:
footerView.apply(primaryTitle: "正在演示上传…", enabled: false, identifier: "drone.delivery.upload.start",
detail: "请保持页面开启,演示成功后更新本地交付记录", secondaryTitle: nil)
case .paused:
footerView.apply(primaryTitle: "继续上传", enabled: true, identifier: "drone.delivery.upload.continue",
detail: "已成功作品会保留;继续时只处理未完成项", secondaryTitle: "完成")
case .partialFailure:
footerView.apply(primaryTitle: "重试失败视频(\(viewModel.failedCount))", enabled: viewModel.failedCount > 0,
identifier: "drone.delivery.upload.retry", detail: "演示交付成功的作品不会重复上传", secondaryTitle: "完成")
case .completed:
footerView.apply(primaryTitle: "继续上传成片", enabled: true, identifier: "drone.delivery.upload.pickMore",
detail: "可分批演示上传,不扣减拍摄次数", secondaryTitle: "完成")
}
}
}
private func showPhase(_ phase: Phase) {
self.phase = phase
applySnapshot(animated: true)
collectionView.setContentOffset(.zero, animated: false)
let sheet = navigationController?.sheetPresentationController ?? sheetPresentationController
let detent: UISheetPresentationController.Detent.Identifier = phase == .picker || (phase == .queue && viewModel.totalUploadCount > 3) ? .large : .medium
sheet?.animateChanges { sheet?.selectedDetentIdentifier = detent }
}
private func primaryTapped() {
switch phase {
case .method: break
case .nearby: showPhase(.point)
case .point: if viewModel.selectedPoint != nil { showPhase(.picker) }
case .picker:
if viewModel.startUpload() { showPhase(.queue); startDemoUpload() }
case .queue:
switch viewModel.uploadPhase {
case .paused:
if viewModel.continueUpload() { applySnapshot(animated: true); startDemoUpload() }
case .partialFailure:
if viewModel.retryFailedUploads() { applySnapshot(animated: true); startDemoUpload() }
case .completed, .idle:
viewModel.clearUploadBatch()
showPhase(viewModel.selectedPoint == nil ? .point : .picker)
case .uploading: break
}
}
}
private func secondaryTapped() {
switch phase {
case .method: break
case .nearby, .point: showPhase(.method)
case .picker: showPhase(.point)
case .queue: finish()
}
}
private func startDemoUpload() {
uploadDriver.start(viewModel: viewModel) { [weak self] in self?.applySnapshot(animated: true) }
}
private func pauseForLeaving() {
uploadDriver.stop()
viewModel.pauseUpload(reason: .leavingPage)
}
private func finish() {
guard !didRequestFinish else { return }
didRequestFinish = true
pauseForLeaving()
if let delegate { delegate.deliveryUploadViewControllerDidFinish(self) }
else if let navigationController { navigationController.dismiss(animated: true) }
else { dismiss(animated: true) }
}
private func configureDebugMenu() {
#if DEBUG
let actions = DroneDeliveryScenario.allCases.map { scenario in
UIAction(title: scenario.title) { [weak self] _ in
guard let self else { return }
self.uploadDriver.stop()
self.viewModel.applyScenario(scenario)
self.showPhase(self.viewModel.batch == nil ? .method : .queue)
}
}
headerView.setDebugMenu(UIMenu(title: "本地交付演示状态", children: actions))
#endif
}
@objc private func applicationWillResignActive() {
uploadDriver.stop()
viewModel.pauseUpload(reason: .background)
if isViewLoaded { applySnapshot(animated: false) }
}
@objc private func applicationDidBecomeActive() {
viewModel.refresh()
if isViewLoaded { applySnapshot(animated: false) }
}
}
extension DroneDeliveryUploadViewController: UICollectionViewDelegate {
/// 卡片与点位整行选择,队列行预览不影响当前批次。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .nearbyMethod: showPhase(.nearby)
case .cloudMethod: showPhase(.point)
case .point(let id): viewModel.selectPoint(id: id); applySnapshot(animated: true)
case .upload(let id):
if let item = uploadItemsByID[id] { delegate?.deliveryUploadViewController(self, didRequestPreview: item.video) }
default: break
}
}
}
extension DroneDeliveryUploadViewController: UIAdaptivePresentationControllerDelegate {
/// 手势关闭 Sheet 后仍暂停未完成上传并刷新原入口。
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() }
}
+16 -1
View File
@@ -6,7 +6,7 @@ import UIKit
enum DroneDockPreview {
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
static func navigationController(arguments: [String]) -> UINavigationController? {
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview", "--dock-ui-materials-preview"]
let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview", "--dock-ui-materials-preview", "--dock-ui-delivery-preview", "--dock-ui-delivery-review-preview"]
guard arguments.contains(where: { entryFlags.contains($0) }) else { return nil }
let store = DroneDockDemoStore()
if let argument = arguments.first(where: { $0.hasPrefix("--dock-ui-scenario=") }),
@@ -59,6 +59,21 @@ enum DroneDockPreview {
materials.delegate = workbench
navigation.setViewControllers([workbench, materials], animated: false)
}
if arguments.contains("--dock-ui-delivery-preview") || arguments.contains("--dock-ui-delivery-review-preview"),
let order = store.orders.first {
let deliveryModel = DroneDeliveryViewModel(store: store, orderID: order.id)
if let argument = arguments.first(where: { $0.hasPrefix("--dock-delivery-scenario=") }),
let scenario = DroneDeliveryScenario(rawValue: String(argument.dropFirst("--dock-delivery-scenario=".count))) {
deliveryModel.applyScenario(scenario)
}
if arguments.contains("--dock-ui-delivery-review-preview") {
let review = DroneDeliveryReviewViewController(viewModel: deliveryModel)
review.delegate = workbench
navigation.setViewControllers([workbench, review], animated: false)
} else {
workbench.prepareDeliveryPreview(orderID: order.id)
}
}
return navigation
}
}
@@ -15,6 +15,10 @@ final class DroneDockWorkbenchViewController: BaseViewController {
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var devicePage = 0
private let pageControl = UIPageControl()
private weak var deliveryPresenter: UIViewController?
#if DEBUG
private var deliveryPreviewOrderID: String?
#endif
/// 默认使用本地演示数据,不会发起请求。
init(viewModel: DroneDockWorkbenchViewModel = DroneDockWorkbenchViewModel()) {
@@ -51,6 +55,21 @@ final class DroneDockWorkbenchViewController: BaseViewController {
navigationItem.backButtonDisplayMode = .minimal
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
#if DEBUG
if let orderID = deliveryPreviewOrderID {
deliveryPreviewOrderID = nil
openDelivery(orderID: orderID, from: self)
}
#endif
}
#if DEBUG
/// 等窗口完成展示后打开本地交付弹层,避免冷启动时抢先 present。
func prepareDeliveryPreview(orderID: String) { deliveryPreviewOrderID = orderID }
#endif
override func setupUI() {
view.backgroundColor = DroneDockStyle.background
collectionView.backgroundColor = .clear
@@ -209,7 +228,7 @@ final class DroneDockWorkbenchViewController: BaseViewController {
navigationController?.pushViewController(controller, animated: true)
}
/// 拍摄和素材进入对应本地页面,成片交付暂保留入口提示。
/// 拍摄、原素材和成片上传分别进入对应本地页面。
private enum OrderEntry { case shooting, materials, delivery }
private func showOrderEntry(id: String, action: OrderEntry) {
@@ -218,8 +237,6 @@ final class DroneDockWorkbenchViewController: BaseViewController {
}
private func showPreviewEntry(order: DroneShootingOrder, action: OrderEntry, presenter: UIViewController? = nil) {
let title: String
let detail: String
switch action {
case .shooting:
openShootingOrder(id: order.id, from: presenter ?? self)
@@ -228,12 +245,8 @@ final class DroneDockWorkbenchViewController: BaseViewController {
openMaterials(orderID: order.id, from: presenter ?? self)
return
case .delivery:
title = "交付成片"
detail = "\(order.deliveredVideoCount) 个已交付视频"
openDelivery(orderID: order.id, from: presenter ?? self)
}
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)
}
/// 始终读取当前范围快照,恢复原任务而不因重新进入重复召唤。
@@ -267,6 +280,39 @@ final class DroneDockWorkbenchViewController: BaseViewController {
presenter.navigationController?.pushViewController(controller, animated: true)
}
private func openDelivery(orderID: String, pointID: String? = nil, from presenter: UIViewController) {
guard viewModel.store.shootingOrder(id: orderID) != nil, presenter.presentedViewController == nil else { return }
let controller = DroneDeliveryUploadViewController(
viewModel: DroneDeliveryViewModel(store: viewModel.store, orderID: orderID, pointID: pointID)
)
controller.delegate = self
deliveryPresenter = presenter
let navigation = UINavigationController(rootViewController: controller)
navigation.setNavigationBarHidden(true, animated: false)
navigation.modalPresentationStyle = .pageSheet
navigation.sheetPresentationController?.detents = [.medium(), .large()]
navigation.sheetPresentationController?.prefersGrabberVisible = true
navigation.sheetPresentationController?.preferredCornerRadius = 24
presenter.present(navigation, animated: true)
}
private func openDeliveryReview(orderID: String, from presenter: UIViewController) {
guard viewModel.store.shootingOrder(id: orderID) != nil else { return }
let controller = DroneDeliveryReviewViewController(
viewModel: DroneDeliveryViewModel(store: viewModel.store, orderID: orderID)
)
controller.delegate = self
presenter.navigationController?.pushViewController(controller, animated: true)
}
private func refreshAfterDelivery(in presenter: UIViewController?) {
viewModel.refresh()
if isViewLoaded { applySnapshot(animated: false) }
if let orders = presenter as? DroneShootingOrdersViewController { orders.refreshOrders() }
if let materials = presenter as? DroneMaterialsViewController { materials.refreshOrderSummary() }
if let review = presenter as? DroneDeliveryReviewViewController { review.refreshDeliveryState() }
}
@objc private func receiptTapped() {
showAlert(title: "收款码", message: "套餐收款页面将在后续搭建,当前不会创建订单或发起收款。")
}
@@ -297,6 +343,9 @@ extension DroneDockWorkbenchViewController: DroneShootingOrdersViewControllerDel
func shootingOrdersViewController(_ controller: DroneShootingOrdersViewController, didSelectDelivery order: DroneShootingOrder) {
showPreviewEntry(order: order, action: .delivery, presenter: controller)
}
func shootingOrdersViewController(_ controller: DroneShootingOrdersViewController, didSelectConfirmation order: DroneShootingOrder) {
openDeliveryReview(orderID: order.id, from: controller)
}
}
extension DroneDockWorkbenchViewController: DroneShootingPreparationViewControllerDelegate {
@@ -334,8 +383,44 @@ extension DroneDockWorkbenchViewController: DroneMaterialsViewControllerDelegate
}
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord) {
guard let order = viewModel.store.shootingOrder(id: controller.viewModel.orderID) else { return }
showPreviewEntry(order: order, action: .delivery, presenter: controller)
openDelivery(orderID: controller.viewModel.orderID, pointID: record.pointID, from: controller)
}
}
extension DroneDockWorkbenchViewController: DroneDeliveryUploadViewControllerDelegate {
func deliveryUploadViewControllerDidFinish(_ controller: DroneDeliveryUploadViewController) {
let presenter = deliveryPresenter
if controller.presentingViewController != nil || controller.navigationController?.presentingViewController != nil {
controller.dismiss(animated: true) { [weak self] in self?.refreshAfterDelivery(in: presenter) }
} else {
refreshAfterDelivery(in: presenter)
}
}
func deliveryUploadViewControllerDidRequestReview(_ controller: DroneDeliveryUploadViewController) {
let presenter = deliveryPresenter ?? self
let orderID = controller.viewModel.orderID
controller.dismiss(animated: true) { [weak self] in
guard let self else { return }
self.refreshAfterDelivery(in: presenter)
if !(presenter is DroneDeliveryReviewViewController) { self.openDeliveryReview(orderID: orderID, from: presenter) }
}
}
func deliveryUploadViewController(_ controller: DroneDeliveryUploadViewController, didRequestPreview video: DroneDeliveryVideo) {
let material = video.previewMaterial
controller.present(DroneMaterialPreviewViewController(items: [material], initialMaterialID: material.id), animated: true)
}
}
extension DroneDockWorkbenchViewController: DroneDeliveryReviewViewControllerDelegate {
func deliveryReviewViewControllerDidRequestUpload(_ controller: DroneDeliveryReviewViewController) {
openDelivery(orderID: controller.viewModel.orderID, from: controller)
}
func deliveryReviewViewController(_ controller: DroneDeliveryReviewViewController, didRequestPreview work: DroneDeliveryWork) {
let materials = controller.previewMaterials
controller.present(DroneMaterialPreviewViewController(items: materials, initialMaterialID: work.id), animated: true)
}
}
@@ -166,7 +166,7 @@ final class DroneMaterialSelectionCell: UICollectionViewCell {
/// 每条拍摄记录的点位、航线、时间与独立的交付入口。
@MainActor
final class DroneMaterialRecordHeaderView: UICollectionReusableView {
/// 交付入口目前只向上层请求展示占位说明。
/// 交付入口向上层请求对应点位的成片上传。
var onDeliveryTap: (() -> Void)?
private let titleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
private let detailLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
@@ -1,12 +1,12 @@
import SnapKit
import UIKit
/// 素材库只提出导航请求,由机巢入口协调预览与尚未实现的交付流程。
/// 素材库只提出导航请求,由机巢入口协调原素材预览与独立成片交付。
@MainActor
protocol DroneMaterialsViewControllerDelegate: AnyObject {
/// 预览单项素材,保持素材库现有选择与下载批次。
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestPreview material: DroneMaterial)
/// 请求当前拍摄记录的交付占位入口。
/// 请求交付成片,并由当前拍摄记录预选点位。
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord)
}
@@ -63,6 +63,11 @@ final class DroneMaterialsViewController: BaseViewController {
/// 返回素材页只刷新快照,不自动继续已暂停的批次。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshOrderSummary()
}
/// 成片弹层关闭后更新订单摘要,保留原素材选择与下载批次。
func refreshOrderSummary() {
viewModel.refresh()
if dataSource != nil { applySnapshot(animated: false) }
}
@@ -10,6 +10,8 @@ final class DroneShootingOrderCardView: UIView {
var onMaterialsTap: (() -> Void)?
/// 用户点击交付入口时触发;具体交付业务由外部协调。
var onDeliveryTap: (() -> Void)?
/// 用户点击整单游客确认或历史记录摘要时触发,与追加上传分开。
var onConfirmationTap: (() -> Void)?
private let contentStack = UIStackView()
private let customerLabel = UILabel()
@@ -132,7 +134,7 @@ final class DroneShootingOrderCardView: UIView {
stateLabel: deliveryStateLabel, chevron: deliveryChevron
)
materialControl.addTarget(self, action: #selector(materialsTapped), for: .touchUpInside)
deliveryControl.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside)
deliveryControl.addTarget(self, action: #selector(confirmationTapped), for: .touchUpInside)
materialRow.axis = .horizontal
materialRow.spacing = 12
materialRow.distribution = .fillEqually
@@ -227,7 +229,8 @@ final class DroneShootingOrderCardView: UIView {
}
private func applyMaterialSummary(order: DroneShootingOrder) {
materialRow.isHidden = !order.hasMaterials
materialRow.isHidden = !order.hasMaterials && order.deliveredVideoCount == 0
materialControl.isHidden = !order.hasMaterials
let isCompleted = order.fulfillmentState == .completed && order.activeTask == nil
materialTitleLabel.text = isCompleted ? "拍摄素材" : "查看素材"
materialChevron.isHidden = isCompleted
@@ -238,9 +241,10 @@ final class DroneShootingOrderCardView: UIView {
let showsDelivery = order.deliveredVideoCount > 0
deliveryControl.isHidden = !showsDelivery
deliveryTitleLabel.text = order.visitorConfirmationState == .confirmed ? "游客已确认" : "请游客确认"
deliveryTitleLabel.text = order.visitorConfirmationState == .confirmed ? "查看记录" : "请游客确认"
deliveryStateLabel.text = "已交付 \(order.deliveredVideoCount) 个视频"
deliveryControl.accessibilityLabel = "\(deliveryTitleLabel.text ?? "交付成片"),\(deliveryStateLabel.text ?? "")"
deliveryControl.accessibilityIdentifier = "drone.order.\(order.id).confirmation"
}
private func applyActions(order: DroneShootingOrder) {
@@ -300,7 +304,7 @@ final class DroneShootingOrderCardView: UIView {
}
@objc private func materialsTapped() { onMaterialsTap?() }
@objc private func deliveryTapped() { onDeliveryTap?() }
@objc private func confirmationTapped() { onConfirmationTap?() }
}
/// Diffable 订单列表使用的自适应高度容器。
@@ -1,15 +1,17 @@
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)
/// 用户请求整单游客确认或查看确认记录。
func shootingOrdersViewController(_ controller: DroneShootingOrdersViewController, didSelectConfirmation order: DroneShootingOrder)
}
/// 当前用户在当前景区的拍摄订单页面;使用本地 ViewModel 展示四种履约分类。
@@ -41,8 +43,13 @@ final class DroneShootingOrdersViewController: BaseViewController {
/// 回到页面后读取共享的本地快照,不创建或重新发送任务。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshOrders()
}
/// 成片弹层关闭后主动读取共享摘要,保留当前 Tab 与滚动位置。
func refreshOrders() {
viewModel.refresh()
applySnapshot(animatingDifferences: false)
if isViewLoaded { applySnapshot(animatingDifferences: false) }
}
override func setupNavigationBar() {
@@ -151,6 +158,10 @@ final class DroneShootingOrdersViewController: BaseViewController {
guard let self else { return }
self.delegate?.shootingOrdersViewController(self, didSelectDelivery: order)
}
cell.cardView.onConfirmationTap = { [weak self] in
guard let self else { return }
self.delegate?.shootingOrdersViewController(self, didSelectConfirmation: order)
}
return cell
}
dataSource?.supplementaryViewProvider = { [weak self] list, kind, indexPath in