feat: 接入景区空境库真实素材并统一交付入口
接通场次详情、分页、视频时长与大小,修复日期筛选越界并增加脱敏日志。统一订单与素材库交付方式弹窗,保留任务预选和上传批次,补充模拟器回归测试与接口记录。
This commit is contained in:
@@ -23,6 +23,7 @@ final class APIClient {
|
||||
private let encoder: JSONEncoder
|
||||
private let decoder: JSONDecoder
|
||||
private let notificationCenter: NotificationCenter
|
||||
private let debugLogSink: (String) -> Void
|
||||
private var authTokenProvider: (() -> String?)?
|
||||
|
||||
private let environment: APIEnvironment
|
||||
@@ -37,13 +38,15 @@ final class APIClient {
|
||||
decoder: JSONDecoder = JSONDecoder(),
|
||||
appVersion: String = AppClientInfo.appVersion(),
|
||||
osType: String = AppClientInfo.osType,
|
||||
notificationCenter: NotificationCenter = .default
|
||||
notificationCenter: NotificationCenter = .default,
|
||||
debugLogSink: @escaping (String) -> Void = { print($0) }
|
||||
) {
|
||||
self.environment = environment
|
||||
self.session = session
|
||||
self.encoder = encoder
|
||||
self.decoder = decoder
|
||||
self.notificationCenter = notificationCenter
|
||||
self.debugLogSink = debugLogSink
|
||||
self.appVersion = appVersion.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? "1.0.0"
|
||||
self.osType = osType.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? AppClientInfo.osType
|
||||
}
|
||||
@@ -69,26 +72,29 @@ final class APIClient {
|
||||
let request = try DeviceCommandDebugPolicy.prepare(
|
||||
makeURLRequest(apiRequest, tokenOverride: tokenOverride),
|
||||
isLocalSimulation: session is any LocalSimulationURLSession)
|
||||
logRequest(request, includeBody: apiRequest.logsPayload)
|
||||
logRequest(request, includeBody: apiRequest.logsPayload, category: apiRequest.redactedLogCategory)
|
||||
|
||||
let data: Data
|
||||
let response: URLResponse
|
||||
do {
|
||||
(data, response) = try await session.data(for: request)
|
||||
} catch is CancellationError {
|
||||
logCancelled(for: request, reason: "CancellationError")
|
||||
logCancelled(for: request, reason: "CancellationError", category: apiRequest.redactedLogCategory)
|
||||
throw CancellationError()
|
||||
} catch let error as URLError {
|
||||
if error.code == .cancelled {
|
||||
logCancelled(for: request, reason: "URLError.cancelled")
|
||||
logCancelled(for: request, reason: "URLError.cancelled", category: apiRequest.redactedLogCategory)
|
||||
throw CancellationError()
|
||||
}
|
||||
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
|
||||
throw APIError.networkFailed(networkErrorMessage(for: error))
|
||||
} catch {
|
||||
logFailure(for: request, error: error, category: apiRequest.redactedLogCategory)
|
||||
throw APIError.networkFailed(error.localizedDescription)
|
||||
}
|
||||
|
||||
logResponse(for: request, response: response, data: data, includeBody: apiRequest.logsPayload)
|
||||
logResponse(for: request, response: response, data: data, includeBody: apiRequest.logsPayload,
|
||||
category: apiRequest.redactedLogCategory)
|
||||
do {
|
||||
try validateHTTPResponse(response, data: data)
|
||||
return try decodeEnvelope(Response.self, from: data)
|
||||
@@ -374,8 +380,12 @@ final class APIClient {
|
||||
}
|
||||
|
||||
/// 在 Debug 环境打印请求信息(含 GET 查询参数与 POST 请求体,对齐 Android Ktor `LogLevel.BODY`)。
|
||||
private func logRequest(_ request: URLRequest, includeBody: Bool = true) {
|
||||
private func logRequest(_ request: URLRequest, includeBody: Bool = true, category: String? = nil) {
|
||||
#if DEBUG
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.request(request, category: category, includeBody: includeBody))
|
||||
return
|
||||
}
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
var lines = ["[API][Request] \(method) \(url)"]
|
||||
@@ -396,27 +406,47 @@ final class APIClient {
|
||||
lines.append("body:\n\(body)")
|
||||
}
|
||||
|
||||
print(lines.joined(separator: "\n"))
|
||||
debugLogSink(lines.joined(separator: "\n"))
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 在 Debug 环境打印响应状态和响应体。
|
||||
private func logResponse(for request: URLRequest, response: URLResponse, data: Data, includeBody: Bool = true) {
|
||||
private func logResponse(for request: URLRequest, response: URLResponse, data: Data,
|
||||
includeBody: Bool = true, category: String? = nil) {
|
||||
#if DEBUG
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.response(for: request, response: response, data: data,
|
||||
category: category, includeBody: includeBody))
|
||||
return
|
||||
}
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
let statusCode = (response as? HTTPURLResponse).map { String($0.statusCode) } ?? "unknown"
|
||||
let body = includeBody ? Self.debugResponseBody(from: data) : "<sensitive payload omitted>"
|
||||
print("[API][Response] \(method) \(url) status=\(statusCode)\n\(body)")
|
||||
debugLogSink("[API][Response] \(method) \(url) status=\(statusCode)\n\(body)")
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 在 Debug 环境打印被取消的请求信息。
|
||||
private func logCancelled(for request: URLRequest, reason: String) {
|
||||
private func logCancelled(for request: URLRequest, reason: String, category: String? = nil) {
|
||||
#if DEBUG
|
||||
if let category {
|
||||
debugLogSink(APIRedactedLog.event("Cancelled", for: request, category: category) + " reason=\(reason)")
|
||||
return
|
||||
}
|
||||
let method = request.httpMethod ?? "REQUEST"
|
||||
let url = request.url?.absoluteString ?? "<invalid url>"
|
||||
print("[API][Cancelled] \(method) \(url) reason=\(reason)")
|
||||
debugLogSink("[API][Cancelled] \(method) \(url) reason=\(reason)")
|
||||
#endif
|
||||
}
|
||||
|
||||
/// 记录已开启模块日志的传输失败,只输出错误域和错误码,避免错误描述夹带凭证。
|
||||
private func logFailure(for request: URLRequest, error: Error, category: String?) {
|
||||
#if DEBUG
|
||||
guard let category else { return }
|
||||
let error = error as NSError
|
||||
debugLogSink(APIRedactedLog.event("Failure", for: request, category: category)
|
||||
+ " error=\(error.domain)(\(error.code))")
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import Foundation
|
||||
|
||||
/// 按模块生成可读的调试日志;只处理输出副本,不修改网络请求和业务响应。
|
||||
nonisolated enum APIRedactedLog {
|
||||
private static let urlPattern = try? NSRegularExpression(pattern: #"https?://[^\s"<>]+"#, options: [.caseInsensitive])
|
||||
|
||||
/// 输出方法、地址、查询参数及可选 JSON 请求体,不输出鉴权 Header。
|
||||
static func request(_ request: URLRequest, category: String, includeBody: Bool) -> String {
|
||||
var lines = [event("Request", for: request, category: category)]
|
||||
if let url = request.url,
|
||||
let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems,
|
||||
!items.isEmpty {
|
||||
lines.append("params: " + items.map {
|
||||
"\($0.name)=\(isSensitive($0.name) ? "<redacted>" : redactURLs(in: $0.value ?? ""))"
|
||||
}.joined(separator: "&"))
|
||||
}
|
||||
if includeBody, let data = request.httpBody {
|
||||
lines.append("body:\n" + body(data))
|
||||
}
|
||||
return lines.joined(separator: "\n")
|
||||
}
|
||||
|
||||
/// 输出 HTTP 状态及格式化的脱敏 JSON,包括业务失败或非 2xx 响应。
|
||||
static func response(for request: URLRequest, response: URLResponse, data: Data,
|
||||
category: String, includeBody: Bool) -> String {
|
||||
let status = (response as? HTTPURLResponse).map { String($0.statusCode) } ?? "unknown"
|
||||
let payload = includeBody ? body(data) : "<sensitive payload omitted>"
|
||||
return event("Response", for: request, category: category) + " status=\(status)\n" + payload
|
||||
}
|
||||
|
||||
/// 生成请求、响应、失败和取消共用的模块标签与安全地址。
|
||||
static func event(_ event: String, for request: URLRequest, category: String) -> String {
|
||||
let url = request.url.map { redactedURL($0, keepsQuery: true) } ?? "<invalid url>"
|
||||
return "[API][\(category)][\(event)] \(request.httpMethod ?? "REQUEST") \(url)"
|
||||
}
|
||||
|
||||
/// 非 JSON 正文可能包含凭证或服务端调试页面,不把原始文本写入控制台。
|
||||
private static func body(_ data: Data) -> String {
|
||||
guard !data.isEmpty else { return "<empty body>" }
|
||||
guard let object = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]),
|
||||
let formatted = try? JSONSerialization.data(withJSONObject: redact(object),
|
||||
options: [.prettyPrinted, .sortedKeys, .fragmentsAllowed, .withoutEscapingSlashes]),
|
||||
let text = String(data: formatted, encoding: .utf8) else {
|
||||
return "<non-JSON body omitted: \(data.count) bytes>"
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
/// 递归处理嵌套对象与数组,保留普通字段、空值及 JSON 类型。
|
||||
private static func redact(_ value: Any) -> Any {
|
||||
if let object = value as? [String: Any] {
|
||||
return Dictionary(uniqueKeysWithValues: object.map { key, value in
|
||||
(key, isSensitive(key) ? "<redacted>" : redact(value))
|
||||
})
|
||||
}
|
||||
if let array = value as? [Any] { return array.map(redact) }
|
||||
if let text = value as? String { return redactURLs(in: text) }
|
||||
return value
|
||||
}
|
||||
|
||||
/// 兼容 snake_case、大小写及 OSS/S3 常用签名字段。
|
||||
private static func isSensitive(_ key: String) -> Bool {
|
||||
let normalized = key.lowercased().filter { $0.isLetter || $0.isNumber }
|
||||
return ["token", "authorization", "signature", "credential", "accesskey", "secret", "password", "cookie"]
|
||||
.contains { normalized.contains($0) }
|
||||
}
|
||||
|
||||
/// JSON 字段或消息中的 URL 只保留资源路径,不记录有效期、签名及其他查询值。
|
||||
private static func redactURLs(in text: String) -> String {
|
||||
guard let pattern = urlPattern else { return text }
|
||||
var result = text
|
||||
for match in pattern.matches(in: text, range: NSRange(text.startIndex..., in: text)).reversed() {
|
||||
guard let range = Range(match.range, in: result) else { continue }
|
||||
let replacement = URL(string: String(result[range])).map { redactedURL($0, keepsQuery: false) }
|
||||
?? "<redacted URL>"
|
||||
result.replaceSubrange(range, with: replacement)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// 请求地址保留业务查询值;正文中的资源地址删除完整查询,兼容未来签名参数。
|
||||
private static func redactedURL(_ url: URL, keepsQuery: Bool) -> String {
|
||||
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return "<redacted URL>" }
|
||||
components.user = nil
|
||||
components.password = nil
|
||||
components.fragment = nil
|
||||
if keepsQuery {
|
||||
components.queryItems = components.queryItems?.map {
|
||||
URLQueryItem(name: $0.name, value: isSensitive($0.name) ? "<redacted>" : $0.value.map(redactURLs))
|
||||
}
|
||||
} else {
|
||||
components.query = nil
|
||||
}
|
||||
return components.string ?? "<redacted URL>"
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,8 @@ nonisolated struct APIRequest<Response: Decodable> {
|
||||
var body: AnyEncodable?
|
||||
/// 敏感请求关闭正文日志,避免验证码和注销资产进入调试日志。
|
||||
var logsPayload: Bool
|
||||
/// 为指定模块输出带标签的脱敏日志;隐藏凭证字段和响应中媒体 URL 的查询参数。
|
||||
var redactedLogCategory: String?
|
||||
|
||||
/// 创建一个 API 请求,并把可编码请求体擦除为统一的 AnyEncodable。
|
||||
init<Body: Encodable>(
|
||||
@@ -31,7 +33,8 @@ nonisolated struct APIRequest<Response: Decodable> {
|
||||
queryItems: [URLQueryItem] = [],
|
||||
headers: [String: String] = [:],
|
||||
body: Body? = Optional<EmptyPayload>.none,
|
||||
logsPayload: Bool = true
|
||||
logsPayload: Bool = true,
|
||||
redactedLogCategory: String? = nil
|
||||
) {
|
||||
self.method = method
|
||||
self.path = path
|
||||
@@ -39,6 +42,7 @@ nonisolated struct APIRequest<Response: Decodable> {
|
||||
self.headers = headers
|
||||
self.body = body.map(AnyEncodable.init)
|
||||
self.logsPayload = logsPayload
|
||||
self.redactedLogCategory = redactedLogCategory
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,8 @@ final class ScenicMaterialsAPI: ScenicMaterialsServing {
|
||||
/// 验证请求范围及响应页码,避免拼入其他页或其他筛选的数据。
|
||||
func sessions(query: ScenicMaterialsQuery) async throws -> ScenicMaterialsSessionsResponse {
|
||||
let response: ScenicMaterialsSessionsResponse = try await client.send(APIRequest(
|
||||
method: .get, path: "/api/app/scenic-media/sessions", queryItems: try query.queryItems(), logsPayload: false
|
||||
method: .get, path: "/api/app/scenic-media/sessions", queryItems: try query.queryItems(),
|
||||
redactedLogCategory: "景区空境库"
|
||||
))
|
||||
guard response.page == query.page, response.pageSize == query.pageSize,
|
||||
response.retentionDays == query.retentionDays,
|
||||
@@ -37,7 +38,8 @@ final class ScenicMaterialsAPI: ScenicMaterialsServing {
|
||||
guard scenicMediaID > 0 else { throw APIError.networkFailed("空境场次无效,请刷新重试") }
|
||||
return try await client.send(APIRequest(
|
||||
method: .get, path: "/api/app/scenic-media/session-detail",
|
||||
queryItems: [URLQueryItem(name: "scenic_media_id", value: String(scenicMediaID))], logsPayload: false
|
||||
queryItems: [URLQueryItem(name: "scenic_media_id", value: String(scenicMediaID))],
|
||||
redactedLogCategory: "景区空境库"
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,11 +62,11 @@ struct ScenicMaterialClip: Hashable, Sendable {
|
||||
let groupID: String
|
||||
/// 组内从 1 开始的片段序号。
|
||||
let ordinal: Int
|
||||
/// 原片段展示时长;本地播放器使用独立演示视频。
|
||||
/// 原片段时长,单位为秒;-1 表示接口没有有效数值。
|
||||
let durationSeconds: Int
|
||||
/// 原片段展示大小,单位为字节。
|
||||
let fileSizeBytes: Int64
|
||||
/// 原片段分辨率展示值。
|
||||
/// 保留原片段分辨率元数据,页面不展示。
|
||||
let resolution: String
|
||||
/// 本地演示封面资源名。
|
||||
let coverAssetName: String
|
||||
@@ -99,11 +99,14 @@ struct ScenicMaterialClip: Hashable, Sendable {
|
||||
self.isRemote = isRemote
|
||||
}
|
||||
|
||||
/// 用于封面与预览信息的分秒时长。
|
||||
/// 用于封面与预览信息的时长;超过一小时显示时分秒,保留后端秒数语义。
|
||||
var durationText: String {
|
||||
guard durationSeconds >= 0 else { return "时长未知" }
|
||||
let value = max(durationSeconds, 0)
|
||||
return String(format: "%02d:%02d", value / 60, value % 60)
|
||||
if value >= 3_600 {
|
||||
return String(format: "%02lld:%02lld:%02lld", Int64(value / 3_600), Int64(value / 60 % 60), Int64(value % 60))
|
||||
}
|
||||
return String(format: "%02lld:%02lld", Int64(value / 60), Int64(value % 60))
|
||||
}
|
||||
|
||||
/// 使用十进制 MB 展示片段大小,避免将原文件与本地示例文件混淆。
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
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<Int>()
|
||||
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<Int>()
|
||||
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<Int>()
|
||||
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),请刷新重试")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// 独立景区空镜库的筛选、选择和前台下载演示逻辑;不依赖 UIKit 或机巢业务。
|
||||
/// 独立景区空境库的正式分页、筛选、选择与下载状态,同时支持本地演示;不依赖 UIKit 或机巢业务。
|
||||
final class ScenicMaterialsViewModel {
|
||||
/// 正式模式使用网络素材与真实相册保存,预览模式使用本地演示。
|
||||
let isRemote: Bool
|
||||
@@ -8,15 +8,15 @@ final class ScenicMaterialsViewModel {
|
||||
let context: ScenicMaterialContext
|
||||
/// 用于筛选的日历及其时区。
|
||||
let calendar: Calendar
|
||||
/// 本地演示保留天数,正式对接后由服务端配置决定。
|
||||
/// 默认保留天数,正式模式采用服务端回显的窗口。
|
||||
private(set) var retentionDays = 90
|
||||
/// 保留期首日零点,包含今天一共 90 个日历日。
|
||||
/// 日期筛选首日;正式模式包含后端返回的第 90 天,演示模式包含今天共 90 天。
|
||||
private(set) var minimumDate: Date
|
||||
/// 可选的最后一天零点,不允许选择未来日期。
|
||||
let maximumDate: Date
|
||||
/// 当前景区的独立空镜航线,含暂无片段的航线。
|
||||
private(set) var routes: [ScenicMaterialRoute]
|
||||
/// 当前演示数据集的所有批次,筛选不会修改它们。
|
||||
/// 当前已加载的批次;正式模式按服务端分页追加。
|
||||
private(set) var allGroups: [ScenicMaterialGroup]
|
||||
/// 选择的航线标识,nil 代表全部航线。
|
||||
private(set) var selectedRouteID: String?
|
||||
@@ -39,26 +39,40 @@ final class ScenicMaterialsViewModel {
|
||||
/// 当前批次的逐项演示进度。
|
||||
private(set) var progressByID: [String: Double] = [:]
|
||||
|
||||
/// 已确认接口的加载状态。
|
||||
/// 正在刷新第一页及其片段详情。
|
||||
private(set) var isLoading = false
|
||||
/// 请求失败或素材字段尚无法映射时的可重试提示。
|
||||
/// 正在读取下一页及其片段详情。
|
||||
private(set) var isLoadingMore = false
|
||||
/// 下一页加载失败时保留已展示内容,由用户重试。
|
||||
private(set) var loadMoreError: String?
|
||||
/// 当前筛选在后端的场次总数。
|
||||
private(set) var remoteTotalCount = 0
|
||||
/// 已加载的去重场次数,不将同页重复项计为新内容。
|
||||
var loadedRemoteSessionCount: Int { isRemote ? allGroups.count : 0 }
|
||||
/// 首次成功加载后,是否仍有未读取的场次。
|
||||
var hasMoreRemoteSessions: Bool {
|
||||
isRemote && loadedRemotePage > 0 && loadedRemoteSessionCount < remoteTotalCount
|
||||
}
|
||||
/// 第一页请求、详情或字段校验失败时的可重试提示。
|
||||
private(set) var loadError: String?
|
||||
/// 保留完整响应,非空且未确认字段时不能被当成空库。
|
||||
/// 最近收到的完整场次响应,解析失败时仍供诊断,不代表已提交到页面。
|
||||
private(set) var remoteSessions: ScenicMaterialsSessionsResponse?
|
||||
/// 素材保留说明优先使用后端返回的文案。
|
||||
private(set) var retentionTips = "素材保留 90 天,请及时下载"
|
||||
private var loadID: UUID?
|
||||
private var loadedRemotePage = 0
|
||||
private var loadedRemoteQuery: ScenicMaterialsQuery?
|
||||
|
||||
private let initialGroups: [ScenicMaterialGroup]
|
||||
|
||||
/// 创建演示库;可注入日历、日期和数据,测试不依赖时间、网络或登录单例。
|
||||
/// 创建正式或演示库;可注入日历、日期和数据,测试不依赖时间、网络或登录单例。
|
||||
init(context: ScenicMaterialContext = .demo, now: Date = Date(), calendar: Calendar = .current,
|
||||
routes: [ScenicMaterialRoute]? = nil, groups: [ScenicMaterialGroup]? = nil, isRemote: Bool = false) {
|
||||
self.isRemote = isRemote
|
||||
self.context = context
|
||||
self.calendar = calendar
|
||||
maximumDate = calendar.startOfDay(for: now)
|
||||
minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate
|
||||
minimumDate = calendar.date(byAdding: .day, value: isRemote ? -retentionDays : -(retentionDays - 1), to: maximumDate) ?? maximumDate
|
||||
let demoRoutes = isRemote ? [] : Self.makeRoutes(context: context)
|
||||
self.routes = routes ?? demoRoutes
|
||||
let data = groups ?? (isRemote ? [] : Self.makeGroups(context: context, routes: demoRoutes, today: maximumDate, calendar: calendar))
|
||||
@@ -66,13 +80,14 @@ final class ScenicMaterialsViewModel {
|
||||
allGroups = data
|
||||
}
|
||||
|
||||
/// 按航线分区、同航线时间倒序的有效批次;保留期外记录不会进入显示或选择范围。
|
||||
/// 按航线及拍摄时间排序;正式范围遵守服务端查询,演示数据再按本地保留期筛选。
|
||||
var filteredGroups: [ScenicMaterialGroup] {
|
||||
let routeOrder = Dictionary(routes.enumerated().map { ($0.element.id, $0.offset) }, uniquingKeysWith: { first, _ in first })
|
||||
return allGroups.filter { group in
|
||||
guard routeOrder[group.routeID] != nil else { return false }
|
||||
let day = calendar.startOfDay(for: group.capturedAt)
|
||||
guard day >= minimumDate, day <= maximumDate else { return false }
|
||||
// 正式保留范围由接口执行,避免再次按本地日界限删掉后端已返回的边界场次。
|
||||
guard isRemote || (day >= minimumDate && day <= maximumDate) else { return false }
|
||||
if let selectedRouteID, group.routeID != selectedRouteID { return false }
|
||||
if let dateRange, day < dateRange.start || day > dateRange.end { return false }
|
||||
return true
|
||||
@@ -90,7 +105,7 @@ final class ScenicMaterialsViewModel {
|
||||
/// 任何批次尚未清理时锁定选择与筛选,避免改变正在展示的批次范围。
|
||||
var isSelectionLocked: Bool { batchID != nil }
|
||||
/// 尚未开始传输且有可选片段时可以下载。
|
||||
var canStartDownload: Bool { !isSelectionLocked && !selectedIDs.isEmpty }
|
||||
var canStartDownload: Bool { !isSelectionLocked && !isLoading && !isLoadingMore && !selectedIDs.isEmpty }
|
||||
/// 当前选择数量。
|
||||
var selectedCount: Int { selectedIDs.count }
|
||||
/// 当前批次总项数。
|
||||
@@ -121,7 +136,7 @@ final class ScenicMaterialsViewModel {
|
||||
var hasAnyMaterials: Bool {
|
||||
allGroups.contains { group in
|
||||
let day = calendar.startOfDay(for: group.capturedAt)
|
||||
return !group.clips.isEmpty && day >= minimumDate && day <= maximumDate
|
||||
return !group.clips.isEmpty && (isRemote || (day >= minimumDate && day <= maximumDate))
|
||||
&& routes.contains(where: { $0.id == group.routeID })
|
||||
}
|
||||
}
|
||||
@@ -138,43 +153,143 @@ final class ScenicMaterialsViewModel {
|
||||
return hasAnyMaterials || (isRemote && (selectedRouteID != nil || dateRange != nil)) ? "试试其他航线或时间范围" : "景区空镜上传后,将显示在这里"
|
||||
}
|
||||
|
||||
/// 读取当前景区的真实列表;在有样本确认子项合同前保留原始响应并明确报错。
|
||||
/// 刷新当前筛选第一页,并读取该页完整片段;详情失败时整页可重试,不混入演示数据。
|
||||
func loadRemoteSessions(api: any ScenicMaterialsServing) async {
|
||||
guard isRemote, !isSelectionLocked else { return }
|
||||
resetRemotePageState()
|
||||
let requestID = UUID()
|
||||
loadID = requestID
|
||||
defer { if loadID == requestID { isLoading = false } }
|
||||
isLoading = true
|
||||
loadError = nil
|
||||
let query = ScenicMaterialsQuery(scenicID: Int(context.scenicID) ?? 0,
|
||||
airLineID: selectedRouteID.flatMap(Int.init),
|
||||
dateFrom: dateRange.map { formatDate($0.start, format: "yyyy-MM-dd") },
|
||||
dateTo: dateRange.map { formatDate($0.end, format: "yyyy-MM-dd") }, retentionDays: retentionDays)
|
||||
let query = remoteQuery(page: 1)
|
||||
do {
|
||||
let response = try await api.sessions(query: query)
|
||||
guard loadID == requestID, !Task.isCancelled else { return }
|
||||
remoteSessions = response
|
||||
retentionDays = response.retentionDays
|
||||
retentionTips = response.retentionTips
|
||||
minimumDate = calendar.date(byAdding: .day, value: -(retentionDays - 1), to: maximumDate) ?? maximumDate
|
||||
allGroups = []
|
||||
routes = []
|
||||
selectedIDs.removeAll()
|
||||
if response.total > 0 || !response.list.isEmpty || !response.groups.isEmpty || !response.airLines.isEmpty {
|
||||
// 当前文档没有非空场次/航线的字段合同,不使用猜测的 ID 下载或错配素材。
|
||||
loadError = "暂时无法显示素材,请稍后重试"
|
||||
let sessions = try ScenicMaterialsRemoteMapper.sessions(from: response, scenicID: query.scenicID, calendar: calendar)
|
||||
let mappedRoutes = try ScenicMaterialsRemoteMapper.routes(from: response)
|
||||
if response.total > 0 && sessions.isEmpty {
|
||||
throw APIError.decodeFailed("场次总数与列表不一致,请刷新重试")
|
||||
}
|
||||
let groups = try await Self.loadGroups(sessions: sessions, api: api)
|
||||
guard loadID == requestID, !Task.isCancelled, remoteQuery(page: 1) == query else { return }
|
||||
allGroups = groups
|
||||
routes = Self.mergedRoutes(mappedRoutes, sessions: sessions)
|
||||
applyRemoteMetadata(response)
|
||||
loadedRemotePage = response.page
|
||||
loadedRemoteQuery = query
|
||||
} catch is CancellationError {
|
||||
} catch {
|
||||
guard loadID == requestID else { return }
|
||||
guard loadID == requestID, !Task.isCancelled else { return }
|
||||
loadError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 使用已成功加载的查询追加下一页,失败不清空已展示页面或选择状态。
|
||||
func loadMoreRemoteSessions(api: any ScenicMaterialsServing) async {
|
||||
guard isRemote, !isSelectionLocked, !isLoading, !isLoadingMore, hasMoreRemoteSessions,
|
||||
loadedRemoteQuery == remoteQuery(page: 1) else { return }
|
||||
let requestID = UUID()
|
||||
loadID = requestID
|
||||
isLoadingMore = true
|
||||
loadMoreError = nil
|
||||
let query = remoteQuery(page: loadedRemotePage + 1)
|
||||
defer { if loadID == requestID { isLoadingMore = false } }
|
||||
do {
|
||||
let response = try await api.sessions(query: query)
|
||||
guard loadID == requestID, !Task.isCancelled else { return }
|
||||
remoteSessions = response
|
||||
let sessions = try ScenicMaterialsRemoteMapper.sessions(from: response, scenicID: query.scenicID, calendar: calendar)
|
||||
let mappedRoutes = try ScenicMaterialsRemoteMapper.routes(from: response)
|
||||
let existingIDs = Set(allGroups.map(\.id))
|
||||
let newSessions = sessions.filter { !existingIDs.contains(String($0.id)) }
|
||||
guard !newSessions.isEmpty || response.total <= loadedRemoteSessionCount else {
|
||||
throw APIError.decodeFailed("后续场次为空或重复,请刷新重试")
|
||||
}
|
||||
let groups = try await Self.loadGroups(sessions: newSessions, api: api)
|
||||
guard loadID == requestID, !Task.isCancelled, loadedRemoteQuery == remoteQuery(page: 1) else { return }
|
||||
allGroups.append(contentsOf: groups)
|
||||
routes = Self.mergedRoutes(routes + mappedRoutes, sessions: sessions)
|
||||
applyRemoteMetadata(response)
|
||||
loadedRemotePage = response.page
|
||||
} catch is CancellationError {
|
||||
} catch {
|
||||
guard loadID == requestID, !Task.isCancelled else { return }
|
||||
loadMoreError = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 同一时刻最多请求四个场次详情,返回顺序始终与列表一致。
|
||||
private static func loadGroups(sessions: [ScenicMaterialsRemoteSession], api: any ScenicMaterialsServing) async throws -> [ScenicMaterialGroup] {
|
||||
try await withThrowingTaskGroup(of: (Int, ScenicMaterialGroup).self) { tasks in
|
||||
var nextIndex = 0
|
||||
var groups: [Int: ScenicMaterialGroup] = [:]
|
||||
func enqueue(_ index: Int) {
|
||||
let session = sessions[index]
|
||||
tasks.addTask {
|
||||
try Task.checkCancellation()
|
||||
let detail = try await api.sessionDetail(scenicMediaID: session.id)
|
||||
try Task.checkCancellation()
|
||||
return (index, try ScenicMaterialsRemoteMapper.group(session: session, detail: detail))
|
||||
}
|
||||
}
|
||||
while nextIndex < min(4, sessions.count) {
|
||||
enqueue(nextIndex)
|
||||
nextIndex += 1
|
||||
}
|
||||
while let (index, group) = try await tasks.next() {
|
||||
groups[index] = group
|
||||
if nextIndex < sessions.count {
|
||||
enqueue(nextIndex)
|
||||
nextIndex += 1
|
||||
}
|
||||
}
|
||||
return (0..<sessions.count).compactMap { groups[$0] }
|
||||
}
|
||||
}
|
||||
|
||||
/// 航线选项优先使用独立筛选集合,列表中的真实航线可补足集合。
|
||||
private static func mergedRoutes(_ routes: [ScenicMaterialRoute], sessions: [ScenicMaterialsRemoteSession]) -> [ScenicMaterialRoute] {
|
||||
var seen = Set<String>()
|
||||
return (routes + sessions.map { ScenicMaterialRoute(id: $0.routeID, name: $0.routeName) })
|
||||
.filter { seen.insert($0.id).inserted }
|
||||
}
|
||||
|
||||
/// 保持页码之外的查询范围一致,翻页时不丢失航线和日期条件。
|
||||
private func remoteQuery(page: Int) -> ScenicMaterialsQuery {
|
||||
ScenicMaterialsQuery(scenicID: Int(context.scenicID) ?? 0, page: page,
|
||||
airLineID: selectedRouteID.flatMap(Int.init),
|
||||
dateFrom: dateRange.map { formatDate($0.start, format: "yyyy-MM-dd") },
|
||||
dateTo: dateRange.map { formatDate($0.end, format: "yyyy-MM-dd") }, retentionDays: retentionDays)
|
||||
}
|
||||
|
||||
/// 正式日期下界包含后端已实测返回的第 90 天,不改变演示日历窗口。
|
||||
private func applyRemoteMetadata(_ response: ScenicMaterialsSessionsResponse) {
|
||||
retentionDays = response.retentionDays
|
||||
retentionTips = response.retentionTips
|
||||
remoteTotalCount = response.total
|
||||
minimumDate = calendar.date(byAdding: .day, value: -retentionDays, to: maximumDate) ?? maximumDate
|
||||
}
|
||||
|
||||
/// 刷新或筛选更换后作废旧请求、旧页码及选择,保留航线选项供筛选使用。
|
||||
private func resetRemotePageState() {
|
||||
cancelRemoteLoad()
|
||||
loadedRemotePage = 0
|
||||
loadedRemoteQuery = nil
|
||||
remoteTotalCount = 0
|
||||
remoteSessions = nil
|
||||
loadError = nil
|
||||
loadMoreError = nil
|
||||
allGroups.removeAll()
|
||||
selectedIDs.removeAll()
|
||||
expandedGroupIDs.removeAll()
|
||||
}
|
||||
|
||||
/// 离页或身份变化后作废尚未返回的列表请求。
|
||||
func cancelRemoteLoad() {
|
||||
loadID = nil
|
||||
isLoading = false
|
||||
isLoadingMore = false
|
||||
}
|
||||
|
||||
/// 查找稳定航线,不依赖名称。
|
||||
@@ -197,6 +312,7 @@ final class ScenicMaterialsViewModel {
|
||||
func setRoute(id: String?) -> Bool {
|
||||
guard !isSelectionLocked, id == nil || routes.contains(where: { $0.id == id }) else { return false }
|
||||
selectedRouteID = id
|
||||
if isRemote { resetRemotePageState() }
|
||||
pruneSelection()
|
||||
return true
|
||||
}
|
||||
@@ -207,6 +323,7 @@ final class ScenicMaterialsViewModel {
|
||||
guard !isSelectionLocked else { return false }
|
||||
if start == nil && end == nil {
|
||||
dateRange = nil
|
||||
if isRemote { resetRemotePageState() }
|
||||
pruneSelection()
|
||||
return true
|
||||
}
|
||||
@@ -215,6 +332,7 @@ final class ScenicMaterialsViewModel {
|
||||
let last = calendar.startOfDay(for: end)
|
||||
guard first >= minimumDate, last <= maximumDate, first <= last else { return false }
|
||||
dateRange = ScenicMaterialDateRange(start: first, end: last)
|
||||
if isRemote { resetRemotePageState() }
|
||||
pruneSelection()
|
||||
return true
|
||||
}
|
||||
@@ -224,6 +342,7 @@ final class ScenicMaterialsViewModel {
|
||||
guard !isSelectionLocked else { return }
|
||||
selectedRouteID = nil
|
||||
dateRange = nil
|
||||
if isRemote { resetRemotePageState() }
|
||||
pruneSelection()
|
||||
}
|
||||
|
||||
@@ -272,7 +391,7 @@ final class ScenicMaterialsViewModel {
|
||||
/// 冻结当前可选范围并开启一轮下载演示,返回是否成功建立批次。
|
||||
@discardableResult
|
||||
func startDownload() -> Bool {
|
||||
guard !isSelectionLocked else { return false }
|
||||
guard canStartDownload else { return false }
|
||||
let items = filteredClips.filter { selectedIDs.contains($0.id) && $0.isAvailable && (!isRemote || $0.remoteURL != nil) && !completedIDs.contains($0.id) }
|
||||
guard !items.isEmpty else { return false }
|
||||
batchItemIDs = items.map(\.id)
|
||||
|
||||
@@ -39,10 +39,10 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
private var uploadItemsByID: [String: DroneDeliveryUploadItem] = [:]
|
||||
private var didRequestFinish = false
|
||||
|
||||
/// 重新进入有未完成批次时直接恢复队列展示,仍需手动继续上传。
|
||||
/// 每次从外部进入均先选择交付方式,已有批次在选择云端后恢复。
|
||||
init(viewModel: DroneDeliveryViewModel) {
|
||||
self.viewModel = viewModel
|
||||
phase = viewModel.batch == nil ? .method : .queue
|
||||
phase = .method
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
modalPresentationStyle = .pageSheet
|
||||
}
|
||||
@@ -320,7 +320,7 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
private func primaryTapped() {
|
||||
switch phase {
|
||||
case .method: break
|
||||
case .nearby: showPhase(.point)
|
||||
case .nearby: openCloudFlow()
|
||||
case .point: if viewModel.selectedPoint != nil { showPhase(.picker) }
|
||||
case .picker:
|
||||
if viewModel.startUpload() { showPhase(.queue); startDemoUpload() }
|
||||
@@ -338,6 +338,11 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
}
|
||||
}
|
||||
|
||||
/// 选择云端仅恢复原队列或进入选点,不清除批次,也不自动继续上传。
|
||||
private func openCloudFlow() {
|
||||
showPhase(viewModel.batch == nil ? .point : .queue)
|
||||
}
|
||||
|
||||
private func secondaryTapped() {
|
||||
switch phase {
|
||||
case .method: break
|
||||
@@ -353,6 +358,7 @@ final class DroneDeliveryUploadViewController: BaseViewController {
|
||||
|
||||
private func pauseForLeaving() {
|
||||
uploadDriver.stop()
|
||||
guard phase == .queue else { return }
|
||||
viewModel.pauseUpload(reason: .leavingPage)
|
||||
}
|
||||
|
||||
@@ -397,7 +403,7 @@ extension DroneDeliveryUploadViewController: UICollectionViewDelegate {
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||
switch item {
|
||||
case .nearbyMethod: showPhase(.nearby)
|
||||
case .cloudMethod: showPhase(.point)
|
||||
case .cloudMethod: openCloudFlow()
|
||||
case .point(let id): viewModel.selectPoint(id: id); applySnapshot(animated: true)
|
||||
case .upload(let id):
|
||||
if let item = uploadItemsByID[id] { delegate?.deliveryUploadViewController(self, didRequestPreview: item.video) }
|
||||
|
||||
@@ -3,8 +3,9 @@ import UIKit
|
||||
/// 订单列表与素材库共用的真实成片交付页面工厂。
|
||||
@MainActor
|
||||
enum DroneDockDeliveryEntry {
|
||||
/// 订单列表先展示方式选择,云端页面在同一弹窗内继续,关闭后再通知列表刷新。
|
||||
/// 所有交付入口先选择方式;素材入口保留任务预选,云端页面在同一弹窗内继续。
|
||||
static func makeMethodSheet(order: DroneDockHomeOrder, context: DroneDockHomeContext,
|
||||
taskID: Int? = nil,
|
||||
controllerFactory: @escaping (DroneDockHomeOrder, DroneDockHomeContext, Int?) -> UIViewController,
|
||||
onDidCloseCloud: @escaping () -> Void = {}) -> UINavigationController {
|
||||
let methods = DroneDockDeliveryMethodViewController(customerTitle: order.touristTitle)
|
||||
@@ -14,7 +15,7 @@ enum DroneDockDeliveryEntry {
|
||||
methods.onClose = { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
methods.onCloudUpload = { [weak navigation, weak methods] in
|
||||
guard let navigation, let methods, navigation.topViewController === methods else { return }
|
||||
let cloud = controllerFactory(order, context, nil)
|
||||
let cloud = controllerFactory(order, context, taskID)
|
||||
if let cloud = cloud as? DroneDockDeliveryViewController {
|
||||
cloud.configureSheetPresentation { [weak navigation] in navigation?.dismiss(animated: true) }
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ final class DroneDockDeliveryViewController: BaseViewController {
|
||||
ownedVideoURLs.forEach(DroneDockDeliveryVideoLoader.discard)
|
||||
}
|
||||
|
||||
/// 订单列表以弹窗展示时复用上传流程,并将关闭动作纳入处理中退出确认。
|
||||
/// 交付入口以弹窗展示时复用上传流程,并将关闭动作纳入处理中退出确认。
|
||||
func configureSheetPresentation(onClose: @escaping () -> Void) {
|
||||
onCloseSheet = onClose
|
||||
}
|
||||
|
||||
@@ -301,10 +301,17 @@ final class DroneDockMaterialsViewController: BaseViewController {
|
||||
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)
|
||||
guard operation == nil, presentedViewController == nil,
|
||||
let order = viewModel.detail?.order, order.canUploadFilm == true, task(taskID) != nil else { return }
|
||||
let sheet = DroneDockDeliveryEntry.makeMethodSheet(order: order, context: viewModel.context,
|
||||
taskID: taskID, controllerFactory: deliveryControllerFactory) { [weak self] in
|
||||
guard let self else { return }
|
||||
self.refreshAfterDelivery = true
|
||||
guard self.viewIfLoaded?.window != nil else { return }
|
||||
self.refreshAfterDelivery = false
|
||||
self.load(.refresh)
|
||||
}
|
||||
present(sheet, animated: true)
|
||||
}
|
||||
|
||||
private func downloadTapped() {
|
||||
|
||||
@@ -382,8 +382,8 @@ extension DroneDockWorkbenchViewController: DroneMaterialsViewControllerDelegate
|
||||
controller.present(preview, animated: true)
|
||||
}
|
||||
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord) {
|
||||
openDelivery(orderID: controller.viewModel.orderID, pointID: record.pointID, from: controller)
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord?) {
|
||||
openDelivery(orderID: controller.viewModel.orderID, pointID: record?.pointID, from: controller)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import UIKit
|
||||
protocol DroneMaterialsViewControllerDelegate: AnyObject {
|
||||
/// 预览单项素材,保持素材库现有选择与下载批次。
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestPreview material: DroneMaterial)
|
||||
/// 请求交付成片,并由当前拍摄记录预选点位。
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord)
|
||||
/// 请求先选择交付方式;指定拍摄记录时保留点位预选,整批入口不猜测目标点位。
|
||||
func materialsViewController(_ controller: DroneMaterialsViewController, didRequestDelivery record: DroneMaterialRecord?)
|
||||
}
|
||||
|
||||
/// 订单素材库:按拍摄记录分组,支持点位筛选、独立预览选择与前台演示下载。
|
||||
@@ -453,22 +453,11 @@ final class DroneMaterialsViewController: BaseViewController {
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
/// 完成底栏的交付入口先明确拍摄记录,不根据下载批次猜测目标点位。
|
||||
/// 完成底栏也先选交付方式;多记录批次在选择云端后再由用户选点位。
|
||||
private func chooseCompletedDelivery() {
|
||||
guard delegate != nil, !viewModel.sections.isEmpty else { return }
|
||||
if viewModel.sections.count == 1, let record = viewModel.sections.first {
|
||||
delegate?.materialsViewController(self, didRequestDelivery: record)
|
||||
return
|
||||
}
|
||||
let sheet = UIAlertController(title: "选择拍摄记录", message: "选择需要交付成片的拍摄记录", preferredStyle: .actionSheet)
|
||||
for record in viewModel.sections {
|
||||
sheet.addAction(UIAlertAction(title: "\(record.pointName) · 记录\(record.sequenceNumber)", style: .default) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.delegate?.materialsViewController(self, didRequestDelivery: record)
|
||||
})
|
||||
}
|
||||
sheet.addAction(UIAlertAction(title: "取消", style: .cancel))
|
||||
present(sheet, animated: true)
|
||||
let record = viewModel.sections.count == 1 ? viewModel.sections.first : nil
|
||||
delegate?.materialsViewController(self, didRequestDelivery: record)
|
||||
}
|
||||
|
||||
private func updateInteractivePopGesture() {
|
||||
|
||||
@@ -77,7 +77,7 @@ final class ScenicMaterialClipCell: UICollectionViewCell {
|
||||
statusLabel.isHidden = true
|
||||
}
|
||||
|
||||
/// 显示片段及本机演示传输状态;首段大图额外显示分辨率和体积。
|
||||
/// 显示片段及本机演示传输状态;首段大图展示时长和文件大小。
|
||||
func configure(clip: ScenicMaterialClip, selected: Bool, isSelectionEnabled: Bool,
|
||||
statusText: String? = nil, progress: Double? = nil, isHero: Bool = false) {
|
||||
cover.kf.cancelDownloadTask()
|
||||
@@ -85,7 +85,7 @@ final class ScenicMaterialClipCell: UICollectionViewCell {
|
||||
cover.kf.setImage(with: clip.coverURL, placeholder: UIImage(systemName: "photo"))
|
||||
} else { cover.image = UIImage(named: clip.coverAssetName) }
|
||||
ordinalLabel.text = clip.fileLabel ?? String(format: "片段 %02d", clip.ordinal)
|
||||
metadataLabel.text = isHero ? "\(clip.durationText) · \(clip.resolution) · \(clip.sizeText)" : clip.durationText
|
||||
metadataLabel.text = isHero ? "\(clip.durationText) · \(clip.sizeText)" : clip.durationText
|
||||
metadataLabel.font = .monospacedDigitSystemFont(ofSize: isHero ? 11 : 10, weight: .regular)
|
||||
selectionButton.setImage(UIImage(systemName: selected ? "checkmark.circle.fill" : "circle",
|
||||
withConfiguration: UIImage.SymbolConfiguration(pointSize: 22, weight: .regular)), for: .normal)
|
||||
|
||||
@@ -123,6 +123,8 @@ final class ScenicMaterialDateFilterViewController: UIViewController, UIPickerVi
|
||||
private var endDate: Date
|
||||
private var usesAllDates: Bool
|
||||
private var endpoint: Endpoint = .start
|
||||
// 日列不能依赖 UIPickerView 正在切换的月份选择,UIKit 可能仍请求上一个月的行。
|
||||
private var displayedMonthIndex: Int
|
||||
private let allButton = UIButton(type: .system)
|
||||
private let startButton = UIButton(type: .custom)
|
||||
private let endButton = UIButton(type: .custom)
|
||||
@@ -137,6 +139,7 @@ final class ScenicMaterialDateFilterViewController: UIViewController, UIPickerVi
|
||||
let clampedEnd = options.clamped(end ?? maximumDate)
|
||||
self.startDate = min(clampedStart, clampedEnd)
|
||||
self.endDate = max(clampedStart, clampedEnd)
|
||||
displayedMonthIndex = options.monthIndex(for: min(clampedStart, clampedEnd))
|
||||
// 打开面板先编辑日期草稿;取消不会改变列表当前的“全部时间”。
|
||||
usesAllDates = false
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
@@ -270,8 +273,9 @@ final class ScenicMaterialDateFilterViewController: UIViewController, UIPickerVi
|
||||
}
|
||||
let value = endpoint == .start ? startDate : endDate
|
||||
let monthIndex = dateOptions.monthIndex(for: value)
|
||||
displayedMonthIndex = monthIndex
|
||||
picker.reloadAllComponents()
|
||||
picker.selectRow(monthIndex, inComponent: 0, animated: false)
|
||||
picker.reloadComponent(1)
|
||||
let dayIndex = dateOptions.months[monthIndex].dates.firstIndex(of: value) ?? 0
|
||||
picker.selectRow(dayIndex, inComponent: 1, animated: false)
|
||||
picker.accessibilityLabel = endpoint == .start ? "开始日期,月份和日期" : "结束日期,月份和日期"
|
||||
@@ -289,7 +293,8 @@ final class ScenicMaterialDateFilterViewController: UIViewController, UIPickerVi
|
||||
/// 首尾月份按保留期裁剪,滚轮中不会出现不可提交的日期。
|
||||
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
|
||||
if component == 0 { return dateOptions.months.count }
|
||||
return dateOptions.months[max(pickerView.selectedRow(inComponent: 0), 0)].dates.count
|
||||
guard component == 1, dateOptions.months.indices.contains(displayedMonthIndex) else { return 0 }
|
||||
return dateOptions.months[displayedMonthIndex].dates.count
|
||||
}
|
||||
|
||||
/// 使用与网页一致的 40 点行高。
|
||||
@@ -304,12 +309,18 @@ final class ScenicMaterialDateFilterViewController: UIViewController, UIPickerVi
|
||||
label.font = .systemFont(ofSize: 20, weight: .medium)
|
||||
label.textColor = ScenicMaterialsStyle.text
|
||||
label.textAlignment = .center
|
||||
label.text = nil
|
||||
label.accessibilityLabel = nil
|
||||
if component == 0 {
|
||||
guard dateOptions.months.indices.contains(row) else { return label }
|
||||
let month = dateOptions.months[row]
|
||||
label.text = dateOptions.monthTitle(at: row)
|
||||
label.accessibilityLabel = "\(month.year)年\(month.number)月"
|
||||
} else {
|
||||
let month = dateOptions.months[max(pickerView.selectedRow(inComponent: 0), 0)]
|
||||
} else if component == 1 {
|
||||
guard dateOptions.months.indices.contains(displayedMonthIndex) else { return label }
|
||||
let month = dateOptions.months[displayedMonthIndex]
|
||||
// 切换到短月或截断末月时,UIKit 过渡帧可能仍请求旧日列的末尾行。
|
||||
guard month.dates.indices.contains(row) else { return label }
|
||||
label.text = "\(calendar.component(.day, from: month.dates[row]))日"
|
||||
label.accessibilityLabel = label.text
|
||||
}
|
||||
@@ -318,15 +329,17 @@ final class ScenicMaterialDateFilterViewController: UIViewController, UIPickerVi
|
||||
|
||||
/// 更改月份时保留日号并收敛月末;更改端点后同步修正倒置区间。
|
||||
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
|
||||
usesAllDates = false
|
||||
let monthIndex = max(pickerView.selectedRow(inComponent: 0), 0)
|
||||
let value: Date
|
||||
if component == 0 {
|
||||
guard dateOptions.months.indices.contains(row) else { return }
|
||||
let current = endpoint == .start ? startDate : endDate
|
||||
value = dateOptions.date(inMonthAt: row, preferredDay: calendar.component(.day, from: current))
|
||||
} else {
|
||||
value = dateOptions.months[monthIndex].dates[row]
|
||||
}
|
||||
} else if component == 1 {
|
||||
guard dateOptions.months.indices.contains(displayedMonthIndex),
|
||||
dateOptions.months[displayedMonthIndex].dates.indices.contains(row) else { return }
|
||||
value = dateOptions.months[displayedMonthIndex].dates[row]
|
||||
} else { return }
|
||||
usesAllDates = false
|
||||
if endpoint == .start {
|
||||
startDate = value
|
||||
if endDate < value { endDate = value }
|
||||
|
||||
@@ -93,7 +93,7 @@ final class ScenicMaterialPreviewViewController: UIViewController {
|
||||
progressView.accessibilityLabel = "播放进度"
|
||||
playbackTime.accessibilityIdentifier = "scenic.materials.preview.playbackTime"
|
||||
resetPlaybackTime()
|
||||
let metadata = ScenicMaterialsStyle.label("\(clip.resolution) · \(clip.sizeText)", size: 11, color: ScenicMaterialsStyle.secondary)
|
||||
let metadata = ScenicMaterialsStyle.label("\(clip.durationText) · \(clip.sizeText)", size: 11, color: ScenicMaterialsStyle.secondary)
|
||||
metadata.numberOfLines = 2
|
||||
metadata.textAlignment = .right
|
||||
metadata.accessibilityIdentifier = "scenic.materials.preview.metadata"
|
||||
|
||||
@@ -11,7 +11,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
/// 辅助说明与每次拍摄批次分别使用稳定分区身份。
|
||||
private enum Section: Hashable { case retention, group(String), end }
|
||||
/// 选择与进度不参与身份,Diffable 更新时复用原有单元。
|
||||
private enum Item: Hashable { case retention, clip(String), expand(String), end }
|
||||
private enum Item: Hashable { case retention, clip(String), expand(String), loadMore, end }
|
||||
|
||||
private let filterBar = UIStackView()
|
||||
private let routeButton = UIButton(type: .system)
|
||||
@@ -24,6 +24,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
private let driver = ScenicMaterialDemoDownloadDriver()
|
||||
private let downloadService = ScenicMaterialDownloadService()
|
||||
private var loadTask: Task<Void, Never>?
|
||||
private var isLoadingNextPage = false
|
||||
private let refreshControl = UIRefreshControl()
|
||||
private let retryButton = UIButton(type: .system)
|
||||
private var authorizationTask: Task<Void, Never>?
|
||||
@@ -50,6 +51,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
@objc private func reloadRemoteMaterials() {
|
||||
guard viewModel.isRemote, !viewModel.isSelectionLocked else { refreshControl.endRefreshing(); return }
|
||||
loadTask?.cancel()
|
||||
isLoadingNextPage = false
|
||||
let session = AppStore.shared.session
|
||||
guard session.accountType == .storeUser, session.userId == viewModel.context.userID,
|
||||
String(session.currentScenicId) == viewModel.context.scenicID else {
|
||||
@@ -72,6 +74,29 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
}
|
||||
}
|
||||
|
||||
/// 用户主动加载下一页;不把第一页误标为全部素材,失败时保留已展示内容。
|
||||
private func loadMoreRemoteMaterials() {
|
||||
guard viewModel.isRemote, !viewModel.isSelectionLocked, !viewModel.isLoading,
|
||||
!isLoadingNextPage, viewModel.hasMoreRemoteSessions else { return }
|
||||
let session = AppStore.shared.session
|
||||
guard session.accountType == .storeUser, session.userId == viewModel.context.userID,
|
||||
String(session.currentScenicId) == viewModel.context.scenicID else {
|
||||
showToast("请使用门店账号并重新进入当前景区素材库")
|
||||
return
|
||||
}
|
||||
isLoadingNextPage = true
|
||||
refreshDisplay(animated: false)
|
||||
let api = ScenicMaterialsAPI(client: NetworkServices.shared.apiClient)
|
||||
loadTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await self.viewModel.loadMoreRemoteSessions(api: api)
|
||||
guard !Task.isCancelled else { return }
|
||||
self.isLoadingNextPage = false
|
||||
self.refreshDisplay()
|
||||
if let error = self.viewModel.loadMoreError { self.showToast(error) }
|
||||
}
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "景区空境库"
|
||||
navigationItem.backButtonDisplayMode = .minimal
|
||||
@@ -121,6 +146,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
collectionView.register(ScenicMaterialClipCell.self, forCellWithReuseIdentifier: "clip")
|
||||
collectionView.register(ScenicMaterialExpandCell.self, forCellWithReuseIdentifier: "expand")
|
||||
collectionView.register(ScenicMaterialTextCell.self, forCellWithReuseIdentifier: "text")
|
||||
collectionView.register(ScenicMaterialPageFooterCell.self, forCellWithReuseIdentifier: "pageFooter")
|
||||
collectionView.register(ScenicMaterialGroupHeaderView.self,
|
||||
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
|
||||
withReuseIdentifier: "group")
|
||||
@@ -186,6 +212,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
/// 仅在确认离开页面后作废异步工作,取消返回手势继续保留原来的加载及下载。
|
||||
private func finishLeaving() {
|
||||
loadTask?.cancel()
|
||||
isLoadingNextPage = false
|
||||
viewModel.cancelRemoteLoad()
|
||||
authorizationTask?.cancel()
|
||||
authorizationTask = nil
|
||||
@@ -197,8 +224,8 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
guard dataSource != nil else { return }
|
||||
routeButton.setTitle(viewModel.routeFilterTitle, for: .normal)
|
||||
dateButton.setTitle(viewModel.dateFilterTitle, for: .normal)
|
||||
routeButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading
|
||||
dateButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading
|
||||
routeButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading && !isLoadingNextPage
|
||||
dateButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading && !isLoadingNextPage
|
||||
retryButton.isHidden = viewModel.loadError == nil
|
||||
emptyTitle.text = viewModel.emptyTitle
|
||||
emptyMessage.text = viewModel.emptyMessage
|
||||
@@ -213,7 +240,8 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
if group.clips.count > 5 { snapshot.appendItems([.expand(group.id)]) }
|
||||
}
|
||||
if !viewModel.filteredGroups.isEmpty {
|
||||
snapshot.appendSections([.end]); snapshot.appendItems([.end])
|
||||
snapshot.appendSections([.end])
|
||||
snapshot.appendItems([viewModel.isRemote && viewModel.hasMoreRemoteSessions ? .loadMore : .end])
|
||||
}
|
||||
let existing = Set(dataSource.snapshot().itemIdentifiers)
|
||||
snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existing.contains($0) })
|
||||
@@ -251,6 +279,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
button.layer.borderWidth = 1
|
||||
button.layer.borderColor = ScenicMaterialsStyle.border.cgColor
|
||||
button.titleLabel?.lineBreakMode = .byTruncatingTail
|
||||
button.titleLabel?.numberOfLines = 1
|
||||
button.accessibilityIdentifier = identifier
|
||||
let chevron = UIImageView(image: UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium)))
|
||||
chevron.tintColor = ScenicMaterialsStyle.secondary
|
||||
@@ -305,6 +334,13 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
self?.refreshDisplay(animated: true)
|
||||
}
|
||||
return cell
|
||||
case .loadMore:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "pageFooter", for: path) as! ScenicMaterialPageFooterCell
|
||||
let title = self.isLoadingNextPage ? "正在加载更多场次…" : self.viewModel.loadMoreError != nil ? "加载失败,点击重试" :
|
||||
"加载更多场次(\(self.viewModel.loadedRemoteSessionCount) / \(self.viewModel.remoteTotalCount))"
|
||||
cell.configure(title: title, enabled: !self.isLoadingNextPage && !self.viewModel.isSelectionLocked)
|
||||
cell.onLoadMore = { [weak self] in self?.loadMoreRemoteMaterials() }
|
||||
return cell
|
||||
case .retention, .end:
|
||||
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! ScenicMaterialTextCell
|
||||
cell.configure(item == .retention ? self.viewModel.retentionTips : (self.viewModel.isRemote ? "已显示全部素材" : "已显示保留期内的全部演示记录"), identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end")
|
||||
@@ -374,7 +410,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
let section = sections[index]
|
||||
guard case .group(let id) = section, let group = self.viewModel.group(id: id) else {
|
||||
let item = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)))
|
||||
let row = NSCollectionLayoutGroup.vertical(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(36)), subitems: [item])
|
||||
let row = NSCollectionLayoutGroup.vertical(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: .absolute(section == .end ? 48 : 36)), subitems: [item])
|
||||
let layout = NSCollectionLayoutSection(group: row)
|
||||
layout.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
|
||||
return layout
|
||||
@@ -418,7 +454,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
switch viewModel.phase {
|
||||
case .idle:
|
||||
footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: viewModel.isRemote ? nil : "本地演示 · 不下载或保存真实文件",
|
||||
primaryTitle: "下载所选", primaryEnabled: viewModel.canStartDownload)
|
||||
primaryTitle: "下载所选", primaryEnabled: viewModel.canStartDownload && !isLoadingNextPage)
|
||||
case .downloading:
|
||||
footer.configure(title: "下载中 · \(completed)/\(total) 段", detail: "请保持页面开启,切后台将暂停",
|
||||
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress, isBusy: true)
|
||||
@@ -435,6 +471,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func performPrimaryAction() {
|
||||
guard !isLoadingNextPage, !viewModel.isLoading, !viewModel.isLoadingMore else { return }
|
||||
if viewModel.phase == .completed {
|
||||
viewModel.continueSelecting(); refreshDisplay(); return
|
||||
}
|
||||
@@ -459,6 +496,7 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func startTransfer() {
|
||||
guard !isLoadingNextPage, !viewModel.isLoading, !viewModel.isLoadingMore else { return }
|
||||
let started: Bool
|
||||
switch viewModel.phase {
|
||||
case .idle: started = viewModel.startDownload()
|
||||
@@ -554,6 +592,44 @@ final class ScenicMaterialsViewController: BaseViewController {
|
||||
}
|
||||
}
|
||||
|
||||
/// 分页末行仅负责触发用户主动加载,加载中禁用,失败后由页面设置重试文案。
|
||||
@MainActor
|
||||
final class ScenicMaterialPageFooterCell: UICollectionViewCell {
|
||||
/// 请求下一页或重试失败页。
|
||||
var onLoadMore: (() -> Void)?
|
||||
private let button = UIButton(type: .system)
|
||||
|
||||
/// 创建完整行宽的可访问加载按钮。
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
button.titleLabel?.font = .systemFont(ofSize: 13)
|
||||
button.tintColor = ScenicMaterialsStyle.primary
|
||||
button.accessibilityIdentifier = "scenic.materials.loadMore"
|
||||
button.addTarget(self, action: #selector(loadMore), for: .touchUpInside)
|
||||
contentView.addSubview(button)
|
||||
button.snp.makeConstraints { $0.edges.equalToSuperview() }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func prepareForReuse() {
|
||||
super.prepareForReuse()
|
||||
onLoadMore = nil
|
||||
}
|
||||
|
||||
/// 显示数量、加载中或重试状态,避免重复触发网络请求。
|
||||
func configure(title: String, enabled: Bool) {
|
||||
button.setTitle(title, for: .normal)
|
||||
button.isEnabled = enabled
|
||||
}
|
||||
|
||||
@objc private func loadMore() {
|
||||
guard button.isEnabled else { return }
|
||||
onLoadMore?()
|
||||
}
|
||||
}
|
||||
|
||||
/// 空镜列表的保留期与末尾说明,不参与素材选择。
|
||||
private final class ScenicMaterialTextCell: UICollectionViewCell {
|
||||
private let label = ScenicMaterialsStyle.label(size: 12, color: ScenicMaterialsStyle.secondary)
|
||||
|
||||
Reference in New Issue
Block a user