import Foundation /// sessions 返回的一次真实场次摘要,持有读取详情所需的身份及已确认展示字段。 struct ScenicMaterialsRemoteSession: Equatable, Sendable { /// 空境场次身份,对应 scenic_media_id。 let id: Int /// 场次所属景区,用于拒绝跨景区素材。 let scenicID: Int /// 所属航线的稳定身份。 let routeID: String /// 后端提供的航线展示名称。 let routeName: String /// 场次开始拍摄时间,按页面业务时区解析。 let capturedAt: Date /// 列表返回的素材数量,详情加载后使用完整素材数组。 let materialCount: Int } /// 将 2026-10-30 实测场次和详情字段转换为页面模型,不读取网络或生成演示素材。 enum ScenicMaterialsRemoteMapper { /// 从分页 list 读取场次,验证当前景区、唯一身份及真实拍摄时间。 static func sessions(from response: ScenicMaterialsSessionsResponse, scenicID: Int, calendar: Calendar) throws -> [ScenicMaterialsRemoteSession] { guard scenicID > 0 else { throw invalid("景区身份无效") } let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .gregorian) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = calendar.timeZone formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" formatter.isLenient = false var seen = Set() return try response.list.map { fields in let id = try positiveInteger(fields["scenic_media_id"], field: "场次身份") let returnedScenicID = try positiveInteger(fields["scenic_id"], field: "景区身份") guard returnedScenicID == scenicID else { throw invalid("场次不属于当前景区") } guard seen.insert(id).inserted else { throw invalid("场次身份重复") } let routeID = try positiveInteger(fields["air_line_id"], field: "航线身份") let routeName = try routeName(fields) guard let timestamp = string(fields["log_stime"]), let date = formatter.date(from: timestamp), formatter.string(from: date) == timestamp else { throw invalid("场次拍摄时间无效") } let count = try nonnegativeInteger(fields["material_count"], field: "场次素材数量") return ScenicMaterialsRemoteSession(id: id, scenicID: returnedScenicID, routeID: String(routeID), routeName: routeName, capturedAt: date, materialCount: count) } } /// 航线筛选只使用服务端 filter_options,保留服务端排序和名称。 static func routes(from response: ScenicMaterialsSessionsResponse) throws -> [ScenicMaterialRoute] { var seen = Set() return try response.airLines.map { fields in let id = try positiveInteger(fields["air_line_id"], field: "航线身份") guard seen.insert(id).inserted else { throw invalid("航线身份重复") } return ScenicMaterialRoute(id: String(id), name: try routeName(fields)) } } /// 校验详情及素材归属,再生成可预览和下载的完整批次;缺地址的文件保持不可用。 static func group(session: ScenicMaterialsRemoteSession, detail: ScenicMaterialsSessionDetailResponse) throws -> ScenicMaterialGroup { guard case let .object(identity)? = detail.fields["session"], try positiveInteger(identity["scenic_media_id"], field: "详情场次身份") == session.id, try positiveInteger(identity["scenic_id"], field: "详情景区身份") == session.scenicID, String(try positiveInteger(identity["air_line_id"], field: "详情航线身份")) == session.routeID else { throw invalid("素材详情与请求的场次或景区不一致") } if let value = detail.fields["material_count"] { guard try nonnegativeInteger(value, field: "详情素材数量") == detail.materials.count else { throw invalid("场次详情的素材数量不完整") } } var seen = Set() let groupID = String(session.id) let clips = try detail.materials.map { fields in guard try positiveInteger(fields["scenic_media_id"], field: "素材场次身份") == session.id else { throw invalid("素材不属于当前场次") } let id = try positiveInteger(fields["id"], field: "素材身份") guard seen.insert(id).inserted else { throw invalid("素材身份重复") } let ordinal: Int if let value = string(fields["clip_no"]), let parsed = Int(value), parsed > 0 { ordinal = parsed } else { ordinal = try positiveInteger(fields["clip_no"], field: "片段序号") } let remoteURL = mediaURL(fields["oss_url"]) let coverURL = mediaURL(fields["cover_url"]) let fileSize = integer64(fields["size_bytes"]).flatMap { $0 >= 0 ? $0 : nil } ?? -1 let duration = integer64(fields["duration_seconds"]).flatMap { $0 >= 0 ? Int(exactly: $0) : nil } ?? -1 let isVideo = integer64(fields["file_type"]) == 2 let isAvailable = isVideo && fields["selectable"] == .bool(true) && fields["downloadable"] == .bool(true) && remoteURL != nil return ScenicMaterialClip(id: "scenic-media:\(session.id):\(id)", groupID: groupID, ordinal: ordinal, durationSeconds: duration, fileSizeBytes: fileSize, resolution: "分辨率未知", coverAssetName: "", isAvailable: isAvailable, remoteURL: remoteURL, coverURL: coverURL, fileLabel: string(fields["file_label"]), isRemote: true) } return ScenicMaterialGroup(id: groupID, routeID: session.routeID, capturedAt: session.capturedAt, clips: clips.sorted { $0.ordinal < $1.ordinal }) } /// 接口明确提供 route_label,空值时使用同一航线的原始名称。 private static func routeName(_ fields: [String: ScenicMaterialsJSONValue]) throws -> String { guard let name = string(fields["route_label"]) ?? string(fields["air_line_name"]) else { throw invalid("航线名称缺失") } return name } /// 只接受可表达的整数,拒绝小数截断及越界转换。 private static func integer64(_ value: ScenicMaterialsJSONValue?) -> Int64? { guard case let .number(number)? = value else { return nil } let integer = NSDecimalNumber(decimal: number).int64Value return number == Decimal(integer) ? integer : nil } /// 读取不允许为零的业务身份。 private static func positiveInteger(_ value: ScenicMaterialsJSONValue?, field: String) throws -> Int { guard let number = integer64(value), number > 0, let result = Int(exactly: number) else { throw invalid("\(field)无效") } return result } /// 数量允许为零,但必须是有效整数。 private static func nonnegativeInteger(_ value: ScenicMaterialsJSONValue?, field: String) throws -> Int { guard let number = integer64(value), number >= 0, let result = Int(exactly: number) else { throw invalid("\(field)无效") } return result } /// 空白文本作为缺失字段处理,不把其他 JSON 类型强制转成文本。 private static func string(_ value: ScenicMaterialsJSONValue?) -> String? { guard case let .string(text)? = value else { return nil } let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) return trimmed.isEmpty ? nil : trimmed } /// 远程媒体仅接受 HTTP(S),保留原始签名查询值供播放器和下载器使用。 private static func mediaURL(_ value: ScenicMaterialsJSONValue?) -> URL? { guard let text = string(value), let url = URL(string: text), let scheme = url.scheme?.lowercased(), ["https", "http"].contains(scheme), let host = url.host, !host.isEmpty else { return nil } return url } /// 统一映射失败为可重试的解析错误,不让错误字段变成演示数据或空库。 private static func invalid(_ reason: String) -> APIError { .decodeFailed("景区空境库数据异常:\(reason),请刷新重试") } }