feat(drone-dock): 接入成片云端交付并精简准备页定位展示
This commit is contained in:
@@ -27,7 +27,8 @@ final class UploadAPI {
|
||||
APIRequest(
|
||||
method: .get,
|
||||
path: "/api/app/config/get-sts-token",
|
||||
queryItems: [URLQueryItem(name: "bucket", value: bucket)]
|
||||
queryItems: [URLQueryItem(name: "bucket", value: bucket)],
|
||||
logsPayload: false
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import Foundation
|
||||
|
||||
/// 成片交付复用订单素材查询,并在 OSS 上传完成后保存指定任务的成片。
|
||||
protocol DroneDockDeliveryServing: DroneDockMaterialsServing {
|
||||
/// 保存或替换一个任务的唯一视频成片;此接口不上传文件二进制。
|
||||
@MainActor
|
||||
func saveFilm(scenicID: Int, taskID: Int, fileURL: String, fileName: String) async throws -> DroneDockSavedFilm
|
||||
}
|
||||
|
||||
/// 张工云端交付接口,保留素材查询的订单归属校验与统一鉴权。
|
||||
@MainActor
|
||||
final class DroneDockDeliveryAPI: DroneDockDeliveryServing {
|
||||
private let client: APIClient
|
||||
private let materials: DroneDockMaterialsAPI
|
||||
|
||||
/// 注入统一客户端,查询和保存使用同一当前登录凭证。
|
||||
init(client: APIClient) {
|
||||
self.client = client
|
||||
materials = DroneDockMaterialsAPI(client: client)
|
||||
}
|
||||
|
||||
/// 读取整单点位和当前上传权限。
|
||||
func detail(scenicID: Int, orderNumber: String) async throws -> DroneDockMaterialDetail {
|
||||
try await materials.detail(scenicID: scenicID, orderNumber: orderNumber)
|
||||
}
|
||||
|
||||
/// 读取有效任务及各自成片,不以点位代替 task_id。
|
||||
func tasks(scenicID: Int, orderNumber: String, spotID: Int?) async throws -> DroneDockMaterialTasks {
|
||||
try await materials.tasks(scenicID: scenicID, orderNumber: orderNumber, spotID: spotID)
|
||||
}
|
||||
|
||||
/// 只提交已上传的视频原始地址,响应身份与文件必须对应本次保存。
|
||||
func saveFilm(scenicID: Int, taskID: Int, fileURL: String, fileName: String) async throws -> DroneDockSavedFilm {
|
||||
guard scenicID > 0, taskID > 0 else { throw DroneDockFilmError.invalidScope }
|
||||
_ = try DroneDockFilmPolicy.contentType(fileName: fileName)
|
||||
guard DroneDockFilmPolicy.remoteURL(fileURL) != nil else {
|
||||
throw APIError.networkFailed("成片地址无效,请重新上传视频")
|
||||
}
|
||||
let response: DroneDockSavedFilm = try await client.send(APIRequest(
|
||||
method: .post, path: "/api/yf-handset-app/photog/multi-plane/tasks/film",
|
||||
body: SaveFilmBody(scenicID: scenicID, taskID: taskID, fileURL: fileURL, fileName: fileName)
|
||||
))
|
||||
guard response.taskID == taskID, response.film.fileURL == fileURL else {
|
||||
throw APIError.decodeFailed("保存结果与当前任务或视频不一致,请刷新后核对")
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
/// 保存仅需四项业务参数,封面和大小由后端读取文件生成。
|
||||
private struct SaveFilmBody: Encodable {
|
||||
let scenicID: Int
|
||||
let taskID: Int
|
||||
let fileURL: String
|
||||
let fileName: String
|
||||
|
||||
/// 张工成片保存字段。
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case scenicID = "scenic_id", taskID = "task_id", fileURL = "file_url", fileName = "file_name"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import Foundation
|
||||
|
||||
/// 用户本次选择的一段本地视频;标识用于隔离重新选择后的上传回调。
|
||||
struct DroneDockDeliveryVideo: Equatable, Sendable {
|
||||
/// 每次选择产生独立身份,即使来源文件相同也不复用旧上传状态。
|
||||
let id: UUID
|
||||
/// App 已复制并持有的本地文件地址。
|
||||
let url: URL
|
||||
/// 提交给成片接口的文件名称。
|
||||
let fileName: String
|
||||
/// 选择时读取的实际字节数。
|
||||
let fileSize: Int
|
||||
|
||||
/// 建立独立的待上传视频,不在模型内读取文件内容。
|
||||
init(url: URL, fileName: String, fileSize: Int) {
|
||||
id = UUID()
|
||||
self.url = url
|
||||
self.fileName = fileName
|
||||
self.fileSize = fileSize
|
||||
}
|
||||
}
|
||||
|
||||
/// 张工保存成片的结果,只有与选中任务一致的有效视频才视为保存成功。
|
||||
struct DroneDockSavedFilm: Decodable, Equatable, Sendable {
|
||||
/// 成片保存到的订单飞行任务 ID。
|
||||
let taskID: Int
|
||||
/// 服务端读取文件后生成的成片与封面信息。
|
||||
let film: DroneDockMaterialFilm
|
||||
|
||||
/// 成片保存响应字段。
|
||||
private enum CodingKeys: String, CodingKey { case taskID = "task_id", film }
|
||||
|
||||
/// 兼容整数字符串身份,拒绝空成片、跨任务成片及无效视频地址。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
if let value = try? container.decode(Int.self, forKey: .taskID) { taskID = value }
|
||||
else if let text = try? container.decode(String.self, forKey: .taskID), let value = Int(text) { taskID = value }
|
||||
else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .taskID, in: container, debugDescription: "保存成片缺少有效任务 ID")
|
||||
}
|
||||
film = try container.decode(DroneDockMaterialFilm.self, forKey: .film)
|
||||
guard taskID > 0, film.taskID == nil || film.taskID == taskID,
|
||||
let fileURL = film.fileURL, DroneDockFilmPolicy.remoteURL(fileURL) != nil else {
|
||||
throw DecodingError.dataCorruptedError(forKey: .film, in: container, debugDescription: "保存成片返回的任务或视频地址无效")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 成片保存和 OSS 上传共用的格式规则,避免把原素材类型值当成上传 MIME。
|
||||
enum DroneDockFilmPolicy {
|
||||
/// 沿用 App 通用上传的单文件大小上限,流式上传不整体载入内存。
|
||||
static let maximumFileSize = 2_048 * 1_024 * 1_024
|
||||
private static let mimeTypes = ["mp4": "video/mp4", "mov": "video/quicktime", "avi": "video/x-msvideo",
|
||||
"mkv": "video/x-matroska", "flv": "video/x-flv", "wmv": "video/x-ms-wmv", "webm": "video/webm"]
|
||||
|
||||
/// 校验本地视频没有丢失或变化,返回明确的 video/* MIME。
|
||||
static func validate(video: DroneDockDeliveryVideo) throws -> String {
|
||||
guard video.url.isFileURL else { throw DroneDockFilmError.invalidLocalFile }
|
||||
let type = try contentType(fileName: video.fileName)
|
||||
// URL.resourceValues 会缓存大小;上传前复查必须重新读取文件系统属性。
|
||||
let attributes = try FileManager.default.attributesOfItem(atPath: video.url.path)
|
||||
guard attributes[.type] as? FileAttributeType == .typeRegular,
|
||||
let size = (attributes[.size] as? NSNumber)?.intValue else { throw DroneDockFilmError.invalidLocalFile }
|
||||
guard size > 0 else { throw DroneDockFilmError.emptyFile }
|
||||
guard size <= maximumFileSize else { throw DroneDockFilmError.fileTooLarge }
|
||||
guard size == video.fileSize else { throw DroneDockFilmError.fileChanged }
|
||||
return type
|
||||
}
|
||||
|
||||
/// 文件名保留用户可读内容,禁止目录和控制字符进入对象键或请求体。
|
||||
static func contentType(fileName: String) throws -> String {
|
||||
guard !fileName.isEmpty, fileName.count <= 255,
|
||||
fileName == fileName.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||
fileName.rangeOfCharacter(from: .controlCharacters) == nil,
|
||||
!fileName.contains("/"), !fileName.contains("\\") else { throw DroneDockFilmError.invalidFileName }
|
||||
guard let type = mimeTypes[URL(fileURLWithPath: fileName).pathExtension.lowercased()] else {
|
||||
throw DroneDockFilmError.unsupportedFileType
|
||||
}
|
||||
return type
|
||||
}
|
||||
|
||||
/// 提交无查询参数的原始 OSS 视频地址,不接受本地地址或临时签名链接。
|
||||
static func remoteURL(_ value: String) -> URL? {
|
||||
guard value.count <= 2048, value.rangeOfCharacter(from: .whitespacesAndNewlines) == nil,
|
||||
let components = URLComponents(string: value),
|
||||
["http", "https"].contains(components.scheme?.lowercased() ?? ""),
|
||||
let host = components.host, !host.isEmpty,
|
||||
components.user == nil, components.password == nil,
|
||||
components.query == nil, components.fragment == nil,
|
||||
let url = components.url, mimeTypes[url.pathExtension.lowercased()] != nil else { return nil }
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
/// 成片文件和上传配置错误,不含 STS 密钥或访问凭证。
|
||||
enum DroneDockFilmError: LocalizedError, Equatable {
|
||||
case invalidLocalFile, emptyFile, fileTooLarge, fileChanged, invalidFileName, unsupportedFileType, invalidConfiguration, invalidScope
|
||||
|
||||
/// 向页面提供可操作的错误说明。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidLocalFile: "视频文件不可用,请重新选择"
|
||||
case .emptyFile: "视频文件为空,请重新选择"
|
||||
case .fileTooLarge: "视频超过 2GB,请压缩后重试"
|
||||
case .fileChanged: "视频文件已变化,请重新选择"
|
||||
case .invalidFileName: "视频文件名称无效或超过 255 个字符"
|
||||
case .unsupportedFileType: "请选择 MP4、MOV、AVI、MKV、FLV、WMV 或 WebM 视频"
|
||||
case .invalidConfiguration: "上传配置暂不可用,请重试"
|
||||
case .invalidScope: "缺少有效景区或拍摄任务,请重新进入"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import Foundation
|
||||
|
||||
#if canImport(AlibabaCloudOSS)
|
||||
import AlibabaCloudOSS
|
||||
#endif
|
||||
|
||||
/// 将用户选择的视频上传至 OSS,返回可提交给张工成片接口的原始地址。
|
||||
protocol DroneDockFilmUploading: Sendable {
|
||||
/// 上传以文件为单位执行,进度在主线程回传;100 表示 OSS 已成功接收。
|
||||
@MainActor
|
||||
func upload(video: DroneDockDeliveryVideo, scenicID: Int,
|
||||
onProgress: @escaping @MainActor @Sendable (Int) -> Void) async throws -> String
|
||||
}
|
||||
|
||||
/// OSS 文件传输边界,生产使用 SDK,单元测试不访问外部存储。
|
||||
protocol DroneDockFilmTransporting: Sendable {
|
||||
/// 使用服务端临时配置和文件流上传,不把整个视频载入内存。
|
||||
@MainActor
|
||||
func put(fileURL: URL, objectKey: String, contentType: String, configuration: AliyunOSSResponse,
|
||||
onProgress: @escaping @MainActor @Sendable (Int) -> Void) async throws
|
||||
}
|
||||
|
||||
/// 云端成片上传器,复用 STS 服务与通用对象键规则,按配置返回原始 OSS 地址。
|
||||
@MainActor
|
||||
final class DroneDockFilmUploader: DroneDockFilmUploading {
|
||||
private let configService: any OSSConfigServing
|
||||
private let transport: any DroneDockFilmTransporting
|
||||
|
||||
/// 注入上传配置及传输实现;正式页面默认使用阿里云 SDK。
|
||||
init(configService: any OSSConfigServing, transport: (any DroneDockFilmTransporting)? = nil) {
|
||||
self.configService = configService
|
||||
self.transport = transport ?? DroneDockOSSFilmTransport()
|
||||
}
|
||||
|
||||
/// 文件与临时凭证都有效时才开始上传,取消或失败不会返回成功地址。
|
||||
func upload(video: DroneDockDeliveryVideo, scenicID: Int,
|
||||
onProgress: @escaping @MainActor @Sendable (Int) -> Void) async throws -> String {
|
||||
try Task.checkCancellation()
|
||||
guard scenicID > 0 else { throw DroneDockFilmError.invalidScope }
|
||||
let contentType = try DroneDockFilmPolicy.validate(video: video)
|
||||
let progress = DroneDockFilmProgress(onProgress: onProgress)
|
||||
defer { progress.close() }
|
||||
progress.report(1)
|
||||
let configuration = try await configService.aliyunOSSBucket(bucket: "default")
|
||||
try Task.checkCancellation()
|
||||
try validate(configuration: configuration)
|
||||
_ = try DroneDockFilmPolicy.validate(video: video)
|
||||
let objectKey = OSSUploadPolicy.objectKey(fileName: video.fileName, scenicId: scenicID, moduleType: "task_upload")
|
||||
var allowed = CharacterSet.urlPathAllowed
|
||||
allowed.remove(charactersIn: "?#%")
|
||||
guard let escapedKey = objectKey.addingPercentEncoding(withAllowedCharacters: allowed) else {
|
||||
throw DroneDockFilmError.invalidFileName
|
||||
}
|
||||
let fileURL = OSSUploadPolicy.joinURL(baseURL: configuration.baseUrl, objectKey: escapedKey)
|
||||
guard DroneDockFilmPolicy.remoteURL(fileURL) != nil else { throw DroneDockFilmError.invalidConfiguration }
|
||||
progress.report(10)
|
||||
try await transport.put(fileURL: video.url, objectKey: objectKey, contentType: contentType,
|
||||
configuration: configuration) { value in
|
||||
progress.report(10 + min(100, max(0, value)) * 89 / 100)
|
||||
}
|
||||
try Task.checkCancellation()
|
||||
progress.finish()
|
||||
return fileURL
|
||||
}
|
||||
|
||||
private func validate(configuration: AliyunOSSResponse) throws {
|
||||
guard let base = URLComponents(string: configuration.baseUrl),
|
||||
["https", "http"].contains(base.scheme?.lowercased() ?? ""),
|
||||
let host = base.host, !host.isEmpty,
|
||||
base.user == nil, base.password == nil, base.query == nil, base.fragment == nil,
|
||||
configuration.baseUrl.rangeOfCharacter(from: .whitespacesAndNewlines) == nil,
|
||||
!configuration.endpoint.isEmpty, !configuration.region.isEmpty, !configuration.bucket.isEmpty,
|
||||
configuration.expireSeconds > 0,
|
||||
!configuration.credentials.accessKeyId.isEmpty,
|
||||
!configuration.credentials.accessKeySecret.isEmpty,
|
||||
!configuration.credentials.securityToken.isEmpty else { throw DroneDockFilmError.invalidConfiguration }
|
||||
}
|
||||
}
|
||||
|
||||
/// 阿里云 SDK 的文件上传实现,与既有上传服务使用相同的临时凭证和 endpoint。
|
||||
@MainActor
|
||||
struct DroneDockOSSFilmTransport: DroneDockFilmTransporting {
|
||||
/// SDK 的 .file body 走 URLSession 文件上传,进度从网络回调切回主线程。
|
||||
func put(fileURL: URL, objectKey: String, contentType: String, configuration: AliyunOSSResponse,
|
||||
onProgress: @escaping @MainActor @Sendable (Int) -> Void) async throws {
|
||||
try Task.checkCancellation()
|
||||
#if canImport(AlibabaCloudOSS)
|
||||
let credentials = StaticCredentialsProvider(accessKeyId: configuration.credentials.accessKeyId,
|
||||
accessKeySecret: configuration.credentials.accessKeySecret, securityToken: configuration.credentials.securityToken)
|
||||
let sdkConfiguration = Configuration.default().withRegion(configuration.region).withCredentialsProvider(credentials)
|
||||
sdkConfiguration.withEndpoint(configuration.endpoint)
|
||||
let client = Client(sdkConfiguration)
|
||||
_ = try await client.putObject(PutObjectRequest(
|
||||
bucket: configuration.bucket, key: objectKey, contentType: contentType, body: .file(fileURL),
|
||||
progress: ProgressClosure { _, transferred, expected in
|
||||
guard expected > 0 else { return }
|
||||
let value = Int(min(100, max(0, Double(transferred) / Double(expected) * 100)))
|
||||
Task { @MainActor in onProgress(value) }
|
||||
}
|
||||
))
|
||||
try Task.checkCancellation()
|
||||
#else
|
||||
throw OSSUploadError.sdkUnavailable
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// 丢弃已结束上传的迟到回调,并防止进度倒退或上传失败提前显示 100%。
|
||||
@MainActor
|
||||
private final class DroneDockFilmProgress {
|
||||
private var latest = -1
|
||||
private var isClosed = false
|
||||
private let onProgress: @MainActor @Sendable (Int) -> Void
|
||||
|
||||
init(onProgress: @escaping @MainActor @Sendable (Int) -> Void) { self.onProgress = onProgress }
|
||||
|
||||
func report(_ value: Int) {
|
||||
guard !isClosed, value > latest else { return }
|
||||
latest = value
|
||||
onProgress(value)
|
||||
}
|
||||
|
||||
func finish() { report(100); close() }
|
||||
func close() { isClosed = true }
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
import Foundation
|
||||
|
||||
/// 云端交付区分校验、文件上传和业务保存,OSS 上传完成不代表交付完成。
|
||||
enum DroneDockDeliveryPhase: Equatable, Sendable {
|
||||
case idle, validating, uploading, saving, succeeded
|
||||
}
|
||||
|
||||
/// 两个入口共用的成片交付状态;每个视频明确绑定一个有效拍摄任务。
|
||||
final class DroneDockDeliveryViewModel {
|
||||
/// 页面进入时冻结的账号、景区与门店身份。
|
||||
let context: DroneDockHomeContext
|
||||
/// 入口订单仅用于确定身份,权限始终重新读取。
|
||||
let order: DroneDockHomeOrder
|
||||
/// 当前服务端整单摘要与点位快照。
|
||||
private(set) var detail: DroneDockMaterialDetail?
|
||||
/// 全部有效任务,点位选择只改变本地候选列表。
|
||||
private(set) var tasks: [DroneDockMaterialTask] = []
|
||||
/// 当前明确选择的购买点位。
|
||||
private(set) var selectedSpotID: Int?
|
||||
/// 当前明确选择的拍摄任务。
|
||||
private(set) var selectedTaskID: Int?
|
||||
/// 当前选择的单个本地视频。
|
||||
private(set) var video: DroneDockDeliveryVideo?
|
||||
/// 是否正在读取首屏或刷新订单数据。
|
||||
private(set) var isLoading = false
|
||||
/// 校验、上传、保存和成功后刷新期间冻结选择。
|
||||
private(set) var isSubmitting = false
|
||||
/// 文件上传进度;业务保存阶段即使为 100 仍不表示交付成功。
|
||||
private(set) var progress = 0
|
||||
/// 当前提交阶段。
|
||||
private(set) var phase: DroneDockDeliveryPhase = .idle
|
||||
/// 首屏或会话范围读取错误。
|
||||
private(set) var loadErrorMessage: String?
|
||||
/// 最近一次上传或保存错误,重试前会重新核对服务端任务。
|
||||
private(set) var submissionErrorMessage: String?
|
||||
/// 仅明确保存成功或查询确认已保存后显示。
|
||||
private(set) var successMessage: String?
|
||||
/// 保存成功后的列表刷新失败,不将已成功保存误报为失败。
|
||||
private(set) var refreshWarning: String?
|
||||
/// 最近一次明确保存成功的成片,刷新失败时仍保留回执。
|
||||
private(set) var lastSavedFilm: DroneDockMaterialFilm?
|
||||
|
||||
/// 全部购买点位,保留服务端顺序。
|
||||
var spots: [DroneDockMaterialSpot] { detail?.spots ?? [] }
|
||||
/// 当前点位的有效任务,不能用任务数推导拍摄次数或上传权限。
|
||||
var filteredTasks: [DroneDockMaterialTask] {
|
||||
guard let selectedSpotID else { return [] }
|
||||
return tasks.filter { $0.spotID == selectedSpotID }
|
||||
}
|
||||
/// 当前任务必须仍属于当前选择的点位。
|
||||
var selectedTask: DroneDockMaterialTask? {
|
||||
filteredTasks.first { $0.id == selectedTaskID }
|
||||
}
|
||||
/// 已上传但业务保存尚未确认的文件地址,失败重试可以复用。
|
||||
var uploadedFileURL: String? { pendingUpload?.url }
|
||||
/// 当前任务已有成片时,用户必须明确确认替换。
|
||||
var needsReplacementConfirmation: Bool {
|
||||
guard let selectedTask, selectedTask.film != nil else { return false }
|
||||
return !isPendingFilm(selectedTask)
|
||||
}
|
||||
/// 只有最新可交付订单中的有效任务可选择视频。
|
||||
var canChooseVideo: Bool {
|
||||
!isLoading && !isSubmitting && loadErrorMessage == nil && canUpload && selectedTask != nil
|
||||
}
|
||||
/// 成功后需重新选择视频才能再次提交,避免重复点击保存同一文件。
|
||||
var canSubmit: Bool {
|
||||
!isLoading && !isSubmitting && loadErrorMessage == nil && selectedTask != nil && video != nil
|
||||
&& phase != .succeeded && (canUpload || pendingUpload != nil)
|
||||
}
|
||||
|
||||
/// 上传回执与选中视频、任务绑定,不能被复用到其他任务。
|
||||
private struct PendingUpload {
|
||||
let videoID: UUID
|
||||
let taskID: Int
|
||||
let url: String
|
||||
}
|
||||
|
||||
private let service: any DroneDockDeliveryServing
|
||||
private let uploader: any DroneDockFilmUploading
|
||||
private let initialTaskID: Int?
|
||||
private let currentContext: @MainActor @Sendable () -> DroneDockHomeContext
|
||||
private var didResolveInitialTask = false
|
||||
private var generation = 0
|
||||
private var pendingUpload: PendingUpload?
|
||||
|
||||
/// 素材库可传任务 ID,订单列表入口不预选任务;依赖均可替换测试。
|
||||
init(context: DroneDockHomeContext, order: DroneDockHomeOrder,
|
||||
service: any DroneDockDeliveryServing, uploader: any DroneDockFilmUploading,
|
||||
initialTaskID: Int? = nil,
|
||||
currentContext: @escaping @MainActor @Sendable () -> DroneDockHomeContext) {
|
||||
self.context = context
|
||||
self.order = order
|
||||
self.service = service
|
||||
self.uploader = uploader
|
||||
self.initialTaskID = initialTaskID
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 读取最新摘要与全部任务,不自动替用户选择另一条任务。
|
||||
@MainActor
|
||||
func refresh() async {
|
||||
guard !isSubmitting else { return }
|
||||
generation &+= 1
|
||||
let requestGeneration = generation
|
||||
isLoading = true
|
||||
loadErrorMessage = nil
|
||||
defer { if generation == requestGeneration { isLoading = false } }
|
||||
guard accepts(requestGeneration) else { return }
|
||||
guard context.canLoad, orderNumber != nil else {
|
||||
clearSnapshot()
|
||||
loadErrorMessage = "缺少景区、门店或订单信息,请返回订单列表重新进入"
|
||||
return
|
||||
}
|
||||
do {
|
||||
let snapshot = try await readSnapshot(requestGeneration)
|
||||
apply(snapshot)
|
||||
if !didResolveInitialTask {
|
||||
didResolveInitialTask = true
|
||||
if let initialTaskID {
|
||||
if let task = tasks.first(where: { $0.id == initialTaskID }) {
|
||||
selectedSpotID = task.spotID
|
||||
selectedTaskID = task.id
|
||||
} else {
|
||||
submissionErrorMessage = "原拍摄任务已不可用,请重新选择任务"
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
guard accepts(requestGeneration) else { return }
|
||||
clearSnapshot()
|
||||
loadErrorMessage = Self.message(for: error)
|
||||
}
|
||||
}
|
||||
|
||||
/// 选择点位后清除旧任务和视频,不将成片误提交到其他点位。
|
||||
@MainActor
|
||||
func selectSpot(id: Int) {
|
||||
guard !isLoading, !isSubmitting, id != selectedSpotID, spots.contains(where: { $0.id == id }) else { return }
|
||||
selectedSpotID = id
|
||||
selectedTaskID = nil
|
||||
resetSubmission()
|
||||
}
|
||||
|
||||
/// 任务需属于当前点位;切换任务清除与原任务绑定的文件。
|
||||
@MainActor
|
||||
func selectTask(id: Int) {
|
||||
guard !isLoading, !isSubmitting, id != selectedTaskID, filteredTasks.contains(where: { $0.id == id }) else { return }
|
||||
selectedTaskID = id
|
||||
resetSubmission()
|
||||
}
|
||||
|
||||
/// 接受已复制到应用临时目录的单个非空视频,上传中不可更换。
|
||||
@MainActor
|
||||
func selectVideo(_ video: DroneDockDeliveryVideo) {
|
||||
guard canChooseVideo else { return }
|
||||
guard video.url.isFileURL, video.fileSize > 0, !video.fileName.isEmpty else {
|
||||
submissionErrorMessage = "视频文件无效,请重新选择"
|
||||
return
|
||||
}
|
||||
do { _ = try DroneDockFilmPolicy.contentType(fileName: video.fileName) }
|
||||
catch { submissionErrorMessage = error.localizedDescription; return }
|
||||
resetSubmission()
|
||||
self.video = video
|
||||
}
|
||||
|
||||
/// 手动移除视频同时放弃尚未保存的上传回执。
|
||||
@MainActor
|
||||
func removeVideo() {
|
||||
guard !isSubmitting else { return }
|
||||
resetSubmission()
|
||||
}
|
||||
|
||||
/// 上传并保存一条成片;保存失败保留 OSS 地址,重试先查询是否已经保存。
|
||||
@MainActor
|
||||
func submit(confirmReplacement: Bool = false,
|
||||
onProgress: @escaping @MainActor (Int) -> Void = { _ in }) async {
|
||||
guard canSubmit, let task = selectedTask, let video else { return }
|
||||
if task.film != nil && !confirmReplacement && !isPendingFilm(task) {
|
||||
submissionErrorMessage = "该任务已有成片,请确认替换后再上传"
|
||||
return
|
||||
}
|
||||
generation &+= 1
|
||||
let requestGeneration = generation
|
||||
isSubmitting = true
|
||||
submissionErrorMessage = nil
|
||||
refreshWarning = nil
|
||||
successMessage = nil
|
||||
phase = .validating
|
||||
onProgress(progress)
|
||||
defer {
|
||||
if generation == requestGeneration {
|
||||
isSubmitting = false
|
||||
if phase != .succeeded { phase = .idle }
|
||||
}
|
||||
}
|
||||
do {
|
||||
let snapshot = try await readSnapshot(requestGeneration)
|
||||
apply(snapshot)
|
||||
let freshTask = try currentTarget(taskID: task.id, spotID: task.spotID)
|
||||
if let pending = pendingUpload, pending.videoID == video.id, pending.taskID == task.id,
|
||||
let film = freshTask.film, film.fileURL == pending.url {
|
||||
markSaved(film)
|
||||
onProgress(progress)
|
||||
return
|
||||
}
|
||||
try validatePermissionAndReplacement(current: freshTask, expectedFilm: task.film, confirmed: confirmReplacement)
|
||||
|
||||
let fileURL: String
|
||||
if let pending = pendingUpload, pending.videoID == video.id, pending.taskID == task.id {
|
||||
fileURL = pending.url
|
||||
} else {
|
||||
phase = .uploading
|
||||
progress = 0
|
||||
onProgress(progress)
|
||||
let url = try await uploader.upload(video: video, scenicID: context.scenicID) { [weak self] value in
|
||||
guard let self, self.accepts(requestGeneration), self.isSubmitting, self.phase == .uploading else { return }
|
||||
self.progress = max(self.progress, min(100, max(0, value)))
|
||||
onProgress(self.progress)
|
||||
}
|
||||
guard accepts(requestGeneration) else { return }
|
||||
guard DroneDockFilmPolicy.remoteURL(url) != nil else {
|
||||
throw APIError.decodeFailed("上传地址无效,请重新上传视频")
|
||||
}
|
||||
pendingUpload = PendingUpload(videoID: video.id, taskID: task.id, url: url)
|
||||
fileURL = url
|
||||
// 上传期间订单可能完成、任务可能失效或成片被他人替换,保存前再次核对。
|
||||
phase = .validating
|
||||
onProgress(progress)
|
||||
let current = try await readSnapshot(requestGeneration)
|
||||
apply(current)
|
||||
let currentTask = try currentTarget(taskID: task.id, spotID: task.spotID)
|
||||
try validatePermissionAndReplacement(current: currentTask, expectedFilm: freshTask.film, confirmed: confirmReplacement)
|
||||
}
|
||||
guard accepts(requestGeneration) else { return }
|
||||
phase = .saving
|
||||
progress = 100
|
||||
onProgress(progress)
|
||||
let result = try await service.saveFilm(scenicID: context.scenicID, taskID: task.id,
|
||||
fileURL: fileURL, fileName: video.fileName)
|
||||
guard accepts(requestGeneration) else { return }
|
||||
guard result.taskID == task.id, result.film.taskID == nil || result.film.taskID == task.id,
|
||||
result.film.fileURL == fileURL else {
|
||||
throw APIError.decodeFailed("成片保存结果不一致,请重试核对")
|
||||
}
|
||||
markSaved(result.film)
|
||||
onProgress(progress)
|
||||
do {
|
||||
let current = try await readSnapshot(requestGeneration)
|
||||
apply(current)
|
||||
} catch {
|
||||
guard accepts(requestGeneration) else { return }
|
||||
refreshWarning = "成片已保存,列表刷新失败,请稍后刷新"
|
||||
}
|
||||
} catch {
|
||||
guard accepts(requestGeneration) else { return }
|
||||
submissionErrorMessage = Self.message(for: error)
|
||||
}
|
||||
}
|
||||
|
||||
/// 确认离开页面后清除内容,拒绝文件上传或保存的迟到回调。
|
||||
@MainActor
|
||||
func invalidate() {
|
||||
generation &+= 1
|
||||
clearSnapshot()
|
||||
isLoading = false
|
||||
isSubmitting = false
|
||||
loadErrorMessage = nil
|
||||
}
|
||||
|
||||
private var orderNumber: String? {
|
||||
guard let number = order.orderNumber, !number.isEmpty,
|
||||
number == number.trimmingCharacters(in: .whitespacesAndNewlines) else { return nil }
|
||||
return number
|
||||
}
|
||||
|
||||
private var canUpload: Bool { detail?.order.canUploadFilm == true && detail?.order.orderStatus == 20 }
|
||||
|
||||
private func isPendingFilm(_ task: DroneDockMaterialTask) -> Bool {
|
||||
guard let pendingUpload, pendingUpload.videoID == video?.id, pendingUpload.taskID == task.id else { return false }
|
||||
return task.film?.fileURL == pendingUpload.url
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func accepts(_ requestGeneration: Int) -> Bool {
|
||||
guard generation == requestGeneration, !Task.isCancelled else { return false }
|
||||
guard context.hasSameIdentity(as: currentContext()) else {
|
||||
invalidate()
|
||||
loadErrorMessage = "账号或景区已变化,请返回订单列表重新进入"
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func readSnapshot(_ requestGeneration: Int) async throws -> (DroneDockMaterialDetail, [DroneDockMaterialTask]) {
|
||||
guard accepts(requestGeneration), context.canLoad, let number = orderNumber else { throw CancellationError() }
|
||||
let detail = try await service.detail(scenicID: context.scenicID, orderNumber: number)
|
||||
guard accepts(requestGeneration) else { throw CancellationError() }
|
||||
guard detail.order.orderNumber == number else { throw APIError.decodeFailed("交付订单不一致,请返回订单列表重新进入") }
|
||||
let response = try await service.tasks(scenicID: context.scenicID, orderNumber: number, spotID: nil)
|
||||
guard accepts(requestGeneration) else { throw CancellationError() }
|
||||
let spotIDs = Set(detail.spots.map(\.id))
|
||||
guard response.orderNumber == number, response.total == response.list.count,
|
||||
Set(response.list.map(\.id)).count == response.list.count,
|
||||
response.list.allSatisfy({ $0.orderNumber == number && spotIDs.contains($0.spotID) }) else {
|
||||
throw APIError.decodeFailed("拍摄任务与订单或点位不一致,请刷新重试")
|
||||
}
|
||||
return (detail, response.list)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func apply(_ snapshot: (DroneDockMaterialDetail, [DroneDockMaterialTask])) {
|
||||
detail = snapshot.0
|
||||
tasks = snapshot.1
|
||||
if let selectedSpotID, !spots.contains(where: { $0.id == selectedSpotID }) { self.selectedSpotID = nil }
|
||||
if selectedTaskID != nil && selectedTask == nil {
|
||||
selectedTaskID = nil
|
||||
video = nil
|
||||
pendingUpload = nil
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func currentTarget(taskID: Int, spotID: Int) throws -> DroneDockMaterialTask {
|
||||
guard let task = tasks.first(where: { $0.id == taskID && $0.spotID == spotID }),
|
||||
selectedTaskID == taskID, selectedSpotID == spotID else {
|
||||
throw APIError.networkFailed("拍摄任务已不可用,请重新选择任务")
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func validatePermissionAndReplacement(current task: DroneDockMaterialTask,
|
||||
expectedFilm: DroneDockMaterialFilm?, confirmed: Bool) throws {
|
||||
guard canUpload else { throw APIError.networkFailed("当前订单不可上传成片,请返回订单列表刷新") }
|
||||
guard task.film == expectedFilm else { throw APIError.networkFailed("该任务的成片已更新,请核对后重新确认替换") }
|
||||
guard task.film == nil || confirmed else { throw APIError.networkFailed("该任务已有成片,请确认替换后再上传") }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func markSaved(_ film: DroneDockMaterialFilm) {
|
||||
lastSavedFilm = film
|
||||
pendingUpload = nil
|
||||
phase = .succeeded
|
||||
progress = 100
|
||||
submissionErrorMessage = nil
|
||||
successMessage = "成片交付成功"
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func resetSubmission() {
|
||||
video = nil
|
||||
pendingUpload = nil
|
||||
phase = .idle
|
||||
progress = 0
|
||||
submissionErrorMessage = nil
|
||||
successMessage = nil
|
||||
refreshWarning = nil
|
||||
lastSavedFilm = nil
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func clearSnapshot() {
|
||||
detail = nil
|
||||
tasks = []
|
||||
selectedSpotID = nil
|
||||
selectedTaskID = nil
|
||||
resetSubmission()
|
||||
}
|
||||
|
||||
private static func message(for error: Error) -> String? {
|
||||
error is CancellationError ? nil : error.localizedDescription
|
||||
}
|
||||
}
|
||||
@@ -100,10 +100,6 @@ final class DroneDockPreparationViewModel {
|
||||
var connectionTitle: String { "机巢连接待确认" }
|
||||
/// 设备连接未知时使用中性色。
|
||||
var connectionTone: DroneDockStatusTone { .gray }
|
||||
/// 当前未读取位置与范围数据。
|
||||
var rangeTitle: String { "位置待确认" }
|
||||
/// 范围未知时使用中性色。
|
||||
var rangeTone: DroneDockStatusTone { .gray }
|
||||
/// 以购买快照中的名称展示当前选择。
|
||||
var selectionSummary: String {
|
||||
guard let selectedSpot else { return "请选择拍摄点" }
|
||||
|
||||
@@ -77,10 +77,6 @@ final class DroneShootingPreparationViewModel {
|
||||
default: .green
|
||||
}
|
||||
}
|
||||
/// 底部所选点位范围文字。
|
||||
var rangeTitle: String { selectedPoint?.range.admissionTitle ?? "未选择拍摄点" }
|
||||
/// 底部范围语义色。
|
||||
var rangeTone: DroneDockStatusTone { selectedPoint?.range.tone ?? .gray }
|
||||
/// 设备与有效电量摘要,未知值不显示为零。
|
||||
var deviceStatusText: String {
|
||||
let value = store.devices.first?.telemetry.batteryText ?? "—"
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import UIKit
|
||||
|
||||
/// 订单列表与素材库共用的真实成片交付页面工厂。
|
||||
@MainActor
|
||||
enum DroneDockDeliveryEntry {
|
||||
/// 同时传递订单与可选任务,进入页面后重新校验当前身份和上传权限。
|
||||
static func makeController(order: DroneDockHomeOrder, context: DroneDockHomeContext, taskID: Int?) -> UIViewController {
|
||||
let client = NetworkServices.shared.apiClient
|
||||
return DroneDockDeliveryViewController(viewModel: DroneDockDeliveryViewModel(
|
||||
context: context, order: order,
|
||||
service: DroneDockDeliveryAPI(client: client),
|
||||
uploader: DroneDockFilmUploader(configService: UploadAPI(client: client)),
|
||||
initialTaskID: taskID,
|
||||
currentContext: { DroneDockHomeViewController.currentContext() }
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import AVFoundation
|
||||
import Foundation
|
||||
import PhotosUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// 将用户选择的视频复制到本页独占的临时目录,避免相册临时文件提前失效。
|
||||
enum DroneDockDeliveryVideoLoader {
|
||||
/// 相册回调返回前完成文件复制,随后验证本地视频轨道。
|
||||
@MainActor
|
||||
static func load(provider: NSItemProvider) async throws -> DroneDockDeliveryVideo {
|
||||
let suggestedName = provider.suggestedName
|
||||
let copiedURL: URL = try await withCheckedThrowingContinuation { continuation in
|
||||
provider.loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier) { source, error in
|
||||
if let error { continuation.resume(throwing: error); return }
|
||||
guard let source else { continuation.resume(throwing: VideoError.unavailable); return }
|
||||
do { continuation.resume(returning: try copy(source: source, suggestedName: suggestedName)) }
|
||||
catch { continuation.resume(throwing: error) }
|
||||
}
|
||||
}
|
||||
return try await validate(copiedURL)
|
||||
}
|
||||
|
||||
/// 文件选择器的安全作用域仅用于复制,上传不持有外部文件访问权限。
|
||||
@MainActor
|
||||
static func load(documentURL: URL) async throws -> DroneDockDeliveryVideo {
|
||||
let accessing = documentURL.startAccessingSecurityScopedResource()
|
||||
defer { if accessing { documentURL.stopAccessingSecurityScopedResource() } }
|
||||
let copiedURL = try await Task.detached(priority: .userInitiated) {
|
||||
try copy(source: documentURL, suggestedName: documentURL.lastPathComponent)
|
||||
}.value
|
||||
return try await validate(copiedURL)
|
||||
}
|
||||
|
||||
/// 只清理本功能创建的独占目录,外部文件和测试文件不受影响。
|
||||
static func discard(_ url: URL) {
|
||||
let directory = url.deletingLastPathComponent().standardizedFileURL
|
||||
guard directory.deletingLastPathComponent() == root.standardizedFileURL else { return }
|
||||
try? FileManager.default.removeItem(at: directory)
|
||||
}
|
||||
|
||||
private static var root: URL { FileManager.default.temporaryDirectory.appendingPathComponent("drone-dock-delivery", isDirectory: true) }
|
||||
|
||||
private static func copy(source: URL, suggestedName: String?) throws -> URL {
|
||||
guard source.isFileURL else { throw VideoError.unavailable }
|
||||
let sourceExtension = source.pathExtension.lowercased()
|
||||
let candidate = (suggestedName ?? source.lastPathComponent).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
var name = URL(fileURLWithPath: candidate.isEmpty ? "成片视频" : candidate).lastPathComponent
|
||||
if URL(fileURLWithPath: name).pathExtension.isEmpty, !sourceExtension.isEmpty { name += "." + sourceExtension }
|
||||
guard name.count <= 255 else { throw VideoError.longName }
|
||||
guard ["mp4", "mov", "avi", "mkv", "flv", "wmv", "webm"].contains(URL(fileURLWithPath: name).pathExtension.lowercased()) else {
|
||||
throw VideoError.unsupported
|
||||
}
|
||||
let values = try source.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey])
|
||||
guard values.isRegularFile == true, let size = values.fileSize, size > 0 else { throw VideoError.unavailable }
|
||||
guard size <= 2_048 * 1_024 * 1_024 else { throw VideoError.tooLarge }
|
||||
let directory = root.appendingPathComponent(UUID().uuidString, isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let destination = directory.appendingPathComponent(name)
|
||||
do { try FileManager.default.copyItem(at: source, to: destination); return destination }
|
||||
catch { try? FileManager.default.removeItem(at: directory); throw error }
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private static func validate(_ url: URL) async throws -> DroneDockDeliveryVideo {
|
||||
do {
|
||||
try Task.checkCancellation()
|
||||
let asset = AVURLAsset(url: url)
|
||||
let tracks = try await asset.loadTracks(withMediaType: .video)
|
||||
guard !tracks.isEmpty else { throw VideoError.unsupported }
|
||||
let values = try url.resourceValues(forKeys: [.fileSizeKey])
|
||||
guard let size = values.fileSize, size > 0 else { throw VideoError.unavailable }
|
||||
try Task.checkCancellation()
|
||||
return DroneDockDeliveryVideo(url: url, fileName: url.lastPathComponent, fileSize: size)
|
||||
} catch {
|
||||
discard(url)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/// 文件准备失败时保留可操作的提示,不把无效文件交给上传队列。
|
||||
private enum VideoError: LocalizedError {
|
||||
case unavailable, unsupported, tooLarge, longName
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .unavailable: "无法读取视频文件,请重新选择"
|
||||
case .unsupported: "请选择 MP4、MOV 等受支持的视频;M4V 请先导出为 MP4"
|
||||
case .tooLarge: "视频不能超过 2 GB,请压缩后重试"
|
||||
case .longName: "视频文件名过长,请缩短后重新选择"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
import AVKit
|
||||
import PhotosUI
|
||||
import SnapKit
|
||||
import UIKit
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// 订单列表与任务素材入口共用的云端成片交付页,一个任务保存一个视频。
|
||||
@MainActor
|
||||
final class DroneDockDeliveryViewController: BaseViewController {
|
||||
/// 当前订单、任务选择及上传保存状态。
|
||||
let viewModel: DroneDockDeliveryViewModel
|
||||
private let onDidSave: (() -> Void)?
|
||||
private let videoPicker: (@MainActor () async throws -> DroneDockDeliveryVideo?)?
|
||||
private var operationTask: Task<Void, Never>?
|
||||
private var hasAppeared = false
|
||||
private var isRefreshing = false
|
||||
private var isPicking = false
|
||||
private var isStartingSubmission = false
|
||||
private var pickerError: String?
|
||||
private var ownedVideoURLs: Set<URL> = []
|
||||
private var previousGestureEnabled: Bool?
|
||||
private weak var trackedNavigationController: UINavigationController?
|
||||
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
|
||||
private let footer = UIView()
|
||||
private let stateLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let progressView = UIProgressView(progressViewStyle: .default)
|
||||
private let submitButton = UIButton(type: .system)
|
||||
|
||||
/// 点位横向排列,其余信息按步骤向下展示。
|
||||
private enum Section: Hashable { case order, points, tasks, video, state }
|
||||
/// 身份稳定的 Diffable 项目,上传进度不改变选择。
|
||||
private enum Item: Hashable { case order, point(Int), task(Int), choosePoint, emptyTasks, video, state }
|
||||
|
||||
/// 注入上传状态、真实保存回调和可测试的视频选择入口。
|
||||
init(viewModel: DroneDockDeliveryViewModel, onDidSave: (() -> Void)? = nil,
|
||||
videoPicker: (@MainActor () async throws -> DroneDockDeliveryVideo?)? = nil) {
|
||||
self.viewModel = viewModel
|
||||
self.onDidSave = onDidSave
|
||||
self.videoPicker = videoPicker
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
deinit {
|
||||
operationTask?.cancel()
|
||||
ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard)
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "交付成片"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
let back = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(backTapped))
|
||||
back.accessibilityIdentifier = "drone.delivery.back"
|
||||
navigationItem.leftBarButtonItem = back
|
||||
let refresh = UIBarButtonItem(title: "刷新", style: .plain, target: self, action: #selector(refreshTapped))
|
||||
refresh.accessibilityIdentifier = "drone.delivery.refresh"
|
||||
navigationItem.rightBarButtonItem = refresh
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = DroneDockStyle.background
|
||||
collectionView.backgroundColor = .clear
|
||||
collectionView.alwaysBounceVertical = true
|
||||
collectionView.accessibilityIdentifier = "drone.delivery.remote.list"
|
||||
collectionView.delegate = self
|
||||
collectionView.register(DroneMaterialFilterCell.self, forCellWithReuseIdentifier: "point")
|
||||
collectionView.register(DroneDockDeliveryTextCell.self, forCellWithReuseIdentifier: "text")
|
||||
collectionView.register(DroneDockDeliveryVideoCell.self, forCellWithReuseIdentifier: "video")
|
||||
let refresh = UIRefreshControl()
|
||||
refresh.addTarget(self, action: #selector(refreshTapped), for: .valueChanged)
|
||||
collectionView.refreshControl = refresh
|
||||
footer.backgroundColor = .white
|
||||
stateLabel.numberOfLines = 0
|
||||
stateLabel.accessibilityIdentifier = "drone.delivery.progressText"
|
||||
progressView.progressTintColor = DroneDockStyle.primary
|
||||
progressView.accessibilityIdentifier = "drone.delivery.progress"
|
||||
submitButton.setTitleColor(.white, for: .normal)
|
||||
submitButton.setTitleColor(DroneDockStyle.text, for: .disabled)
|
||||
submitButton.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
|
||||
submitButton.layer.cornerRadius = 12
|
||||
submitButton.accessibilityIdentifier = "drone.delivery.submit"
|
||||
submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
|
||||
view.addSubview(collectionView)
|
||||
view.addSubview(footer)
|
||||
[stateLabel, progressView, submitButton].forEach(footer.addSubview)
|
||||
configureDataSource()
|
||||
applySnapshot(animated: false)
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
collectionView.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide)
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.bottom.equalTo(footer.snp.top)
|
||||
}
|
||||
footer.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview() }
|
||||
stateLabel.snp.makeConstraints { make in make.top.equalToSuperview().offset(12); make.leading.trailing.equalToSuperview().inset(20) }
|
||||
progressView.snp.makeConstraints { make in make.top.equalTo(stateLabel.snp.bottom).offset(8); make.leading.trailing.equalTo(stateLabel); make.height.equalTo(3) }
|
||||
submitButton.snp.makeConstraints { make in
|
||||
make.top.equalTo(progressView.snp.bottom).offset(12)
|
||||
make.leading.trailing.equalToSuperview().inset(16)
|
||||
make.height.equalTo(48)
|
||||
make.bottom.equalTo(footer.safeAreaLayoutGuide).offset(-12)
|
||||
}
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
trackedNavigationController = navigationController
|
||||
if previousGestureEnabled == nil { previousGestureEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled }
|
||||
guard !hasAppeared else { updateFooter(); return }
|
||||
hasAppeared = true
|
||||
refresh()
|
||||
}
|
||||
|
||||
/// 预览和系统选择器覆盖不清空上传页,只有确认离开后才取消并清理。
|
||||
override func viewDidDisappear(_ animated: Bool) {
|
||||
super.viewDidDisappear(animated)
|
||||
trackedNavigationController?.interactivePopGestureRecognizer?.isEnabled = previousGestureEnabled ?? true
|
||||
guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true || parent == nil else { return }
|
||||
operationTask?.cancel()
|
||||
viewModel.invalidate()
|
||||
ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard)
|
||||
ownedVideoURLs.removeAll()
|
||||
hasAppeared = false
|
||||
}
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { [weak self] list, path, item in
|
||||
guard let self else { return nil }
|
||||
if case .point(let id) = item {
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "point", for: path) as! DroneMaterialFilterCell
|
||||
let title = self.viewModel.spots.first { $0.id == id }.map { Self.text($0.name, fallback: "点位 \(id)") } ?? "点位 \(id)"
|
||||
cell.apply(title: title, id: String(id), selected: self.viewModel.selectedSpotID == id, locked: self.locked)
|
||||
cell.accessibilityIdentifier = "drone.delivery.point.\(id)"
|
||||
return cell
|
||||
}
|
||||
if item == .video {
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "video", for: path) as! DroneDockDeliveryVideoCell
|
||||
cell.apply(video: self.viewModel.video, enabled: self.viewModel.canChooseVideo && !self.locked, isPicking: self.isPicking,
|
||||
choose: { [weak self] in self?.chooseVideo(fromFiles: false) },
|
||||
files: { [weak self] in self?.chooseVideo(fromFiles: true) },
|
||||
preview: { [weak self] in self?.previewVideo() },
|
||||
remove: { [weak self] in self?.removeVideo() })
|
||||
return cell
|
||||
}
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! DroneDockDeliveryTextCell
|
||||
self.configureText(cell, item: item)
|
||||
return cell
|
||||
}
|
||||
}
|
||||
|
||||
private func configureText(_ cell: DroneDockDeliveryTextCell, item: Item) {
|
||||
switch item {
|
||||
case .order:
|
||||
guard let order = viewModel.detail?.order else { return }
|
||||
cell.apply(title: order.touristTitle, body: "\(order.orderNumberText)\n\(order.packageTitle) · \(order.progressTitle)", id: "drone.delivery.order")
|
||||
case .choosePoint:
|
||||
cell.apply(title: "选择点位与拍摄任务", body: "每个拍摄任务可交付一个视频成片", id: "drone.delivery.chooseTask")
|
||||
case .task(let id):
|
||||
guard let task = viewModel.tasks.first(where: { $0.id == id }) else { return }
|
||||
let number = task.sequence.map(String.init) ?? String(task.id)
|
||||
let film = task.film.map { "已有成片:\(Self.text($0.fileName, fallback: "视频成片"))\n重新上传将替换此任务的原成片" } ?? "尚未交付成片"
|
||||
cell.apply(title: "任务 \(number) · \(Self.text(task.spotName, fallback: "点位 \(task.spotID)"))",
|
||||
body: "\(Self.text(task.airLineName, fallback: "航线待确认")) · \(Self.flightTitle(task.flightStatus))\n\(Self.text(task.createdAt, fallback: "时间待确认"))\n\(film)",
|
||||
id: "drone.delivery.task.\(id)", selected: viewModel.selectedTaskID == id, selectable: true)
|
||||
case .emptyTasks:
|
||||
let noTasks = viewModel.tasks.isEmpty
|
||||
cell.apply(title: noTasks ? "暂无可交付的拍摄任务" : "此点位暂无拍摄任务", body: "请在拍摄任务创建后刷新,再选择对应任务上传成片", id: "drone.delivery.empty")
|
||||
case .state:
|
||||
if isRefreshing || viewModel.isLoading { cell.apply(title: "正在读取订单与任务", body: nil, id: "drone.delivery.loading") }
|
||||
else if let error = viewModel.loadErrorMessage {
|
||||
cell.apply(title: "订单信息加载失败", body: error, id: "drone.delivery.error", button: "重试", actionID: "drone.delivery.retry") { [weak self] in self?.refresh() }
|
||||
} else if let error = pickerError ?? viewModel.submissionErrorMessage {
|
||||
cell.apply(title: "交付尚未完成", body: error, id: "drone.delivery.error")
|
||||
} else if let success = viewModel.successMessage {
|
||||
cell.apply(title: success, body: viewModel.refreshWarning ?? "成片已保存,可返回素材库查看", id: "drone.delivery.success")
|
||||
} else if viewModel.detail?.order.canUploadFilm != true {
|
||||
cell.apply(title: "当前订单暂不可上传成片", body: viewModel.detail?.order.orderStatus == 30 ? "订单已完成,无法继续上传或替换成片" : "请确认订单已付款且已有有效拍摄任务,刷新后重试", id: "drone.delivery.unavailable")
|
||||
} else { cell.apply(title: "云端上传", body: "选择视频后点击上传,保存成功后游客可在小程序相册查看", id: "drone.delivery.hint") }
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
private var locked: Bool { isRefreshing || isPicking || isStartingSubmission || viewModel.isLoading || viewModel.isSubmitting }
|
||||
|
||||
private func makeLayout() -> UICollectionViewLayout {
|
||||
UICollectionViewCompositionalLayout { [weak self] index, _ in
|
||||
guard let self, let source = self.dataSource else { return nil }
|
||||
let sections = source.snapshot().sectionIdentifiers
|
||||
guard sections.indices.contains(index) else { return nil }
|
||||
let points = sections[index] == .points
|
||||
let size = NSCollectionLayoutSize(widthDimension: points ? .estimated(112) : .fractionalWidth(1), heightDimension: points ? .absolute(40) : .estimated(100))
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: points ? .fractionalHeight(1) : .estimated(100)))
|
||||
let group = NSCollectionLayoutGroup.vertical(layoutSize: size, subitems: [item])
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.contentInsets = .init(top: 0, leading: 16, bottom: 12, trailing: 16)
|
||||
section.interGroupSpacing = 10
|
||||
if points { section.orthogonalScrollingBehavior = .continuous }
|
||||
return section
|
||||
}
|
||||
}
|
||||
|
||||
private func applySnapshot(animated: Bool) {
|
||||
guard dataSource != nil else { return }
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
|
||||
if viewModel.detail != nil && !isRefreshing {
|
||||
snapshot.appendSections([.order, .points, .tasks])
|
||||
snapshot.appendItems([.order, .choosePoint], toSection: .order)
|
||||
snapshot.appendItems(viewModel.spots.map { .point($0.id) }, toSection: .points)
|
||||
if viewModel.selectedSpotID != nil {
|
||||
snapshot.appendItems(viewModel.filteredTasks.isEmpty ? [.emptyTasks] : viewModel.filteredTasks.map { .task($0.id) }, toSection: .tasks)
|
||||
} else if viewModel.tasks.isEmpty { snapshot.appendItems([.emptyTasks], toSection: .tasks) }
|
||||
if viewModel.selectedTask != nil {
|
||||
snapshot.appendSections([.video])
|
||||
snapshot.appendItems([.video], toSection: .video)
|
||||
}
|
||||
}
|
||||
snapshot.appendSections([.state])
|
||||
snapshot.appendItems([.state], toSection: .state)
|
||||
let previous = Set(dataSource.snapshot().itemIdentifiers)
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { previous.contains($0) })
|
||||
dataSource.apply(snapshot, animatingDifferences: animated)
|
||||
updateFooter()
|
||||
}
|
||||
|
||||
private func updateFooter() {
|
||||
guard isViewLoaded else { return }
|
||||
let working = viewModel.isSubmitting
|
||||
let status: String
|
||||
switch viewModel.phase {
|
||||
case .validating: status = "正在核对订单与任务…"
|
||||
case .uploading: status = "正在上传视频 \(viewModel.progress)%"
|
||||
case .saving: status = "视频上传完成,正在保存成片…"
|
||||
case .succeeded: status = "成片交付成功"
|
||||
case .idle: status = isPicking ? "正在准备视频文件…" : viewModel.uploadedFileURL != nil ? "视频已上传,可重试保存成片" : "一个拍摄任务对应一个视频成片"
|
||||
}
|
||||
stateLabel.text = status
|
||||
progressView.isHidden = !working
|
||||
progressView.progress = Float(viewModel.progress) / 100
|
||||
let title = viewModel.successMessage != nil ? "交付成功" : viewModel.uploadedFileURL != nil ? "重试保存成片" : viewModel.needsReplacementConfirmation ? "上传并替换成片" : "上传成片"
|
||||
submitButton.setTitle(working ? "处理中…" : title, for: .normal)
|
||||
submitButton.isEnabled = viewModel.canSubmit && !locked
|
||||
submitButton.backgroundColor = submitButton.isEnabled ? DroneDockStyle.primary : DroneDockStyle.secondary.withAlphaComponent(0.45)
|
||||
navigationItem.rightBarButtonItem?.isEnabled = !working && !isPicking && !isRefreshing
|
||||
navigationController?.interactivePopGestureRecognizer?.isEnabled = !working && !isStartingSubmission && !isPicking && (previousGestureEnabled ?? true)
|
||||
}
|
||||
|
||||
private func refresh() {
|
||||
guard !viewModel.isSubmitting, !isStartingSubmission, !isPicking else { collectionView.refreshControl?.endRefreshing(); return }
|
||||
operationTask?.cancel()
|
||||
isRefreshing = true
|
||||
pickerError = nil
|
||||
applySnapshot(animated: false)
|
||||
operationTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.refresh()
|
||||
guard !Task.isCancelled else { return }
|
||||
self.isRefreshing = false
|
||||
self.discardUnusedVideos()
|
||||
self.collectionView.refreshControl?.endRefreshing()
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func refreshTapped() { refresh() }
|
||||
|
||||
@objc private func submitTapped() {
|
||||
guard viewModel.canSubmit, !locked else { return }
|
||||
if viewModel.needsReplacementConfirmation {
|
||||
let alert = UIAlertController(title: "替换此任务的成片?", message: "保存成功后,游客将看到新视频。保存失败会保留原成片。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
|
||||
let replace = UIAlertAction(title: "替换成片", style: .destructive) { [weak self] _ in self?.submit(confirmed: true) }
|
||||
alert.addAction(replace)
|
||||
present(alert, animated: true)
|
||||
} else { submit(confirmed: false) }
|
||||
}
|
||||
|
||||
private func submit(confirmed: Bool) {
|
||||
guard viewModel.canSubmit, !locked else { return }
|
||||
pickerError = nil
|
||||
isStartingSubmission = true
|
||||
updateFooter()
|
||||
operationTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.submit(confirmReplacement: confirmed) { [weak self] _ in self?.applySnapshot(animated: false) }
|
||||
guard !Task.isCancelled else { return }
|
||||
self.isStartingSubmission = false
|
||||
self.discardUnusedVideos()
|
||||
self.applySnapshot(animated: true)
|
||||
if self.viewModel.successMessage != nil { self.onDidSave?() }
|
||||
}
|
||||
}
|
||||
|
||||
private func chooseVideo(fromFiles: Bool) {
|
||||
guard viewModel.canChooseVideo, !locked else { return }
|
||||
pickerError = nil
|
||||
if let videoPicker {
|
||||
loadPickedVideo { try await videoPicker() }
|
||||
} else if fromFiles {
|
||||
let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.movie], asCopy: true)
|
||||
picker.allowsMultipleSelection = false
|
||||
picker.delegate = self
|
||||
present(picker, animated: true)
|
||||
} else {
|
||||
var configuration = PHPickerConfiguration(photoLibrary: .shared())
|
||||
configuration.filter = .videos
|
||||
configuration.selectionLimit = 1
|
||||
configuration.preferredAssetRepresentationMode = .current
|
||||
let picker = PHPickerViewController(configuration: configuration)
|
||||
picker.delegate = self
|
||||
present(picker, animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func loadPickedVideo(_ loader: @escaping @MainActor () async throws -> DroneDockDeliveryVideo?) {
|
||||
isPicking = true
|
||||
applySnapshot(animated: false)
|
||||
operationTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
defer {
|
||||
if !Task.isCancelled {
|
||||
self.isPicking = false
|
||||
self.applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
do {
|
||||
if let selected = try await loader() {
|
||||
guard !Task.isCancelled, self.viewModel.canChooseVideo else { DroneDockDeliveryVideoLoader.discard(selected.url); return }
|
||||
do { _ = try DroneDockFilmPolicy.validate(video: selected) }
|
||||
catch { DroneDockDeliveryVideoLoader.discard(selected.url); throw error }
|
||||
self.viewModel.selectVideo(selected)
|
||||
if self.viewModel.video?.id == selected.id {
|
||||
self.ownedVideoURLs.insert(selected.url)
|
||||
self.discardUnusedVideos()
|
||||
} else { DroneDockDeliveryVideoLoader.discard(selected.url) }
|
||||
}
|
||||
} catch {
|
||||
if !Task.isCancelled { self.pickerError = error.localizedDescription }
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
}
|
||||
}
|
||||
|
||||
private func discardUnusedVideos() {
|
||||
let unused = ownedVideoURLs.filter { $0 != viewModel.video?.url }
|
||||
unused.forEach(DroneDockDeliveryVideoLoader.discard)
|
||||
ownedVideoURLs.subtract(unused)
|
||||
}
|
||||
|
||||
private func removeVideo() {
|
||||
guard !locked else { return }
|
||||
if let video = viewModel.video { DroneDockDeliveryVideoLoader.discard(video.url); ownedVideoURLs.remove(video.url) }
|
||||
viewModel.removeVideo()
|
||||
pickerError = nil
|
||||
applySnapshot(animated: true)
|
||||
}
|
||||
|
||||
private func previewVideo() {
|
||||
guard !locked, let video = viewModel.video else { return }
|
||||
let player = AVPlayerViewController()
|
||||
player.player = AVPlayer(url: video.url)
|
||||
present(player, animated: true) { player.player?.play() }
|
||||
}
|
||||
|
||||
@objc private func backTapped() {
|
||||
guard viewModel.isSubmitting || isStartingSubmission || isPicking else { navigationController?.popViewController(animated: true); return }
|
||||
let alert = UIAlertController(title: "停止处理并返回?", message: "未完成的上传将停止。如果正在保存成片,返回素材库刷新可核对实际结果。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续处理", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "停止并返回", style: .destructive) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.operationTask?.cancel()
|
||||
self.viewModel.invalidate()
|
||||
self.navigationController?.popViewController(animated: true)
|
||||
})
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
private static func text(_ value: String?, fallback: String) -> String { DroneDockHomeMetric.usableText(value) ?? fallback }
|
||||
private static func flightTitle(_ value: Int?) -> String {
|
||||
switch value { case 10: "待飞行"; case 20: "执行中"; case 30: "飞行成功"; case 40: "飞行失败"; case 50: "已取消"; case 60: "待确认"; default: "状态待确认" }
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockDeliveryViewController: UICollectionViewDelegate {
|
||||
/// 仅显式选择的点位与任务用于上传;切换任务不自动提交文件。
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard !locked, let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||
switch item {
|
||||
case .point(let id): viewModel.selectSpot(id: id)
|
||||
case .task(let id): viewModel.selectTask(id: id)
|
||||
default: return
|
||||
}
|
||||
discardUnusedVideos()
|
||||
pickerError = nil
|
||||
applySnapshot(animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockDeliveryViewController: PHPickerViewControllerDelegate {
|
||||
/// 相册取消不改变已选视频;选择结果复制完成后才交给上传状态。
|
||||
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
|
||||
picker.dismiss(animated: true)
|
||||
guard let result = results.first else { return }
|
||||
loadPickedVideo { try await DroneDockDeliveryVideoLoader.load(provider: result.itemProvider) }
|
||||
}
|
||||
}
|
||||
|
||||
extension DroneDockDeliveryViewController: UIDocumentPickerDelegate {
|
||||
/// 文件选择器只接受一段视频,复制到本页临时目录后读取。
|
||||
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
|
||||
guard let url = urls.first else { return }
|
||||
loadPickedVideo { try await DroneDockDeliveryVideoLoader.load(documentURL: url) }
|
||||
}
|
||||
}
|
||||
|
||||
/// 订单、任务与错误提示共用的自适应卡片。
|
||||
@MainActor
|
||||
private final class DroneDockDeliveryTextCell: UICollectionViewCell {
|
||||
private let titleLabel = DroneDockStyle.label(size: 15, weight: .semibold)
|
||||
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let actionButton = UIButton(type: .system)
|
||||
private var action: (() -> Void)?
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
DroneDockStyle.applyCard(to: contentView)
|
||||
titleLabel.numberOfLines = 0
|
||||
detailLabel.numberOfLines = 0
|
||||
let stack = UIStackView(arrangedSubviews: [titleLabel, detailLabel, actionButton])
|
||||
stack.axis = .vertical; stack.spacing = 8; stack.alignment = .leading
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(14) }
|
||||
titleLabel.snp.makeConstraints { $0.width.equalTo(stack) }
|
||||
detailLabel.snp.makeConstraints { $0.width.equalTo(stack) }
|
||||
actionButton.addTarget(self, action: #selector(tapped), for: .touchUpInside)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 重配内容时同步清除旧操作与选中状态。
|
||||
func apply(title: String, body: String?, id: String, selected: Bool = false, selectable: Bool = false,
|
||||
button: String? = nil, actionID: String? = nil, action: (() -> Void)? = nil) {
|
||||
titleLabel.text = (selectable ? (selected ? "● " : "○ ") : "") + title
|
||||
detailLabel.text = body
|
||||
detailLabel.isHidden = body == nil
|
||||
actionButton.setTitle(button, for: .normal)
|
||||
actionButton.isHidden = button == nil
|
||||
actionButton.accessibilityIdentifier = actionID
|
||||
self.action = action
|
||||
contentView.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor
|
||||
contentView.layer.borderWidth = selected ? 1 : 0
|
||||
accessibilityIdentifier = id
|
||||
accessibilityTraits = selected ? [.button, .selected] : selectable ? .button : []
|
||||
}
|
||||
@objc private func tapped() { action?() }
|
||||
}
|
||||
|
||||
/// 单视频选择、预览与移除卡片,所有动作由页面显式分派。
|
||||
@MainActor
|
||||
private final class DroneDockDeliveryVideoCell: UICollectionViewCell {
|
||||
private let titleLabel = DroneDockStyle.label("选择成片视频", size: 15, weight: .semibold)
|
||||
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
|
||||
private let chooseButton = UIButton(type: .system)
|
||||
private let filesButton = UIButton(type: .system)
|
||||
private let previewButton = UIButton(type: .system)
|
||||
private let removeButton = UIButton(type: .system)
|
||||
private var choose: (() -> Void)?
|
||||
private var files: (() -> Void)?
|
||||
private var preview: (() -> Void)?
|
||||
private var remove: (() -> Void)?
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
DroneDockStyle.applyCard(to: contentView)
|
||||
detailLabel.numberOfLines = 0
|
||||
let buttons = UIStackView(arrangedSubviews: [chooseButton, filesButton, previewButton, removeButton])
|
||||
buttons.axis = .horizontal; buttons.spacing = 14; buttons.alignment = .leading
|
||||
let stack = UIStackView(arrangedSubviews: [titleLabel, detailLabel, buttons])
|
||||
stack.axis = .vertical; stack.spacing = 10
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(14) }
|
||||
chooseButton.setTitle("从相册选择", for: .normal)
|
||||
filesButton.setTitle("从文件选择", for: .normal)
|
||||
previewButton.setTitle("预览", for: .normal)
|
||||
removeButton.setTitle("移除", for: .normal)
|
||||
for button in [chooseButton, filesButton, previewButton, removeButton] { button.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium) }
|
||||
chooseButton.accessibilityIdentifier = "drone.delivery.chooseVideo"
|
||||
filesButton.accessibilityIdentifier = "drone.delivery.chooseFile"
|
||||
previewButton.accessibilityIdentifier = "drone.delivery.preview"
|
||||
removeButton.accessibilityIdentifier = "drone.delivery.removeVideo"
|
||||
chooseButton.addTarget(self, action: #selector(chooseTapped), for: .touchUpInside)
|
||||
filesButton.addTarget(self, action: #selector(filesTapped), for: .touchUpInside)
|
||||
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
|
||||
removeButton.addTarget(self, action: #selector(removeTapped), for: .touchUpInside)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 显示本地文件信息,不将选择或 OSS 完成当作已经交付。
|
||||
func apply(video: DroneDockDeliveryVideo?, enabled: Bool, isPicking: Bool, choose: @escaping () -> Void,
|
||||
files: @escaping () -> Void, preview: @escaping () -> Void, remove: @escaping () -> Void) {
|
||||
self.choose = choose; self.files = files; self.preview = preview; self.remove = remove
|
||||
detailLabel.text = isPicking ? "正在读取视频…" : video.map { "\($0.fileName)\n\(ByteCountFormatter.string(fromByteCount: Int64($0.fileSize), countStyle: .file))" } ?? "请选择一个视频,支持 MP4、MOV 等格式,最大 2 GB"
|
||||
previewButton.isHidden = video == nil
|
||||
removeButton.isHidden = video == nil
|
||||
[chooseButton, filesButton, previewButton, removeButton].forEach { $0.isEnabled = enabled }
|
||||
}
|
||||
@objc private func chooseTapped() { choose?() }
|
||||
@objc private func filesTapped() { files?() }
|
||||
@objc private func previewTapped() { preview?() }
|
||||
@objc private func removeTapped() { remove?() }
|
||||
}
|
||||
@@ -393,7 +393,7 @@ final class DroneDockHomeViewController: BaseViewController {
|
||||
#endif
|
||||
|
||||
/// 只从现有会话读取身份,不修改登录状态或当前选择。
|
||||
private static func currentContext() -> DroneDockHomeContext {
|
||||
static func currentContext() -> DroneDockHomeContext {
|
||||
let session = AppStore.shared.session
|
||||
return DroneDockHomeContext(userID: session.userId, accountType: session.accountType.rawValue,
|
||||
scenicID: session.currentScenicId, scenicName: session.currentScenicName,
|
||||
|
||||
@@ -8,6 +8,7 @@ import UIKit
|
||||
final class DroneDockMaterialsViewController: BaseViewController {
|
||||
/// 保存当前订单摘要、点位和任务的真实状态。
|
||||
let viewModel: DroneDockMaterialsViewModel
|
||||
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
|
||||
|
||||
/// 元数据与媒体分区独立,任务没有素材时也保留其状态。
|
||||
private enum Section: Hashable { case order, filters, summary, task(Int), media(Int), message }
|
||||
@@ -23,10 +24,13 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
private var loadTask: Task<Void, Never>?
|
||||
private var operation: LoadAction?
|
||||
private var hasAppeared = false
|
||||
private var refreshAfterDelivery = false
|
||||
|
||||
/// 注入冻结订单范围的只读素材服务。
|
||||
init(viewModel: DroneDockMaterialsViewModel) {
|
||||
init(viewModel: DroneDockMaterialsViewModel,
|
||||
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil) {
|
||||
self.viewModel = viewModel
|
||||
self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
@@ -71,8 +75,9 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
guard !hasAppeared else { return }
|
||||
guard !hasAppeared || refreshAfterDelivery else { return }
|
||||
hasAppeared = true
|
||||
refreshAfterDelivery = false
|
||||
load(.refresh)
|
||||
}
|
||||
|
||||
@@ -135,7 +140,10 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
Self.usable(task.createdAt, fallback: "时间待确认")]
|
||||
if task.materials.isEmpty { lines.append("暂无原素材") }
|
||||
if task.film == nil { lines.append("暂无视频成片") }
|
||||
cell.apply(title: title, body: lines.joined(separator: "\n"), identifier: "drone.materials.remote.task.\(id)")
|
||||
let canDeliver = operation == nil && viewModel.detail?.order.canUploadFilm == true
|
||||
cell.apply(title: title, body: lines.joined(separator: "\n"), identifier: "drone.materials.remote.task.\(id)",
|
||||
button: canDeliver ? (task.film == nil ? "交付成片" : "替换成片") : nil,
|
||||
actionID: "drone.materials.remote.delivery.\(id)") { [weak self] in self?.openDelivery(taskID: id) }
|
||||
case .message:
|
||||
if operation != nil || viewModel.isLoading || viewModel.isLoadingTasks {
|
||||
cell.apply(title: viewModel.detail == nil ? "正在加载订单素材库" : "正在加载任务素材", body: nil, identifier: "drone.materials.remote.loading")
|
||||
@@ -235,6 +243,13 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
@objc private func refreshTapped() { load(.refresh) }
|
||||
private func task(_ id: Int) -> DroneDockMaterialTask? { viewModel.tasks.first { $0.id == id } }
|
||||
|
||||
private func openDelivery(taskID: Int) {
|
||||
guard operation == nil, let order = viewModel.detail?.order, order.canUploadFilm == true,
|
||||
task(taskID) != nil, let navigationController else { return }
|
||||
refreshAfterDelivery = true
|
||||
navigationController.pushViewController(deliveryControllerFactory(order, viewModel.context, taskID), animated: true)
|
||||
}
|
||||
|
||||
private func preview(url: URL, isVideo: Bool, title: String) {
|
||||
if isVideo {
|
||||
let player = AVPlayerViewController()
|
||||
|
||||
@@ -8,6 +8,7 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
let viewModel: DroneDockOrdersViewModel
|
||||
private let preparationControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private let materialsControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController
|
||||
private let deliveryControllerFactory: (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController
|
||||
private let countLabel = DroneDockStyle.label(size: 17, weight: .semibold)
|
||||
private let descriptionLabel = DroneDockStyle.label("分配给我的全部订单,含已完成订单", size: 12, color: DroneDockStyle.secondary)
|
||||
private let filterView = DroneShootingOrderFilterView()
|
||||
@@ -21,13 +22,15 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
/// 刷新替换整页,翻页保留已加载订单。
|
||||
private enum LoadAction: Equatable { case refresh, more, filter(DroneShootingOrderFilter) }
|
||||
|
||||
/// 注入真实订单服务及与首页一致的拍摄准备、素材库入口。
|
||||
/// 注入真实订单服务、拍摄准备、素材库与共用云端交付入口。
|
||||
init(viewModel: DroneDockOrdersViewModel,
|
||||
preparationControllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController,
|
||||
materialsControllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController) {
|
||||
materialsControllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext) -> UIViewController,
|
||||
deliveryControllerFactory: ((DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController)? = nil) {
|
||||
self.viewModel = viewModel
|
||||
self.preparationControllerFactory = preparationControllerFactory
|
||||
self.materialsControllerFactory = materialsControllerFactory
|
||||
self.deliveryControllerFactory = deliveryControllerFactory ?? DroneDockDeliveryEntry.makeController
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
hidesBottomBarWhenPushed = true
|
||||
}
|
||||
@@ -110,7 +113,7 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
cell.cardView.apply(homeOrder: order)
|
||||
cell.cardView.onShootingTap = { [weak self] in self?.openPreparation(orderID: id) }
|
||||
cell.cardView.onMaterialsTap = { [weak self] in self?.openMaterials(orderID: id) }
|
||||
cell.cardView.onDeliveryTap = { [weak self] in self?.showUnavailable("交付成片") }
|
||||
cell.cardView.onDeliveryTap = { [weak self] in self?.openDelivery(orderID: id) }
|
||||
cell.cardView.onConfirmationTap = { [weak self] in self?.showUnavailable("交付确认") }
|
||||
}
|
||||
return cell
|
||||
@@ -201,6 +204,12 @@ final class DroneDockOrdersViewController: BaseViewController {
|
||||
|
||||
private func showUnavailable(_ feature: String) { showAlert(title: feature, message: "该功能暂未开放") }
|
||||
|
||||
private func openDelivery(orderID: String) {
|
||||
guard operation == nil, let order = viewModel.orders.first(where: { $0.orderID == orderID }),
|
||||
order.canUploadFilm == true else { return }
|
||||
navigationController?.pushViewController(deliveryControllerFactory(order, viewModel.context, nil), animated: true)
|
||||
}
|
||||
|
||||
private func openMaterials(orderID: String) {
|
||||
guard operation == nil, let order = viewModel.orders.first(where: { $0.orderID == orderID }) else { return }
|
||||
guard DroneDockHomeMetric.usableText(order.orderNumber) != nil else {
|
||||
|
||||
@@ -6,6 +6,17 @@ import UIKit
|
||||
enum DroneDockPreview {
|
||||
/// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。
|
||||
static func navigationController(arguments: [String]) -> UINavigationController? {
|
||||
if let argument = arguments.first(where: { $0.hasPrefix("--dock-delivery-live=") }), AppStore.shared.session.isLoggedIn {
|
||||
let number = String(argument.dropFirst("--dock-delivery-live=".count))
|
||||
if let data = try? JSONEncoder().encode(["order_number": number]),
|
||||
let order = try? JSONDecoder().decode(DroneDockHomeOrder.self, from: data) {
|
||||
let home = DroneDockHomeViewController()
|
||||
let delivery = DroneDockDeliveryEntry.makeController(order: order, context: DroneDockHomeViewController.currentContext(), taskID: nil)
|
||||
let navigation = UINavigationController()
|
||||
navigation.setViewControllers([home, delivery], animated: false)
|
||||
return navigation
|
||||
}
|
||||
}
|
||||
if (arguments.contains("--dock-payment-live") || arguments.contains("--dock-receipts-live")), AppStore.shared.session.isLoggedIn {
|
||||
let home = DroneDockHomeViewController()
|
||||
let payment = DroneDockPaymentViewController()
|
||||
|
||||
@@ -206,7 +206,7 @@ final class DroneDockRemotePreparationViewController: BaseViewController {
|
||||
switch section {
|
||||
case .order: height = .estimated(100); width = .fractionalWidth(1)
|
||||
case .points:
|
||||
height = .absolute(self.viewModel.spots.isEmpty ? 150 : 80)
|
||||
height = .absolute(self.viewModel.spots.isEmpty ? 150 : 64)
|
||||
width = self.viewModel.spots.isEmpty ? .fractionalWidth(1) : .absolute(160)
|
||||
case .routes:
|
||||
height = self.viewModel.routes.isEmpty ? .absolute(160) : .estimated(64)
|
||||
|
||||
@@ -92,13 +92,11 @@ final class DronePreparationOrderCell: UICollectionViewCell {
|
||||
}
|
||||
}
|
||||
|
||||
/// 横向点位小卡,展示点位、距离与拍摄记录,真实数据缺图时使用中性占位。
|
||||
/// 横向点位小卡,展示点位与拍摄记录,真实数据缺图时使用中性占位。
|
||||
@MainActor
|
||||
final class DronePreparationPointCell: UICollectionViewCell {
|
||||
private let nameLabel = DroneDockStyle.label(size: 13, weight: .semibold)
|
||||
private let rangeLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let countLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
|
||||
private let locationIcon = UIImageView(image: UIImage(systemName: "mappin.circle.fill"))
|
||||
private let thumbnail = UIImageView()
|
||||
|
||||
override init(frame: CGRect) {
|
||||
@@ -110,30 +108,19 @@ final class DronePreparationPointCell: UICollectionViewCell {
|
||||
thumbnail.backgroundColor = DroneDockStyle.background
|
||||
thumbnail.layer.cornerRadius = 5
|
||||
thumbnail.clipsToBounds = true
|
||||
locationIcon.contentMode = .scaleAspectFit
|
||||
[thumbnail, nameLabel, locationIcon, rangeLabel, countLabel].forEach(contentView.addSubview)
|
||||
[thumbnail, nameLabel, countLabel].forEach(contentView.addSubview)
|
||||
thumbnail.snp.makeConstraints { make in
|
||||
make.leading.equalToSuperview().offset(8)
|
||||
make.centerY.equalToSuperview()
|
||||
make.size.equalTo(48)
|
||||
}
|
||||
nameLabel.snp.makeConstraints { make in
|
||||
make.top.equalToSuperview().offset(10)
|
||||
make.bottom.equalTo(contentView.snp.centerY).offset(-3)
|
||||
make.leading.equalTo(thumbnail.snp.trailing).offset(8)
|
||||
make.trailing.equalToSuperview().inset(6)
|
||||
}
|
||||
locationIcon.snp.makeConstraints { make in
|
||||
make.leading.equalTo(nameLabel)
|
||||
make.top.equalTo(nameLabel.snp.bottom).offset(5)
|
||||
make.size.equalTo(10)
|
||||
}
|
||||
rangeLabel.snp.makeConstraints { make in
|
||||
make.leading.equalTo(locationIcon.snp.trailing).offset(3)
|
||||
make.centerY.equalTo(locationIcon)
|
||||
make.trailing.equalToSuperview().inset(5)
|
||||
}
|
||||
countLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(rangeLabel.snp.bottom).offset(4)
|
||||
make.top.equalTo(contentView.snp.centerY).offset(3)
|
||||
make.leading.equalTo(nameLabel)
|
||||
make.trailing.equalToSuperview().inset(5)
|
||||
}
|
||||
@@ -143,43 +130,33 @@ final class DronePreparationPointCell: UICollectionViewCell {
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 仅映射模型提供的范围和次数,已拍摄的点位仍保持可选择。
|
||||
/// 展示点位名称与次数,已拍摄的点位仍保持可选择。
|
||||
func apply(point: DroneShootingPoint, selected: Bool) {
|
||||
thumbnail.kf.cancelDownloadTask()
|
||||
contentView.alpha = 1
|
||||
nameLabel.text = point.name
|
||||
thumbnail.contentMode = .scaleAspectFill
|
||||
thumbnail.image = UIImage(named: point.id == "point-jinque" ? "drone_demo_pagoda" : "drone_demo_mountain")
|
||||
rangeLabel.text = point.range.title
|
||||
switch point.range {
|
||||
case .inside: rangeLabel.textColor = DroneDockStyle.success
|
||||
case .outside: rangeLabel.textColor = DroneDockStyle.secondary
|
||||
case .unknown: rangeLabel.textColor = DroneDockStyle.warning
|
||||
}
|
||||
locationIcon.tintColor = rangeLabel.textColor
|
||||
countLabel.text = point.successfulCountText
|
||||
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : .white
|
||||
contentView.layer.borderColor = (selected ? DroneDockStyle.primary : DroneDockStyle.border).cgColor
|
||||
accessibilityLabel = "\(point.name),\(point.range.title),\(point.successfulCountText)"
|
||||
accessibilityLabel = "\(point.name),\(point.successfulCountText)"
|
||||
accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
accessibilityIdentifier = "drone.preparation.point.\(point.id)"
|
||||
}
|
||||
|
||||
/// 展示已购点位;当前接口未提供距离与点位已拍次数,保持未知占位。
|
||||
/// 展示已购点位与可用性;点位已拍次数缺失时保持未知占位。
|
||||
func apply(spot: DroneDockPurchasedSpot, selected: Bool) {
|
||||
nameLabel.text = spot.name
|
||||
thumbnail.kf.cancelDownloadTask()
|
||||
thumbnail.image = UIImage(systemName: "mappin.and.ellipse")
|
||||
thumbnail.image = UIImage(systemName: "photo")
|
||||
thumbnail.contentMode = .center
|
||||
thumbnail.tintColor = DroneDockStyle.secondary
|
||||
if let text = spot.coverURL, let url = URL(string: text),
|
||||
let scheme = url.scheme?.lowercased(), ["https", "http"].contains(scheme), url.host != nil {
|
||||
thumbnail.contentMode = .scaleAspectFill
|
||||
thumbnail.kf.setImage(with: url, placeholder: UIImage(systemName: "mappin.and.ellipse"))
|
||||
thumbnail.kf.setImage(with: url, placeholder: UIImage(systemName: "photo"))
|
||||
}
|
||||
rangeLabel.text = "距离待确认"
|
||||
rangeLabel.textColor = DroneDockStyle.secondary
|
||||
locationIcon.tintColor = rangeLabel.textColor
|
||||
if spot.available != true {
|
||||
countLabel.text = spot.available == false ? "拍摄点不可用" : "可用性待确认"
|
||||
} else {
|
||||
@@ -188,7 +165,7 @@ final class DronePreparationPointCell: UICollectionViewCell {
|
||||
contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : .white
|
||||
contentView.layer.borderColor = (selected ? DroneDockStyle.primary : DroneDockStyle.border).cgColor
|
||||
contentView.alpha = spot.available == true ? 1 : 0.55
|
||||
accessibilityLabel = "\(spot.name),\(rangeLabel.text ?? ""),\(countLabel.text ?? "")"
|
||||
accessibilityLabel = "\(spot.name),\(countLabel.text ?? "")"
|
||||
accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
if spot.available != true { accessibilityTraits.insert(.notEnabled) }
|
||||
accessibilityIdentifier = "drone.preparation.point.\(spot.id)"
|
||||
@@ -417,7 +394,7 @@ final class DronePreparationEmptyCell: UICollectionViewCell {
|
||||
}
|
||||
}
|
||||
|
||||
/// 固定底部许可栏,独立刷新连接、范围、设备与主按钮。
|
||||
/// 固定底部许可栏,独立刷新连接、设备与主按钮。
|
||||
@MainActor
|
||||
final class DronePreparationFooterView: UIView {
|
||||
/// 工作人员主动点击主操作时通知控制器。
|
||||
@@ -426,7 +403,6 @@ final class DronePreparationFooterView: UIView {
|
||||
var onRefreshTap: (() -> Void)?
|
||||
|
||||
private let connectionLabel = DronePreparationIndicatorView()
|
||||
private let rangeLabel = DronePreparationIndicatorView()
|
||||
private let selectionLabel = DroneDockStyle.label(size: 13, weight: .semibold)
|
||||
private let deviceCaption = DroneDockStyle.label("无人机:", size: 11, color: DroneDockStyle.secondary)
|
||||
private let deviceLabel = DroneDockStatusLabel()
|
||||
@@ -437,13 +413,8 @@ final class DronePreparationFooterView: UIView {
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
backgroundColor = .white
|
||||
let statusRow = UIStackView(arrangedSubviews: [connectionLabel, rangeLabel])
|
||||
statusRow.axis = .horizontal
|
||||
statusRow.distribution = .fillEqually
|
||||
let divider = UIView()
|
||||
divider.backgroundColor = DroneDockStyle.border
|
||||
let verticalDivider = UIView()
|
||||
verticalDivider.backgroundColor = DroneDockStyle.border
|
||||
let deviceRow = UIStackView(arrangedSubviews: [deviceCaption, deviceLabel, UIView()])
|
||||
deviceRow.axis = .horizontal
|
||||
deviceRow.alignment = .center
|
||||
@@ -470,19 +441,13 @@ final class DronePreparationFooterView: UIView {
|
||||
primaryButton.titleLabel?.minimumScaleFactor = 0.85
|
||||
primaryButton.accessibilityIdentifier = "drone.preparation.summon"
|
||||
primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside)
|
||||
[statusRow, divider, summary, primaryButton, messageRow].forEach(addSubview)
|
||||
statusRow.addSubview(verticalDivider)
|
||||
statusRow.snp.makeConstraints { make in
|
||||
[connectionLabel, divider, summary, primaryButton, messageRow].forEach(addSubview)
|
||||
connectionLabel.snp.makeConstraints { make in
|
||||
make.leading.trailing.top.equalToSuperview()
|
||||
make.height.equalTo(42)
|
||||
}
|
||||
verticalDivider.snp.makeConstraints { make in
|
||||
make.center.equalToSuperview()
|
||||
make.width.equalTo(1 / UIScreen.main.scale)
|
||||
make.height.equalTo(18)
|
||||
}
|
||||
divider.snp.makeConstraints { make in
|
||||
make.top.equalTo(statusRow.snp.bottom)
|
||||
make.top.equalTo(connectionLabel.snp.bottom)
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.height.equalTo(1 / UIScreen.main.scale)
|
||||
}
|
||||
@@ -515,7 +480,6 @@ final class DronePreparationFooterView: UIView {
|
||||
/// 只绑定 ViewModel 已计算的展示内容和许可,不按电量或连接自行判定可召唤。
|
||||
func apply(viewModel: DroneShootingPreparationViewModel) {
|
||||
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
|
||||
rangeLabel.apply(title: viewModel.rangeTitle, tone: viewModel.rangeTone)
|
||||
selectionLabel.text = viewModel.selectionSummary
|
||||
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceState.tone)
|
||||
primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal)
|
||||
@@ -523,7 +487,12 @@ final class DronePreparationFooterView: UIView {
|
||||
primaryButton.backgroundColor = viewModel.primaryButtonEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE1E7F0)
|
||||
primaryButton.setTitleColor(.white, for: .normal)
|
||||
primaryButton.setTitleColor(UIColor(hex: 0x8792A5), for: .disabled)
|
||||
messageLabel.text = viewModel.admission.message
|
||||
switch viewModel.admission {
|
||||
case .outOfRange, .unknownRange:
|
||||
messageLabel.text = "当前暂不可召唤,请稍后重试"
|
||||
default:
|
||||
messageLabel.text = viewModel.admission.message
|
||||
}
|
||||
messageLabel.textColor = DroneDockStyle.color(for: viewModel.admission.tone)
|
||||
refreshButton.isHidden = !viewModel.shouldShowSummonRefresh
|
||||
}
|
||||
@@ -531,7 +500,6 @@ final class DronePreparationFooterView: UIView {
|
||||
/// 展示真实准备状态;本阶段保留召唤按钮文案,但尚不提供飞行执行入口。
|
||||
func apply(preparationViewModel viewModel: DroneDockPreparationViewModel, isRefreshing: Bool = false) {
|
||||
connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone)
|
||||
rangeLabel.apply(title: viewModel.rangeTitle, tone: viewModel.rangeTone)
|
||||
selectionLabel.text = viewModel.selectionSummary
|
||||
selectionLabel.numberOfLines = 2
|
||||
deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceTone)
|
||||
@@ -549,7 +517,7 @@ final class DronePreparationFooterView: UIView {
|
||||
@objc private func refreshTapped() { onRefreshTap?() }
|
||||
}
|
||||
|
||||
/// 连接与范围共用的小型状态图标,图标只映射语义色。
|
||||
/// 机巢连接的小型状态图标,图标只映射语义色。
|
||||
@MainActor
|
||||
private final class DronePreparationIndicatorView: UIView {
|
||||
private let icon = UIImageView()
|
||||
|
||||
@@ -136,7 +136,7 @@ final class DroneShootingPreparationViewController: BaseViewController {
|
||||
height = .estimated(90)
|
||||
case .points:
|
||||
width = self.viewModel.points.isEmpty ? .fractionalWidth(1) : .absolute(144)
|
||||
height = self.viewModel.points.isEmpty ? .absolute(124) : .absolute(80)
|
||||
height = self.viewModel.points.isEmpty ? .absolute(124) : .absolute(64)
|
||||
case .routes:
|
||||
width = .fractionalWidth(1)
|
||||
height = self.viewModel.routes.isEmpty ? .absolute(200) : .absolute(64)
|
||||
|
||||
Reference in New Issue
Block a user