278 lines
15 KiB
Swift
278 lines
15 KiB
Swift
import SnapKit
|
|
import UIKit
|
|
|
|
#if DEBUG
|
|
/// 使用正式订单素材页和内存服务验证各展示状态,不读取登录身份或连接后端。
|
|
@MainActor
|
|
enum DroneDockMaterialsSimulation {
|
|
/// 支持显式场景参数,未传场景的模拟入口默认展示混合上传状态。
|
|
static func makeController(arguments: [String]) -> UIViewController? {
|
|
let flag = "--dock-materials-mock"
|
|
guard arguments.contains(flag) || arguments.contains(where: { $0.hasPrefix(flag + "=") }) else { return nil }
|
|
let value = arguments.first(where: { $0.hasPrefix(flag + "=") }).map { String($0.dropFirst(flag.count + 1)) }
|
|
let localFlag = "--dock-materials-download-local="
|
|
let localValue = arguments.first(where: { $0.hasPrefix(localFlag) }).map { String($0.dropFirst(localFlag.count)) }
|
|
let localBaseURL = value == "ready" ? localValue.flatMap(loopbackBaseURL) : nil
|
|
return makeController(scenario: value ?? "mixed", localBaseURL: localBaseURL)
|
|
}
|
|
|
|
/// 创建全新模拟会话;同一页的点位筛选、选择及刷新仍由正式 ViewModel 执行。
|
|
static func makeController(scenario: String) -> UIViewController? {
|
|
makeController(scenario: scenario, localBaseURL: nil)
|
|
}
|
|
|
|
private static func makeController(scenario: String, localBaseURL: URL?) -> UIViewController? {
|
|
let state = DroneDockMaterialsMockScenario(rawValue: scenario) ?? .mixed
|
|
guard let service = try? DroneDockMaterialsMockService(scenario: state, localBaseURL: localBaseURL) else { return nil }
|
|
let context = DroneDockHomeContext(userID: "local-materials-mock", accountType: "store_user",
|
|
scenicID: 901, scenicName: "本地模拟景区", storeID: 901,
|
|
photographerName: "本地演示", token: "local-materials-only")
|
|
let model = DroneDockMaterialsViewModel(context: context, order: service.order,
|
|
service: service, currentContext: { context })
|
|
let downloadService: ScenicMaterialDownloadService
|
|
if localBaseURL != nil {
|
|
downloadService = ScenicMaterialDownloadService()
|
|
} else {
|
|
downloadService = ScenicMaterialDownloadService(
|
|
downloader: DroneDockMaterialsMockDownloader(), photoSaver: DroneDockMaterialsMockPhotoSaver())
|
|
}
|
|
let downloadModel = DroneDockMaterialDownloadViewModel(service: downloadService,
|
|
isContextValid: { [weak model] in model?.acceptsDownloadContext() == true })
|
|
let controller = DroneDockMaterialsViewController(viewModel: model,
|
|
deliveryControllerFactory: { _, _, _ in
|
|
DroneDockMaterialsMockPreviewController(title: "交付成片 · 本地演示", image: nil,
|
|
message: "本地演示仅验证入口,不连接云端或上传文件。")
|
|
},
|
|
thumbnailProvider: { taskID, fileID in
|
|
guard service.isReady(taskID: taskID, fileID: fileID) else { return nil }
|
|
return UIImage(named: taskID == 902 ? "drone_demo_pagoda" : fileID.isMultiple(of: 2) ? "drone_demo_mountain" : "drone_demo_tourists")
|
|
},
|
|
mediaPreviewControllerFactory: { _, isVideo, title in
|
|
DroneDockMaterialsMockPreviewController(title: title, image: UIImage(named: "drone_demo_tourists"),
|
|
message: isVideo ? "本地演示视频封面,不请求远程片源。" : "本地演示图片,不请求远程文件。")
|
|
},
|
|
downloadViewModel: downloadModel,
|
|
downloadSourceDescription: localBaseURL == nil ? "本地演示 · 未下载或保存真实文件" : "本地测试素材 · 保存至系统相册",
|
|
downloadIsSimulated: localBaseURL == nil)
|
|
controller.navigationItem.prompt = localBaseURL == nil ? "本地演示 · 未联网" : "本地测试素材 · 无业务请求"
|
|
return controller
|
|
}
|
|
|
|
/// 本地保存验证只接受显式 IPv4 回环地址与端口,路径和文件名由代码固定。
|
|
private static func loopbackBaseURL(_ value: String) -> URL? {
|
|
guard let parts = URLComponents(string: value), parts.scheme == "http", parts.host == "127.0.0.1",
|
|
let port = parts.port, (1...65_535).contains(port),
|
|
parts.user == nil, parts.password == nil, parts.query == nil, parts.fragment == nil,
|
|
parts.path.isEmpty || parts.path == "/" else { return nil }
|
|
var canonical = URLComponents()
|
|
canonical.scheme = "http"
|
|
canonical.host = "127.0.0.1"
|
|
canonical.port = port
|
|
return canonical.url
|
|
}
|
|
}
|
|
|
|
/// 上传、记录及首屏异常的固定样例,不表示实际接口或设备状态。
|
|
private enum DroneDockMaterialsMockScenario: String {
|
|
case ready, uploading, uploadFailed, mixed, empty, loading, error, taskUploading, taskFailed, film
|
|
}
|
|
|
|
/// 通过正式解码器构造的纯内存素材服务,没有真实网络或共享账号依赖。
|
|
@MainActor
|
|
private final class DroneDockMaterialsMockService: DroneDockMaterialsServing {
|
|
private let scenario: DroneDockMaterialsMockScenario
|
|
private let detailValue: DroneDockMaterialDetail
|
|
private let taskValues: [[String: Any]]
|
|
|
|
/// 合成订单用于正式页面的入口身份,不可用于真实请求。
|
|
var order: DroneDockHomeOrder { detailValue.order }
|
|
|
|
/// 固定三条拍摄记录与两处购买点位,文件状态由场景决定。
|
|
init(scenario: DroneDockMaterialsMockScenario, localBaseURL: URL? = nil) throws {
|
|
self.scenario = scenario
|
|
let detail: [String: Any] = [
|
|
"order_number": "LOCAL-MOCK-MATERIALS-901", "project_id": 901,
|
|
"project_name": "模拟航拍套餐", "user_phone": "158****8888",
|
|
"shoot_count": 5, "shot_count": scenario == .empty ? 0 : 3,
|
|
"remaining_count": scenario == .empty ? 5 : 2, "shoot_status": "processing",
|
|
"order_status": 20, "can_upload_film": true, "can_create_task": true,
|
|
"spot": [["scenic_spot_id": 301, "scenic_spot_name": "三皇寨"],
|
|
["scenic_spot_id": 302, "scenic_spot_name": "金阙云宫"]]
|
|
]
|
|
detailValue = try JSONDecoder().decode(DroneDockMaterialDetail.self,
|
|
from: JSONSerialization.data(withJSONObject: detail))
|
|
taskValues = scenario == .empty ? [] : [3, 2, 1].map { sequence in
|
|
let taskID = 900 + sequence
|
|
let isPagoda = sequence == 2
|
|
let files: [[String: Any]] = [sequence * 2 - 1, sequence * 2].map { fileID in
|
|
let status = Self.uploadStatus(scenario: scenario, sequence: sequence, fileID: fileID)
|
|
let fileURL = localBaseURL?.appendingPathComponent(fileID.isMultiple(of: 2) ? "demo.jpg" : "demo.mp4").absoluteString
|
|
?? "https://mock.invalid/media/\(taskID)/\(fileID)"
|
|
return ["id": fileID, "file_name": String(format: "素材%02d", fileID),
|
|
"file_type": fileID.isMultiple(of: 2) ? 1 : 2,
|
|
"file_size": 4_194_304,
|
|
"file_url": status == 1 ? fileURL : "",
|
|
"cover_url": "", "upload_status": status,
|
|
"failure_reason": status == 3 ? "本地演示:素材上传失败,请刷新查看最新状态" : ""]
|
|
}
|
|
let taskOnly = scenario == .taskUploading || scenario == .taskFailed
|
|
var task: [String: Any] = [
|
|
"id": taskID, "order_number": "LOCAL-MOCK-MATERIALS-901", "seq": sequence,
|
|
"scenic_spot_id": isPagoda ? 302 : 301,
|
|
"scenic_spot_name": isPagoda ? "金阙云宫" : "三皇寨",
|
|
"air_line_name": isPagoda ? "云宫环绕" : "经典航线",
|
|
"created_at": "2026-10-29 \(sequence == 3 ? "14:32:00" : sequence == 2 ? "14:10:00" : "13:45:00")",
|
|
"flight_status": 30,
|
|
"material_status": scenario == .taskFailed || scenario == .uploadFailed ? 3 : scenario == .ready || scenario == .film ? 1 : 2,
|
|
"materials": taskOnly ? [] : files, "film": NSNull()
|
|
]
|
|
if scenario == .film, sequence == 3 {
|
|
task["film"] = ["id": 8001, "task_id": taskID, "file_name": "已交付成片",
|
|
"file_size": 8_388_608, "cover_url": "",
|
|
"file_url": "https://mock.invalid/film/\(taskID)"]
|
|
}
|
|
return task
|
|
}
|
|
}
|
|
|
|
/// 纯内存详情;加载场景等待取消,错误场景提供明确失败。
|
|
func detail(scenicID: Int, orderNumber: String) async throws -> DroneDockMaterialDetail {
|
|
try validate(scenicID: scenicID, orderNumber: orderNumber)
|
|
if scenario == .loading {
|
|
while true { try await Task.sleep(nanoseconds: 30_000_000_000) }
|
|
}
|
|
if scenario == .error { throw APIError.networkFailed("本地演示:订单素材读取失败,请稍后重试") }
|
|
try Task.checkCancellation()
|
|
return detailValue
|
|
}
|
|
|
|
/// 根据所选点位过滤内存任务,不发出 HTTP 请求。
|
|
func tasks(scenicID: Int, orderNumber: String, spotID: Int?) async throws -> DroneDockMaterialTasks {
|
|
try validate(scenicID: scenicID, orderNumber: orderNumber)
|
|
try Task.checkCancellation()
|
|
let values = taskValues.filter { spotID == nil || ($0["scenic_spot_id"] as? Int) == spotID }
|
|
return try JSONDecoder().decode(DroneDockMaterialTasks.self, from: JSONSerialization.data(withJSONObject: [
|
|
"order_number": orderNumber, "total": values.count, "list": values
|
|
]))
|
|
}
|
|
|
|
/// 仅就绪样例使用本地缩略图,上传中和失败仍保留页面占位样式。
|
|
func isReady(taskID: Int, fileID: Int) -> Bool {
|
|
guard let task = taskValues.first(where: { $0["id"] as? Int == taskID }),
|
|
let files = task["materials"] as? [[String: Any]],
|
|
let file = files.first(where: { $0["id"] as? Int == fileID }) else { return false }
|
|
return file["upload_status"] as? Int == 1
|
|
}
|
|
|
|
private func validate(scenicID: Int, orderNumber: String) throws {
|
|
guard scenicID == 901, orderNumber == "LOCAL-MOCK-MATERIALS-901" else {
|
|
throw APIError.networkFailed("本地素材演示不接受真实订单身份")
|
|
}
|
|
}
|
|
|
|
private static func uploadStatus(scenario: DroneDockMaterialsMockScenario, sequence: Int, fileID: Int) -> Int {
|
|
switch scenario {
|
|
case .uploading, .taskUploading: return 2
|
|
case .uploadFailed, .taskFailed: return 3
|
|
case .mixed:
|
|
if sequence == 3, fileID.isMultiple(of: 2) { return 2 }
|
|
if sequence == 2, !fileID.isMultiple(of: 2) { return 3 }
|
|
return 1
|
|
default: return 1
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 为纯本地演示复制 App 内的测试媒体,不访问网络,也不会将请求转发给真实下载器。
|
|
private struct DroneDockMaterialsMockDownloader: CloudFileDownloading {
|
|
private let videoURL: URL?
|
|
private let imageData: Data?
|
|
|
|
/// 在主线程读取 UIKit 图片资源,后续下载仅复制固定文件或数据。
|
|
@MainActor
|
|
init() {
|
|
videoURL = Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4")
|
|
?? Bundle.main.url(forResource: "drone_material_demo", withExtension: "mp4", subdirectory: "DroneDock")
|
|
imageData = UIImage(named: "drone_demo_tourists")?.jpegData(compressionQuality: 0.8)
|
|
}
|
|
|
|
/// 模拟约 0.3 秒的传输进度,返回独立临时文件供正式服务清理。
|
|
func downloadFile(remoteURL: String, fileName: String,
|
|
onProgress: @escaping @Sendable (Int) -> Void) async throws -> URL {
|
|
guard let url = URL(string: remoteURL), url.scheme == "https", url.host == "mock.invalid",
|
|
url.pathComponents.count == 4, url.pathComponents[1] == "media",
|
|
let identifier = Int(url.lastPathComponent) else { throw ScenicMaterialDownloadError.invalidURL }
|
|
for percent in [30, 60, 100] {
|
|
try await Task.sleep(nanoseconds: 100_000_000)
|
|
onProgress(percent)
|
|
}
|
|
try Task.checkCancellation()
|
|
let isImage = identifier.isMultiple(of: 2)
|
|
let destination = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("dock-materials-demo-\(UUID().uuidString).\(isImage ? "jpg" : "mp4")")
|
|
if isImage {
|
|
guard let imageData else { throw CloudTransferError.localFileMissing }
|
|
try imageData.write(to: destination)
|
|
} else {
|
|
guard let videoURL else { throw CloudTransferError.localFileMissing }
|
|
try FileManager.default.copyItem(at: videoURL, to: destination)
|
|
}
|
|
return destination
|
|
}
|
|
}
|
|
|
|
/// 纯本地演示的保存替身,不请求 Photos 权限、不创建相册资产。
|
|
private struct DroneDockMaterialsMockPhotoSaver: CloudPhotoSaving {
|
|
/// 仅检查演示文件存在;界面明确标为模拟完成,不表示系统相册保存成功。
|
|
func saveToPhotoLibrary(fileURL: URL, fileType: Int) async throws {
|
|
try Task.checkCancellation()
|
|
guard FileManager.default.fileExists(atPath: fileURL.path) else { throw CloudTransferError.localFileMissing }
|
|
}
|
|
}
|
|
|
|
/// 图片预览及交付入口的本地占位,不使用播放器、云端上传或相册权限。
|
|
@MainActor
|
|
private final class DroneDockMaterialsMockPreviewController: BaseViewController {
|
|
private let image: UIImage?
|
|
private let message: String
|
|
private let imageView = UIImageView()
|
|
private let messageLabel = UILabel()
|
|
|
|
/// 固定当前演示内容,防止跳入真实媒体或上传服务。
|
|
init(title: String, image: UIImage?, message: String) {
|
|
self.image = image
|
|
self.message = message
|
|
super.init(nibName: nil, bundle: nil)
|
|
self.title = title
|
|
navigationItem.prompt = "本地演示 · 未联网"
|
|
}
|
|
|
|
@available(*, unavailable)
|
|
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
|
|
|
override func setupUI() {
|
|
view.backgroundColor = .systemBackground
|
|
imageView.image = image
|
|
imageView.contentMode = .scaleAspectFit
|
|
messageLabel.text = message
|
|
messageLabel.numberOfLines = 0
|
|
messageLabel.font = .systemFont(ofSize: 14)
|
|
messageLabel.textAlignment = .center
|
|
view.addSubview(imageView)
|
|
view.addSubview(messageLabel)
|
|
}
|
|
|
|
override func setupConstraints() {
|
|
imageView.snp.makeConstraints { make in
|
|
make.leading.trailing.equalToSuperview().inset(16)
|
|
make.top.equalTo(view.safeAreaLayoutGuide).offset(24)
|
|
make.height.equalTo(view).multipliedBy(0.5)
|
|
}
|
|
messageLabel.snp.makeConstraints { make in
|
|
make.top.equalTo(imageView.snp.bottom).offset(16)
|
|
make.leading.trailing.equalTo(imageView)
|
|
}
|
|
}
|
|
}
|
|
#endif
|