import Foundation /// 张工创建待飞任务的回执,保留最新订单摘要和完整 data 字段供联调展示。 struct DroneDockCreatedTask: Decodable, Equatable, Sendable { /// 后端创建的订单飞行任务 ID,后续召唤应复用该任务。 let taskID: Int /// 创建后的权威订单摘要,待飞任务不由客户端扣减次数。 let order: DroneDockHomeOrder /// 格式化后的完整 data JSON;不添加或伪造外层 code、msg、time。 let dataJSON: String /// 创建任务回执的必需身份字段。 private enum CodingKeys: String, CodingKey { case taskID = "task_id" } /// 任务身份允许整数字符串,但必须为正整数;额外字段保留原 JSON 类型。 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") } guard taskID > 0 else { throw DecodingError.dataCorruptedError(forKey: .taskID, in: container, debugDescription: "创建任务返回的任务 ID 必须为正整数") } order = try DroneDockHomeOrder(from: decoder) let rawData = try DroneDockHomeJSONValue(from: decoder) let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] dataJSON = String(decoding: try encoder.encode(DroneDockTaskJSONSnapshot(value: rawData)), as: UTF8.self) } } /// 复用现有 JSON 值解码器,将回执 data 格式化,保留未建模字段和空值。 private struct DroneDockTaskJSONSnapshot: Encodable { let value: DroneDockHomeJSONValue /// JSON 类型保持不变,数字使用 Decimal 避免先转换为 Double 丢失精度。 func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch value { case .object(let object): try container.encode(object.mapValues { DroneDockTaskJSONSnapshot(value: $0) }) case .array(let array): try container.encode(array.map { DroneDockTaskJSONSnapshot(value: $0) }) case .string(let text): try container.encode(text) case .number(let number): try container.encode(number) case .bool(let flag): try container.encode(flag) case .null: try container.encodeNil() } } }