Files
suixinkan_uikit/suixinkan/UI/DroneDock/DroneDockMaterialComponents.swift
T

366 lines
20 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Kingfisher
import SnapKit
import UIKit
/// 真实订单素材库摘要:游客与状态同排,次数始终来自订单详情。
@MainActor
final class DroneDockMaterialOrderCell: UICollectionViewCell {
private let customerLabel = DroneDockStyle.label(size: 19, weight: .semibold)
private let statusLabel = DroneDockStatusLabel()
private let numberLabel = DroneDockStyle.label(size: 13, color: UIColor(hex: 0x70809D))
private let countLabel = DroneDockStyle.label(size: 13, color: UIColor(hex: 0x5D6C88))
override init(frame: CGRect) {
super.init(frame: frame)
let row = UIStackView(arrangedSubviews: [customerLabel, statusLabel, UIView()])
row.axis = .horizontal
row.spacing = 8
row.alignment = .center
customerLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
customerLabel.lineBreakMode = .byTruncatingTail
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
numberLabel.numberOfLines = 2
countLabel.numberOfLines = 2
let stack = UIStackView(arrangedSubviews: [row, numberLabel, countLabel])
stack.axis = .vertical
stack.spacing = 9
contentView.addSubview(stack)
stack.snp.makeConstraints { make in
make.top.equalToSuperview().offset(16)
make.leading.trailing.equalToSuperview()
make.bottom.equalToSuperview().inset(18)
}
accessibilityIdentifier = "drone.materials.remote.order"
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 不根据任务数量或素材上传状态推导订单拍摄履约状态。
func apply(order: DroneDockHomeOrder) {
customerLabel.text = order.touristTitle
let tone: DroneDockStatusTone = switch order.shootStatus {
case "completed": .green
case "processing": .blue
case "pending": .orange
default: .gray
}
statusLabel.apply(title: order.statusTitle, tone: tone)
numberLabel.text = order.orderNumberText
let total = order.shotTotal.map(String.init) ?? "—"
let used = order.shotUsed.map(String.init) ?? "—"
let remain = order.shotRemain.map(String.init) ?? "—"
countLabel.text = "含\(total)次拍摄 · 已拍摄\(used)次 · 剩余\(remain)次"
accessibilityLabel = [order.touristTitle, order.statusTitle, order.orderNumberText, countLabel.text].compactMap { $0 }.joined(separator: ",")
}
}
/// 素材记录标题:点位和交付按钮同排,航线、时间、记录序号位于次行。
@MainActor
final class DroneDockMaterialRecordCell: UICollectionViewCell {
private let titleLabel = DroneDockStyle.label(size: 17, weight: .semibold)
private let metadataLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let deliveryButton = UIButton(type: .system)
private let emptyIcon = UIImageView()
private let emptyTitle = DroneDockStyle.label(size: 13, weight: .medium)
private let emptyDetail = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary)
private let emptyPanel = UIStackView()
private let separator = UIView()
private var action: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.numberOfLines = 1
titleLabel.lineBreakMode = .byTruncatingTail
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
deliveryButton.setContentCompressionResistancePriority(.required, for: .horizontal)
deliveryButton.tintColor = DroneDockStyle.primary
deliveryButton.addTarget(self, action: #selector(deliveryTapped), for: .touchUpInside)
let titleRow = UIStackView(arrangedSubviews: [titleLabel, UIView(), deliveryButton])
titleRow.axis = .horizontal
titleRow.alignment = .center
titleRow.spacing = 8
metadataLabel.numberOfLines = 2
emptyIcon.contentMode = .scaleAspectFit
emptyTitle.numberOfLines = 2
emptyDetail.numberOfLines = 0
emptyPanel.axis = .vertical
emptyPanel.alignment = .leading
emptyPanel.spacing = 6
let emptyHeading = UIStackView(arrangedSubviews: [emptyIcon, emptyTitle])
emptyHeading.axis = .horizontal
emptyHeading.alignment = .center
emptyHeading.spacing = 6
emptyIcon.snp.makeConstraints { $0.size.equalTo(16).priority(999) }
emptyPanel.addArrangedSubview(emptyHeading)
emptyPanel.addArrangedSubview(emptyDetail)
let stack = UIStackView(arrangedSubviews: [titleRow, metadataLabel, emptyPanel])
stack.axis = .vertical
stack.spacing = 7
stack.setCustomSpacing(14, after: metadataLabel)
contentView.addSubview(stack)
stack.snp.makeConstraints { make in
make.top.equalToSuperview().offset(14)
make.leading.trailing.equalToSuperview()
make.bottom.equalToSuperview().inset(14)
}
deliveryButton.snp.makeConstraints { $0.height.equalTo(44) }
separator.backgroundColor = DroneDockStyle.border
contentView.addSubview(separator)
separator.snp.makeConstraints { make in make.leading.trailing.bottom.equalToSuperview(); make.height.equalTo(0.5) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 保留无素材任务的独立飞行与上传状态,不伪造文件或上传进度。
func apply(task: DroneDockMaterialTask, canDeliver: Bool, action: @escaping () -> Void) {
titleLabel.text = usable(task.spotName, fallback: "点位 \(task.spotID)")
let record = task.sequence.map { String(format: "记录%02d", $0) } ?? "记录序号待确认"
metadataLabel.text = "\(usable(task.airLineName, fallback: "航线待确认")) · \(shortDate(task.createdAt)) · \(record)"
var configuration = UIButton.Configuration.plain()
configuration.title = task.film == nil ? "交付成片" : "替换成片"
configuration.image = UIImage(systemName: "play.rectangle")
configuration.imagePadding = 5
configuration.contentInsets = .zero
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 13)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { value in
var attributes = value
attributes.font = .systemFont(ofSize: 12)
return attributes
}
deliveryButton.configuration = configuration
deliveryButton.isHidden = !canDeliver
deliveryButton.accessibilityIdentifier = "drone.materials.remote.delivery.\(task.id)"
self.action = action
emptyPanel.isHidden = !task.materials.isEmpty
separator.isHidden = !task.materials.isEmpty || task.film != nil
let state: (String, String, String, UIColor) = switch task.materialStatus {
case 0: ("素材待上传", "拍摄完成后将自动上传,请稍后刷新", "icloud.and.arrow.up", DroneDockStyle.secondary)
case 1: ("暂无可用原素材", "素材记录尚未返回,请刷新查看", "photo.on.rectangle", DroneDockStyle.secondary)
case 2: ("素材上传中", "素材正在上传,请稍后刷新查看", "icloud.and.arrow.up", DroneDockStyle.primary)
case 3: ("素材上传失败", "请刷新查看最新状态,或联系工作人员", "xmark.circle", DroneDockStyle.color(for: .red))
default: ("素材状态待确认", "暂无原素材,请稍后刷新查看", "questionmark.circle", DroneDockStyle.secondary)
}
emptyTitle.text = state.0
emptyTitle.textColor = state.3
emptyIcon.image = UIImage(systemName: state.2)
emptyIcon.tintColor = state.3
let film = task.film == nil ? " · 暂无视频成片" : ""
emptyDetail.text = "\(flightTitle(task.flightStatus))\(film)\n\(state.1)"
accessibilityIdentifier = "drone.materials.remote.task.\(task.id)"
}
private func usable(_ value: String?, fallback: String) -> String { DroneDockHomeMetric.usableText(value) ?? fallback }
private func shortDate(_ raw: String?) -> String {
guard let raw = DroneDockHomeMetric.usableText(raw) else { return "时间待确认" }
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let date = formatter.date(from: raw) else { return raw }
formatter.dateFormat = "MM-dd HH:mm"
return formatter.string(from: date)
}
private func flightTitle(_ value: Int?) -> String {
switch value {
case 10: "待飞行"
case 20: "执行中"
case 30: "飞行成功"
case 40: "飞行失败"
case 50: "已取消"
case 60: "待确认"
default: "飞行状态待确认"
}
}
@objc private func deliveryTapped() { action?() }
}
/// 真实文件的缩略图、状态和选择控件;预览与选择使用独立点击区域。
@MainActor
final class DroneDockMaterialMediaCell: UICollectionViewCell {
private let thumbnail = UIImageView()
private let icon = UIImageView()
private let previewButton = UIButton(type: .custom)
private let selectionButton = UIButton(type: .custom)
private let videoBadge = DroneDockStyle.label("视频", size: 10, color: .white)
private let titleLabel = DroneDockStyle.label(size: 13, weight: .medium)
private let stateLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let retryLabel = DroneDockStyle.label("重试上传", size: 11, color: DroneDockStyle.primary.withAlphaComponent(0.5))
private var previewAction: (() -> Void)?
private var selectionAction: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
thumbnail.contentMode = .scaleAspectFill
thumbnail.clipsToBounds = true
thumbnail.layer.cornerRadius = 6
thumbnail.layer.borderWidth = 2
thumbnail.backgroundColor = UIColor(hex: 0xE9EDF5)
thumbnail.accessibilityIdentifier = "drone.materials.remote.thumbnail"
icon.contentMode = .scaleAspectFit
titleLabel.lineBreakMode = .byTruncatingMiddle
titleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
retryLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
retryLabel.accessibilityTraits = [.button, .notEnabled]
retryLabel.accessibilityHint = "当前接口不支持重试上传,可通过页面刷新查看最新状态"
videoBadge.textAlignment = .center
videoBadge.backgroundColor = UIColor.black.withAlphaComponent(0.48)
videoBadge.layer.cornerRadius = 3
videoBadge.clipsToBounds = true
previewButton.addTarget(self, action: #selector(previewTapped), for: .touchUpInside)
selectionButton.addTarget(self, action: #selector(selectionTapped), for: .touchUpInside)
selectionButton.contentHorizontalAlignment = .right
selectionButton.contentVerticalAlignment = .top
let nameRow = UIStackView(arrangedSubviews: [titleLabel, retryLabel])
nameRow.axis = .horizontal
nameRow.spacing = 4
nameRow.alignment = .center
[thumbnail, icon, previewButton, videoBadge, selectionButton, nameRow, stateLabel].forEach(contentView.addSubview)
thumbnail.snp.makeConstraints { make in make.top.leading.trailing.equalToSuperview(); make.height.equalTo(thumbnail.snp.width).multipliedBy(9.0 / 16.0) }
icon.snp.makeConstraints { make in make.center.equalTo(thumbnail); make.size.equalTo(28) }
previewButton.snp.makeConstraints { $0.edges.equalTo(thumbnail) }
selectionButton.snp.makeConstraints { make in make.top.trailing.equalTo(thumbnail).inset(6); make.size.equalTo(44) }
videoBadge.snp.makeConstraints { make in make.leading.bottom.equalTo(thumbnail).inset(6); make.size.equalTo(CGSize(width: 32, height: 18)) }
nameRow.snp.makeConstraints { make in make.top.equalTo(thumbnail.snp.bottom).offset(7); make.leading.trailing.equalToSuperview() }
stateLabel.snp.makeConstraints { make in make.top.equalTo(nameRow.snp.bottom).offset(4); make.leading.trailing.equalToSuperview(); make.bottom.lessThanOrEqualToSuperview().inset(5) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func prepareForReuse() {
super.prepareForReuse()
thumbnail.kf.cancelDownloadTask()
thumbnail.image = nil
previewAction = nil
selectionAction = nil
}
/// 原素材上传就绪且 URL 有效才可勾选;Mock 图片存在时不请求远程缩略图。
func apply(file: DroneDockMaterialFile, taskID: Int, selected: Bool, selectionEnabled: Bool,
localImage: UIImage?, allowsRemoteImage: Bool, preview: @escaping () -> Void, select: @escaping () -> Void) {
let ready = file.previewURL != nil
let state: (String, UIColor) = switch file.uploadStatus {
case 0: ("待上传", DroneDockStyle.secondary)
case 1: (ready ? "上传完成 · 可下载" : "暂不可预览", ready ? DroneDockStyle.success : DroneDockStyle.secondary)
case 2: ("上传中", DroneDockStyle.primary)
case 3: ("上传失败", DroneDockStyle.color(for: .red))
default: ("素材状态待确认", DroneDockStyle.secondary)
}
let title = DroneDockHomeMetric.usableText(file.fileName) ?? "原素材 \(file.id)"
apply(title: title, state: state.0, color: state.1, cover: ready ? file.coverURL : nil,
fallback: ready && file.fileType == 1 ? file.previewURL : nil, video: file.fileType == 2,
enabled: ready, failed: file.uploadStatus == 3, localImage: ready ? localImage : nil,
allowsRemoteImage: allowsRemoteImage, identifier: "drone.materials.remote.file.\(taskID).\(file.id)")
previewAction = preview
selectionAction = select
selectionButton.isHidden = !ready
selectionButton.isEnabled = ready && selectionEnabled
selectionButton.accessibilityIdentifier = "drone.materials.remote.select.\(taskID).\(file.id)"
selectionButton.accessibilityLabel = "选择\(title)"
selectionButton.accessibilityTraits = selected ? [.button, .selected] : .button
selectionButton.setImage(MaterialSelectionIcon.orderImage(selected: selected, size: 22,
tint: MaterialSelectionIcon.primary,
includesBackground: true), for: .normal)
thumbnail.layer.borderColor = selected ? DroneDockStyle.primary.cgColor : UIColor.clear.cgColor
previewButton.accessibilityHint = file.uploadStatus == 3 ? DroneDockHomeMetric.usableText(file.failureReason) : nil
}
/// 已交付成片独立标记且不参与原素材全选。
func apply(film: DroneDockMaterialFilm, taskID: Int, localImage: UIImage?, allowsRemoteImage: Bool,
preview: @escaping () -> Void) {
let ready = film.previewURL != nil
apply(title: DroneDockHomeMetric.usableText(film.fileName) ?? "视频成片", state: ready ? "视频成片 · 点击播放" : "视频成片 · 暂不可预览",
color: ready ? DroneDockStyle.success : DroneDockStyle.secondary, cover: film.coverURL, fallback: nil,
video: true, enabled: ready, failed: false, localImage: localImage, allowsRemoteImage: allowsRemoteImage,
identifier: "drone.materials.remote.film.\(taskID).\(film.id)")
selectionButton.isHidden = true
selectionAction = nil
previewAction = preview
previewButton.accessibilityHint = nil
thumbnail.layer.borderColor = UIColor.clear.cgColor
}
private func apply(title: String, state: String, color: UIColor, cover: String?, fallback: URL?, video: Bool,
enabled: Bool, failed: Bool, localImage: UIImage?, allowsRemoteImage: Bool, identifier: String) {
thumbnail.kf.cancelDownloadTask()
thumbnail.image = localImage
let coverURL = cover.flatMap(URL.init(string:)).flatMap { url in
["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host != nil ? url : nil
}
if allowsRemoteImage, enabled { thumbnail.kf.setImage(with: coverURL ?? fallback) }
icon.image = UIImage(systemName: failed ? "xmark.circle" : video ? "play.fill" : "photo")
icon.tintColor = failed ? DroneDockStyle.color(for: .red) : UIColor(hex: 0x9CA6B6)
icon.isHidden = enabled && (localImage != nil || coverURL != nil || fallback != nil)
titleLabel.text = title
stateLabel.text = state
stateLabel.textColor = color
retryLabel.isHidden = !failed
retryLabel.accessibilityIdentifier = identifier + ".retryUpload"
videoBadge.isHidden = !video || !enabled
previewButton.isEnabled = enabled
previewButton.accessibilityIdentifier = identifier + ".preview"
previewButton.accessibilityLabel = "\(title),\(state)"
accessibilityIdentifier = identifier
accessibilityLabel = "\(title),\(state)"
accessibilityTraits = enabled ? .button : [.notEnabled]
}
@objc private func previewTapped() { previewAction?() }
@objc private func selectionTapped() { selectionAction?() }
}
/// 居中展示列表加载、空态和错误;刷新失败与没有素材是不同状态。
@MainActor
final class DroneDockMaterialMessageCell: UICollectionViewCell {
private let icon = UIImageView()
private let titleLabel = DroneDockStyle.label(size: 16, weight: .medium)
private let detailLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary)
private let button = UIButton(type: .system)
private let spinner = UIActivityIndicatorView(style: .medium)
private var action: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
icon.contentMode = .scaleAspectFit
icon.tintColor = DroneDockStyle.secondary
titleLabel.textAlignment = .center
titleLabel.numberOfLines = 2
detailLabel.textAlignment = .center
detailLabel.numberOfLines = 0
button.tintColor = DroneDockStyle.primary
button.addTarget(self, action: #selector(retryTapped), for: .touchUpInside)
let stack = UIStackView(arrangedSubviews: [icon, spinner, titleLabel, detailLabel, button])
stack.axis = .vertical
stack.alignment = .center
stack.spacing = 12
contentView.addSubview(stack)
stack.snp.makeConstraints { make in make.centerY.equalToSuperview(); make.leading.trailing.equalToSuperview().inset(12) }
icon.snp.makeConstraints { $0.size.equalTo(38).priority(999) }
button.snp.makeConstraints { $0.height.equalTo(44).priority(999) }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 不将错误转换为空列表,未提供重试闭包时隐藏操作。
func apply(title: String, detail: String, identifier: String, loading: Bool = false,
error: Bool = false, retry: (() -> Void)? = nil) {
titleLabel.text = title
detailLabel.text = detail
detailLabel.isHidden = detail.isEmpty
icon.image = UIImage(systemName: error ? "exclamationmark.circle" : "photo.on.rectangle.angled")
icon.isHidden = loading
if loading { spinner.startAnimating() } else { spinner.stopAnimating() }
spinner.isHidden = !loading
spinner.alpha = loading ? 1 : 0
button.isHidden = retry == nil
button.setTitle("重试", for: .normal)
button.accessibilityIdentifier = "drone.materials.remote.retry"
action = retry
accessibilityIdentifier = identifier
}
@objc private func retryTapped() { action?() }
}