feat: 完善机巢模拟调试与素材交付交互

增加禁飞期间的设备指令拦截及本地模拟拍摄流程;适配订单素材库和景区空境库,完善素材筛选、预览与下载;订单交付入口改为方式选择弹窗并复用云端上传。补充单元测试、接口记录和模拟器截图。
This commit is contained in:
2026-10-30 09:59:11 +08:00
parent e827bf8725
commit b95b251de1
100 changed files with 7256 additions and 500 deletions
@@ -1,3 +1,4 @@
import Photos
import SnapKit
import UIKit
@@ -21,6 +22,11 @@ final class ScenicMaterialsViewController: BaseViewController {
private let emptyMessage = ScenicMaterialsStyle.label(size: 14, color: ScenicMaterialsStyle.secondary)
private let resetButton = UIButton(type: .system)
private let driver = ScenicMaterialDemoDownloadDriver()
private let downloadService = ScenicMaterialDownloadService()
private var loadTask: Task<Void, Never>?
private let refreshControl = UIRefreshControl()
private let retryButton = UIButton(type: .system)
private var authorizationTask: Task<Void, Never>?
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout())
private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
private var isDemoPhotoPermissionAllowed: Bool
@@ -36,6 +42,36 @@ final class ScenicMaterialsViewController: BaseViewController {
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
if viewModel.isRemote { reloadRemoteMaterials() }
}
@objc private func reloadRemoteMaterials() {
guard viewModel.isRemote, !viewModel.isSelectionLocked else { refreshControl.endRefreshing(); return }
loadTask?.cancel()
let session = AppStore.shared.session
guard session.accountType == .storeUser, session.userId == viewModel.context.userID,
String(session.currentScenicId) == viewModel.context.scenicID else {
refreshControl.endRefreshing()
showToast("请使用门店账号并重新进入当前景区素材库")
return
}
let api = ScenicMaterialsAPI(client: NetworkServices.shared.apiClient)
emptyTitle.text = "正在加载素材"
emptyMessage.text = "请稍候"
retryButton.isHidden = true
routeButton.isEnabled = false
dateButton.isEnabled = false
loadTask = Task { @MainActor [weak self] in
guard let self else { return }
await self.viewModel.loadRemoteSessions(api: api)
guard !Task.isCancelled else { return }
self.refreshControl.endRefreshing()
self.refreshDisplay()
}
}
override func setupNavigationBar() {
title = "景区空境库"
navigationItem.backButtonDisplayMode = .minimal
@@ -48,12 +84,14 @@ final class ScenicMaterialsViewController: BaseViewController {
navigationItem.standardAppearance = appearance
navigationItem.scrollEdgeAppearance = appearance
#if DEBUG
guard !viewModel.isRemote else { return }
var actions: [UIAction] = ScenicMaterialsScenario.allCases.map { scenario in
UIAction(title: scenario.title) { [weak self] _ in self?.applyPreviewScenario(scenario) }
}
actions.append(UIAction(title: "相册权限不足") { [weak self] _ in
guard let self else { return }
self.driver.stop()
self.downloadService.stop()
self.viewModel.pauseDownload()
self.isDemoPhotoPermissionAllowed = false
self.refreshDisplay(animated: false)
@@ -89,6 +127,10 @@ final class ScenicMaterialsViewController: BaseViewController {
view.addSubview(filterBar)
view.addSubview(collectionView)
view.addSubview(footer)
if viewModel.isRemote {
collectionView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(reloadRemoteMaterials), for: .valueChanged)
}
setupEmptyView()
configureDataSource()
refreshDisplay(animated: false)
@@ -98,7 +140,7 @@ final class ScenicMaterialsViewController: BaseViewController {
filterBar.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide).offset(10)
make.leading.trailing.equalToSuperview().inset(16)
make.height.equalTo(42)
make.height.equalTo(40)
}
collectionView.snp.makeConstraints { make in
make.top.equalTo(filterBar.snp.bottom).offset(8)
@@ -116,6 +158,7 @@ final class ScenicMaterialsViewController: BaseViewController {
footer.onSecondaryTap = { [weak self] in
guard let self else { return }
self.driver.stop()
self.downloadService.stop()
if self.viewModel.phase == .downloading || self.viewModel.phase == .paused {
self.viewModel.cancelDownload()
} else {
@@ -133,20 +176,30 @@ final class ScenicMaterialsViewController: BaseViewController {
guard isMovingFromParent || isBeingDismissed || navigationController?.isBeingDismissed == true else { return }
if let coordinator = transitionCoordinator, coordinator.isInteractive {
coordinator.animate(alongsideTransition: nil) { [weak self] context in
if !context.isCancelled { self?.pauseForBackground() }
if !context.isCancelled { self?.finishLeaving() }
}
} else {
pauseForBackground()
finishLeaving()
}
}
/// 仅在确认离开页面后作废异步工作,取消返回手势继续保留原来的加载及下载。
private func finishLeaving() {
loadTask?.cancel()
viewModel.cancelRemoteLoad()
authorizationTask?.cancel()
authorizationTask = nil
pauseForBackground()
}
/// 外部演示回执后显式刷新,不自动开始或继续任何传输。
func refreshDisplay(animated: Bool = true) {
guard dataSource != nil else { return }
routeButton.setTitle(viewModel.routeFilterTitle, for: .normal)
dateButton.setTitle(viewModel.dateFilterTitle, for: .normal)
routeButton.isEnabled = !viewModel.isSelectionLocked
dateButton.isEnabled = !viewModel.isSelectionLocked
routeButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading
dateButton.isEnabled = !viewModel.isSelectionLocked && !viewModel.isLoading
retryButton.isHidden = viewModel.loadError == nil
emptyTitle.text = viewModel.emptyTitle
emptyMessage.text = viewModel.emptyMessage
resetButton.isHidden = viewModel.selectedRouteID == nil && viewModel.dateRange == nil
@@ -184,21 +237,26 @@ final class ScenicMaterialsViewController: BaseViewController {
private func configureFilterButton(_ button: UIButton, identifier: String) {
var configuration = UIButton.Configuration.plain()
configuration.image = UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium))
configuration.imagePlacement = .trailing
configuration.imagePadding = 8
configuration.baseForegroundColor = ScenicMaterialsStyle.text
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 12)
configuration.cornerStyle = .fixed
configuration.background.cornerRadius = 11
configuration.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 12, bottom: 8, trailing: 32)
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var result = incoming; result.font = .systemFont(ofSize: 13); return result
var result = incoming; result.font = .systemFont(ofSize: 15, weight: .medium); return result
}
button.configuration = configuration
button.backgroundColor = UIColor(hex: 0xF6F7F9)
button.layer.cornerRadius = 10
button.layer.borderWidth = 0.5
button.contentHorizontalAlignment = .leading
button.backgroundColor = UIColor(hex: 0xF7F8FA)
button.layer.cornerRadius = 11
button.layer.borderWidth = 1
button.layer.borderColor = ScenicMaterialsStyle.border.cgColor
button.titleLabel?.lineBreakMode = .byTruncatingTail
button.accessibilityIdentifier = identifier
let chevron = UIImageView(image: UIImage(systemName: "chevron.down", withConfiguration: UIImage.SymbolConfiguration(pointSize: 10, weight: .medium)))
chevron.tintColor = ScenicMaterialsStyle.secondary
chevron.isUserInteractionEnabled = false
button.addSubview(chevron)
chevron.snp.makeConstraints { $0.trailing.equalToSuperview().inset(12); $0.centerY.equalToSuperview() }
}
private func setupEmptyView() {
@@ -213,7 +271,10 @@ final class ScenicMaterialsViewController: BaseViewController {
resetButton.tintColor = ScenicMaterialsStyle.primary
resetButton.accessibilityIdentifier = "scenic.materials.resetFilters"
emptyView.accessibilityIdentifier = "scenic.materials.empty"
let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton])
retryButton.setTitle("重新加载", for: .normal)
retryButton.accessibilityIdentifier = "scenic.materials.retry"
retryButton.addTarget(self, action: #selector(reloadRemoteMaterials), for: .touchUpInside)
let stack = UIStackView(arrangedSubviews: [icon, emptyTitle, emptyMessage, resetButton, retryButton])
stack.axis = .vertical
stack.spacing = 14
emptyView.addSubview(stack)
@@ -246,7 +307,7 @@ final class ScenicMaterialsViewController: BaseViewController {
return cell
case .retention, .end:
let cell = list.dequeueReusableCell(withReuseIdentifier: "text", for: path) as! ScenicMaterialTextCell
cell.configure(item == .retention ? "素材保留 90 天,请及时下载" : "已显示保留期内的全部演示记录", identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end")
cell.configure(item == .retention ? self.viewModel.retentionTips : (self.viewModel.isRemote ? "已显示全部素材" : "已显示保留期内的全部演示记录"), identifier: item == .retention ? "scenic.materials.retention" : "scenic.materials.end")
return cell
}
}
@@ -265,7 +326,7 @@ final class ScenicMaterialsViewController: BaseViewController {
let completed = viewModel.completedIDs.contains(clip.id)
let failed = viewModel.failedIDs.contains(clip.id)
let inBatch = viewModel.batchItemIDs.contains(clip.id)
let status: String? = completed ? "演示已下载" : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil
let status: String? = completed ? (viewModel.isRemote ? "已保存相册" : "演示已下载") : failed ? "下载失败" : inBatch && viewModel.phase == .paused ? "已暂停" : nil
cell.configure(clip: clip, selected: viewModel.selectedIDs.contains(clip.id),
isSelectionEnabled: viewModel.canSelect(id: clip.id), statusText: status,
progress: inBatch && viewModel.phase == .downloading && !completed ? viewModel.progressByID[clip.id] ?? 0 : nil,
@@ -356,20 +417,20 @@ final class ScenicMaterialsViewController: BaseViewController {
let total = viewModel.totalCount
switch viewModel.phase {
case .idle:
footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: "本地演示 · 不下载或保存真实文件",
primaryTitle: viewModel.selectedCount > 0 ? "下载所选(\(viewModel.selectedCount))" : "下载所选", primaryEnabled: viewModel.canStartDownload)
footer.configure(title: "已选 \(viewModel.selectedCount) 段", detail: viewModel.isRemote ? nil : "本地演示 · 不下载或保存真实文件",
primaryTitle: "下载所选", primaryEnabled: viewModel.canStartDownload)
case .downloading:
footer.configure(title: "下载中 · \(completed)/\(total) 段", detail: "请保持页面开启,切后台将暂停",
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress))
primaryTitle: "正在下载…", primaryEnabled: false, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress, isBusy: true)
case .paused:
footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "演示进度已保留,请手动继续",
primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消")
footer.configure(title: "已暂停 · 已完成 \(completed)/\(total) 段", detail: "已完成项已保留,请手动继续",
primaryTitle: "继续下载", primaryEnabled: true, secondaryTitle: "取消", progress: Float(viewModel.downloadProgress), layout: .progress)
case .partialFailure:
footer.configure(title: "演示完成 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: "未保存真实文件,成功项不重复下载",
primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择")
footer.configure(title: "已下载 \(completed) 段 · 失败 \(viewModel.failedCount) 段", detail: viewModel.isRemote ? "成功项已保存相册" : "演示结果 · 未保存真实文件",
primaryTitle: "重试失败(\(viewModel.failedCount))", primaryEnabled: true, secondaryTitle: "继续选择", layout: .result)
case .completed:
footer.configure(title: "演示完成 \(completed) 段", detail: "未写入系统相册",
primaryTitle: "继续选择素材", primaryEnabled: true)
footer.configure(title: viewModel.isRemote ? "已保存 \(completed) 段" : "演示完成 \(completed) 段", detail: viewModel.isRemote ? "可在系统相册查看" : "未写入系统相册",
primaryTitle: "继续选择素材", primaryEnabled: true, layout: .result)
}
}
@@ -377,7 +438,27 @@ final class ScenicMaterialsViewController: BaseViewController {
if viewModel.phase == .completed {
viewModel.continueSelecting(); refreshDisplay(); return
}
if viewModel.isRemote {
guard authorizationTask == nil else { return }
authorizationTask = Task { @MainActor [weak self] in
let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
guard let self else { return }
self.authorizationTask = nil
guard !Task.isCancelled, self.view.window != nil,
UIApplication.shared.applicationState == .active else { return }
guard status == .authorized || status == .limited else {
self.presentPhotoPermissionSettings()
return
}
self.startTransfer()
}
return
}
guard isDemoPhotoPermissionAllowed else { presentPermissionDemo(); return }
startTransfer()
}
private func startTransfer() {
let started: Bool
switch viewModel.phase {
case .idle: started = viewModel.startDownload()
@@ -386,11 +467,25 @@ final class ScenicMaterialsViewController: BaseViewController {
case .downloading, .completed: started = false
}
refreshDisplay(animated: false)
if started { driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) } }
guard started else { return }
if viewModel.isRemote, let batchID = viewModel.batchID {
let items = viewModel.pendingIDs.compactMap { id -> ScenicMaterialDownloadItem? in
guard let clip = viewModel.clip(id: id), let url = clip.remoteURL else { return nil }
return ScenicMaterialDownloadItem(id: id, remoteURL: url,
fileName: url.pathExtension.isEmpty ? "scenic-material.mp4" : url.lastPathComponent)
}
downloadService.start(items: items, batchID: batchID) { [weak self] id, token, event in
self?.viewModel.receive(event, clipID: id, batchID: token)
self?.refreshDisplay(animated: false)
} onFailure: { [weak self] _, error in self?.showToast(error.localizedDescription) }
} else {
driver.start(viewModel: viewModel) { [weak self] in self?.refreshDisplay(animated: false) }
}
}
@objc private func pauseForBackground() {
driver.stop()
downloadService.stop()
viewModel.pauseDownload()
if isViewLoaded { refreshDisplay(animated: false) }
}
@@ -400,6 +495,7 @@ final class ScenicMaterialsViewController: BaseViewController {
let picker = ScenicMaterialRouteFilterViewController(routes: viewModel.routes, selectedRouteID: viewModel.selectedRouteID)
picker.onSelectRoute = { [weak self] id in
self?.viewModel.setRoute(id: id)
self?.reloadRemoteMaterials()
self?.refreshDisplay()
self?.collectionView.setContentOffset(.zero, animated: false)
}
@@ -414,6 +510,7 @@ final class ScenicMaterialsViewController: BaseViewController {
picker.onSelectRange = { [weak self] start, end in
guard let self else { return }
if self.viewModel.setDateRange(start: start, end: end) {
self.reloadRemoteMaterials()
self.refreshDisplay()
self.collectionView.setContentOffset(.zero, animated: false)
} else { self.showToast("请选择保留期内的有效日期范围") }
@@ -423,6 +520,7 @@ final class ScenicMaterialsViewController: BaseViewController {
@objc private func resetFilters() {
viewModel.resetFilters()
reloadRemoteMaterials()
refreshDisplay()
}
@@ -433,6 +531,16 @@ final class ScenicMaterialsViewController: BaseViewController {
present(controller, animated: true)
}
private func presentPhotoPermissionSettings() {
guard presentedViewController == nil else { return }
let alert = UIAlertController(title: "需要相册保存权限", message: "请允许添加照片和视频,以保存所选素材。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in
if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }
})
present(alert, animated: true)
}
private func presentPermissionDemo() {
guard presentedViewController == nil else { return }
let alert = UIAlertController(title: "需要相册保存权限", message: "真实下载需允许保存视频。此处仅演示权限流程,不读取或修改系统权限。", preferredStyle: .alert)