feat(drone-dock): 接入游客确认交付并对齐网页样式
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
#if DEBUG
|
||||
/// 正式交付确认页的隔离预览,接口、图片和封面均由本机提供。
|
||||
@MainActor
|
||||
enum DroneDockConfirmationSimulation {
|
||||
/// 显式启动参数选择确认场景,不读取真实登录身份或回退线上服务。
|
||||
static func makeController(arguments: [String]) -> UIViewController? {
|
||||
let flag = "--dock-confirmation-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 scenario = value.flatMap(DroneDockConfirmationMockScenario.init(rawValue:)) ?? .ready
|
||||
let session = DroneDockConfirmationMockSession(scenario: scenario)
|
||||
let environment = APIEnvironment(baseURL: URL(string: "https://mock.invalid")!,
|
||||
webSocketURL: URL(string: "wss://mock.invalid/unused")!)
|
||||
let client = APIClient(environment: environment, session: session, debugLogSink: { _ in })
|
||||
let context = DroneDockHomeContext(userID: "local-confirmation-mock", accountType: "store_user",
|
||||
scenicID: 901, scenicName: "本地模拟景区", storeID: 901,
|
||||
photographerName: "本地模拟工作人员", token: "local-confirmation-only")
|
||||
client.bindAuthTokenProvider { "local-confirmation-only" }
|
||||
guard let orderData = try? JSONSerialization.data(withJSONObject: session.initialDetail),
|
||||
let order = try? JSONDecoder().decode(DroneDockHomeOrder.self, from: orderData) else { return nil }
|
||||
let model = DroneDockConfirmationViewModel(context: context, order: order,
|
||||
service: DroneDockConfirmationAPI(client: client), currentContext: { context })
|
||||
let controller = DroneDockConfirmationViewController(viewModel: model,
|
||||
imageLoader: DroneDockConfirmationMockImageLoader(failsFirstLoad: scenario == .imageFailed),
|
||||
allowsRemoteMedia: false,
|
||||
thumbnailProvider: { UIImage(named: $0.spotID == 302 ? "drone_demo_pagoda" : "drone_demo_mountain") },
|
||||
deliveryControllerFactory: { _, _, _ in
|
||||
let preview = UIViewController()
|
||||
preview.title = "云端交付 · 本地模拟"
|
||||
preview.view.backgroundColor = .white
|
||||
let label = UILabel()
|
||||
label.text = "本地 UI 预览,不上传文件"
|
||||
label.textAlignment = .center
|
||||
preview.view.addSubview(label)
|
||||
label.translatesAutoresizingMaskIntoConstraints = false
|
||||
NSLayoutConstraint.activate([
|
||||
label.centerXAnchor.constraint(equalTo: preview.view.centerXAnchor),
|
||||
label.centerYAnchor.constraint(equalTo: preview.view.centerYAnchor)
|
||||
])
|
||||
return preview
|
||||
})
|
||||
controller.navigationItem.prompt = "本地模拟 · 未联网 · 不可扫码"
|
||||
print("[LOCAL MOCK][Confirmation] 场景=\(scenario.rawValue),全部响应来自内存,不连接后端或设备")
|
||||
return controller
|
||||
}
|
||||
}
|
||||
|
||||
/// 确认页预览场景,不表示任何真实订单或游客的操作结果。
|
||||
private enum DroneDockConfirmationMockScenario: String {
|
||||
case ready, empty, completeAfterRefresh, generationFailed, imageFailed, confirmed
|
||||
}
|
||||
|
||||
/// 仅接受模拟域名和固定订单的内存传输,没有 URLSession 或网络回退路径。
|
||||
private final class DroneDockConfirmationMockSession: LocalSimulationURLSession {
|
||||
private let scenario: DroneDockConfirmationMockScenario
|
||||
private let lock = NSLock()
|
||||
private var generationAttempts = 0
|
||||
private var hasInvitation = false
|
||||
private var hasGeneratedImage = false
|
||||
private static let orderNumber = "LOCAL-MOCK-CONFIRM-901"
|
||||
private static let prefix = "/api/yf-handset-app/photog/multi-plane"
|
||||
|
||||
/// 每次进入建立独立场景状态,不与其他模拟页面或真实订单共享。
|
||||
init(scenario: DroneDockConfirmationMockScenario) { self.scenario = scenario }
|
||||
|
||||
/// 用于页面入口的固定摘要,读取它不会推进模拟状态。
|
||||
var initialDetail: [String: Any] { detail(completed: scenario == .confirmed, invited: false) }
|
||||
|
||||
/// 真实 API 请求经过本方法获得模拟 JSON,未知请求直接失败且绝不转发。
|
||||
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
|
||||
try Task.checkCancellation()
|
||||
let data = try lock.withLock { try responseData(for: request) }
|
||||
guard let url = request.url,
|
||||
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil) else {
|
||||
throw URLError(.badURL)
|
||||
}
|
||||
print("[LOCAL MOCK][Confirmation Request] \(request.httpMethod ?? "") \(url.absoluteString) — 纯内存,未联网")
|
||||
if let body = request.httpBody { print(String(decoding: body, as: UTF8.self)) }
|
||||
print("[LOCAL MOCK][Confirmation Response] \(String(decoding: data, as: UTF8.self))")
|
||||
return (data, response)
|
||||
}
|
||||
|
||||
private func responseData(for request: URLRequest) throws -> Data {
|
||||
guard let url = request.url, url.scheme == "https", url.host == "mock.invalid" else {
|
||||
throw APIError.networkFailed("本地确认模拟拒绝外部请求")
|
||||
}
|
||||
let payload: [String: Any]
|
||||
if request.httpMethod == "GET" {
|
||||
let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
|
||||
guard items.filter({ $0.name == "scenic_id" }).map(\.value) == ["901"],
|
||||
items.filter({ $0.name == "order_number" }).map(\.value) == [Self.orderNumber] else {
|
||||
throw APIError.networkFailed("本地确认模拟拒绝真实景区或订单")
|
||||
}
|
||||
switch url.path {
|
||||
case Self.prefix + "/orders/detail":
|
||||
guard Set(items.map(\.name)) == ["scenic_id", "order_number"] else {
|
||||
throw APIError.networkFailed("本地确认详情不支持其他参数")
|
||||
}
|
||||
payload = detail(completed: scenario == .confirmed || (scenario == .completeAfterRefresh && hasGeneratedImage),
|
||||
invited: hasInvitation)
|
||||
case Self.prefix + "/tasks":
|
||||
guard Set(items.map(\.name)).isSubset(of: ["scenic_id", "order_number", "scenic_spot_id"]) else {
|
||||
throw APIError.networkFailed("本地确认任务不支持其他参数")
|
||||
}
|
||||
let spotItems = items.filter { $0.name == "scenic_spot_id" }
|
||||
let spotID = spotItems.first?.value.flatMap(Int.init)
|
||||
guard spotItems.isEmpty || (spotItems.count == 1 && spotID.map({ $0 > 0 }) == true) else {
|
||||
throw APIError.networkFailed("本地确认模拟拒绝无效点位筛选")
|
||||
}
|
||||
let list = tasks().filter { spotID == nil || ($0["scenic_spot_id"] as? Int) == spotID }
|
||||
payload = ["order_number": Self.orderNumber, "total": list.count, "list": list]
|
||||
default:
|
||||
throw APIError.networkFailed("本地确认模拟拒绝未配置接口")
|
||||
}
|
||||
} else if request.httpMethod == "POST", url.path == Self.prefix + "/orders/confirm-code" {
|
||||
guard url.query == nil, let data = request.httpBody,
|
||||
let body = try JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
Set(body.keys) == ["scenic_id", "order_number"],
|
||||
body["scenic_id"] as? Int == 901, body["order_number"] as? String == Self.orderNumber else {
|
||||
throw APIError.networkFailed("本地确认模拟拒绝非约定出码请求")
|
||||
}
|
||||
guard scenario != .confirmed, !(scenario == .completeAfterRefresh && hasGeneratedImage) else {
|
||||
return try envelope([:], code: 160001, message: "本地模拟:订单已完成,不可生成确认码")
|
||||
}
|
||||
generationAttempts += 1
|
||||
hasInvitation = true
|
||||
if scenario == .generationFailed, generationAttempts == 1 {
|
||||
return try envelope([:], code: 160001, message: "本地模拟:确认码生成失败,请重试")
|
||||
}
|
||||
hasGeneratedImage = true
|
||||
payload = ["order_number": Self.orderNumber, "confirm_status": 1,
|
||||
"confirm_url": "https://mock.invalid/mini_qr/confirmation.png"]
|
||||
} else {
|
||||
throw APIError.networkFailed("本地确认模拟不支持此请求,不会访问后端或设备")
|
||||
}
|
||||
return try envelope(payload)
|
||||
}
|
||||
|
||||
private func detail(completed: Bool, invited: Bool) -> [String: Any] {
|
||||
["order_number": Self.orderNumber, "project_id": 901, "project_name": "本地模拟双点位航拍",
|
||||
"created_at": "2026-10-30 10:00:00", "user_phone": "158****8888",
|
||||
"shoot_count": 3, "shot_count": 3, "remaining_count": 0,
|
||||
"shoot_status": completed ? "completed" : "processing", "order_status": completed ? 30 : 20,
|
||||
"material_status": 0, "film_count": scenario == .empty ? 0 : 3,
|
||||
"can_create_task": false, "can_upload_film": !completed, "can_confirm": !completed,
|
||||
"confirm_status": completed ? 2 : invited ? 1 : 0,
|
||||
"confirmed_at": completed ? "2026-10-30 10:30:00" as Any : NSNull(),
|
||||
"spot": [["scenic_spot_id": 301, "scenic_spot_name": "三皇寨"],
|
||||
["scenic_spot_id": 302, "scenic_spot_name": "金阙云宫"]]]
|
||||
}
|
||||
|
||||
private func tasks() -> [[String: Any]] {
|
||||
[301, 301, 302].enumerated().map { index, spotID in
|
||||
let taskID = index + 901
|
||||
let title = spotID == 301 ? "三皇寨" : "金阙云宫"
|
||||
var value: [String: Any] = [
|
||||
"id": taskID, "task_id": taskID, "order_number": Self.orderNumber,
|
||||
"scenic_spot_id": spotID, "scenic_spot_name": title,
|
||||
"air_line_name": "本地模拟航线", "seq": index + 1,
|
||||
"flight_status": 30, "material_status": 0,
|
||||
"created_at": "2026-10-30 10:10:00", "materials": [], "film": NSNull()
|
||||
]
|
||||
if scenario != .empty {
|
||||
value["film"] = ["id": taskID + 1000, "task_id": taskID,
|
||||
"file_name": "\(title)本地模拟成片.mp4", "file_size": 8_388_608,
|
||||
"file_url": "https://mock.invalid/films/\(taskID).mp4",
|
||||
"cover_url": "https://mock.invalid/covers/\(taskID).jpg"]
|
||||
}
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
private func envelope(_ data: [String: Any], code: Int = 100000, message: String = "success") throws -> Data {
|
||||
try JSONSerialization.data(withJSONObject: ["code": code, "msg": message, "data": data,
|
||||
"time": "2026-10-30 10:30:00"], options: [.sortedKeys])
|
||||
}
|
||||
}
|
||||
|
||||
/// 确认码图片的本地替身,只绘制不可扫码文字且不尝试下载 URL。
|
||||
@MainActor
|
||||
private final class DroneDockConfirmationMockImageLoader: DroneDockPaymentImageLoading {
|
||||
private let failsFirstLoad: Bool
|
||||
private var loadCount = 0
|
||||
private var generation = 0
|
||||
|
||||
/// 图片失败场景只拒绝首轮读取,之后允许用户显式重试。
|
||||
init(failsFirstLoad: Bool) { self.failsFirstLoad = failsFirstLoad }
|
||||
|
||||
/// 忽略远程地址的内容,返回带明确模拟来源的纯文字图片。
|
||||
func loadImage(from url: URL, forceRefresh: Bool,
|
||||
completion: @escaping @MainActor @Sendable (Result<UIImage, Error>) -> Void) {
|
||||
generation &+= 1
|
||||
let currentGeneration = generation
|
||||
loadCount += 1
|
||||
let shouldFail = failsFirstLoad && loadCount == 1
|
||||
Task { @MainActor [weak self] in
|
||||
await Task.yield()
|
||||
guard let self, self.generation == currentGeneration else { return }
|
||||
print("[LOCAL MOCK][Confirmation Image] \(shouldFail ? "模拟加载失败" : "本机文字占位") — 未下载图片")
|
||||
if shouldFail {
|
||||
completion(.failure(APIError.networkFailed("本地模拟:确认码图片加载失败")))
|
||||
return
|
||||
}
|
||||
let image = UIGraphicsImageRenderer(size: CGSize(width: 260, height: 260)).image { context in
|
||||
UIColor.white.setFill()
|
||||
context.fill(CGRect(x: 0, y: 0, width: 260, height: 260))
|
||||
let paragraph = NSMutableParagraphStyle()
|
||||
paragraph.alignment = .center
|
||||
("本地模拟·不可扫码" as NSString).draw(in: CGRect(x: 10, y: 115, width: 240, height: 40),
|
||||
withAttributes: [.font: UIFont.systemFont(ofSize: 20, weight: .semibold),
|
||||
.foregroundColor: UIColor(hex: 0x066BFF), .paragraphStyle: paragraph])
|
||||
}
|
||||
completion(.success(image))
|
||||
}
|
||||
}
|
||||
|
||||
/// 让旧图片回调失效,不涉及任何真实图片传输。
|
||||
func cancel() { generation &+= 1 }
|
||||
}
|
||||
#endif
|
||||
Reference in New Issue
Block a user