新增景区排队管理功能

This commit is contained in:
2026-07-07 15:32:25 +08:00
parent 854a66689f
commit 0aa8b14e1f
20 changed files with 4642 additions and 1 deletions

View File

@ -0,0 +1,81 @@
//
// ScenicQueueSettingChangeLogViewModel.swift
// suixinkan
//
import Foundation
/// ViewModel
final class ScenicQueueSettingChangeLogViewModel {
private enum Constants {
static let pageSize = 20
}
private(set) var items: [ScenicQueueSettingChangeLogItem] = []
private(set) var isRefreshing = false
private(set) var isLoadingMore = false
private(set) var canLoadMore = false
var onStateChange: (() -> Void)?
var onShowMessage: ((String) -> Void)?
private let appStore: AppStore
private var total = 0
private var lastLoadedPage = 0
init(appStore: AppStore = .shared) {
self.appStore = appStore
}
///
func refresh(api: ScenicQueueAPIProtocol) async {
await load(api: api, page: 1, append: false)
}
///
func loadMore(api: ScenicQueueAPIProtocol) async {
guard canLoadMore, !isRefreshing, !isLoadingMore else { return }
await load(api: api, page: lastLoadedPage + 1, append: true)
}
private func load(api: ScenicQueueAPIProtocol, page: Int, append: Bool) async {
guard appStore.currentScenicId > 0 else {
onShowMessage?("请先选择景区")
return
}
if append {
isLoadingMore = true
} else {
isRefreshing = true
}
notifyStateChange()
defer {
if append { isLoadingMore = false } else { isRefreshing = false }
notifyStateChange()
}
let spotId = Int64(appStore.scenicQueuePunchSpotId)
do {
let data = try await api.settingChangeLog(
scenicId: Int64(appStore.currentScenicId),
scenicSpotId: spotId,
page: page,
pageSize: Constants.pageSize
)
if append {
let seen = Set(items.map(\.id))
items += data.list.filter { !seen.contains($0.id) }
} else {
items = data.list
}
total = max(0, data.total)
lastLoadedPage = max(1, data.page)
canLoadMore = items.count < total && !data.list.isEmpty
} catch {
onShowMessage?(error.localizedDescription)
}
}
private func notifyStateChange() {
onStateChange?()
}
}

View File

@ -0,0 +1,496 @@
//
// ScenicQueueSettingsViewModel.swift
// suixinkan
//
import Foundation
/// ViewModel Android `ScenicQueueSettingsViewModel`
final class ScenicQueueSettingsViewModel {
private enum Limits {
static let remarkMaxLen = 255
static let shootMinute = 0...30
static let shootSecond = 0...59
static let ahead = 0...50
static let broadcastInterval = 40...60
static let readableThreshold = 10...30
static let queueDistance = 0...9_999_990
static let queueTakeLimit = 0...999_999
static let missCallRequeueOffset = 1...9_999
static let autoCallAheadCount = 0...5
}
private(set) var punchSpotOptions: [ScenicQueuePunchSpotOption] = []
private(set) var selectedPunchSpotId: String?
private(set) var selectedPunchSpotLabel: String
private(set) var shootMinute: Int
private(set) var shootSecond: Int
private(set) var firstAheadCount: Int
private(set) var firstSms: Bool
private(set) var firstPhone: Bool
private(set) var secondAheadCount: Int
private(set) var secondSms: Bool
private(set) var secondPhone: Bool
private(set) var broadcastIntervalSec: Int
private(set) var countdownThresholdSec: Int
private(set) var queueDistanceMeter: Int
private(set) var queueTakeLimit: Int
private(set) var missCallRequeueOffset: Int
private(set) var showStartShootingButton: Bool
private(set) var autoCallAheadCount: Int
private(set) var quickCallButtonEnabled: Bool
private(set) var prepareCallButtonEnabled: Bool
private(set) var businessOpen: Bool
private(set) var businessStartTime: String
private(set) var businessEndTime: String
private(set) var customTTSText: String
private(set) var presetVoices: [String]
private(set) var settingsTab: ScenicQueueSettingsTab = .basic
private(set) var highlightedInvalidFieldKeys: Set<String> = []
var onStateChange: (() -> Void)?
var onShowMessage: ((String) -> Void)?
var onNavigateBack: (() -> Void)?
var onNavigateLog: (() -> Void)?
private let appStore: AppStore
private let ttsManager: ScenicQueueTTSManaging
private var punchSpotSettingRequestGeneration = 0
private var ttsLoopAnchorText: String?
init(appStore: AppStore = .shared, ttsManager: ScenicQueueTTSManaging = AliyunNLSTTSManager.shared) {
self.appStore = appStore
self.ttsManager = ttsManager
let snapshot = appStore.scenicQueueSettingsSnapshot() ?? ScenicQueueSettingsSnapshot()
selectedPunchSpotId = appStore.scenicQueuePunchSpotId.nonEmptyTrimmed
selectedPunchSpotLabel = appStore.scenicQueuePunchSpotName
shootMinute = snapshot.shootMinute.clamped(to: Limits.shootMinute)
shootSecond = snapshot.shootSecond.clamped(to: Limits.shootSecond)
firstAheadCount = snapshot.firstAheadCount.clamped(to: Limits.ahead)
firstSms = snapshot.firstSms
firstPhone = snapshot.firstPhone
secondAheadCount = snapshot.secondAheadCount.clamped(to: Limits.ahead)
secondSms = snapshot.secondSms
secondPhone = snapshot.secondPhone
broadcastIntervalSec = snapshot.broadcastIntervalSec.clamped(to: Limits.broadcastInterval)
countdownThresholdSec = snapshot.countdownThresholdSec.clamped(to: Limits.readableThreshold)
queueDistanceMeter = snapshot.queueDistanceMeter.clamped(to: Limits.queueDistance)
queueTakeLimit = snapshot.queueTakeLimit.clamped(to: Limits.queueTakeLimit)
missCallRequeueOffset = snapshot.missCallRequeueOffset.clamped(to: Limits.missCallRequeueOffset)
showStartShootingButton = snapshot.showStartShootingButton
autoCallAheadCount = snapshot.autoCallAheadCount.clamped(to: Limits.autoCallAheadCount)
quickCallButtonEnabled = snapshot.quickCallButtonEnabled
prepareCallButtonEnabled = snapshot.prepareCallButtonEnabled
businessOpen = snapshot.businessOpen
businessStartTime = Self.normalizedTime(snapshot.businessStartTime, fallback: "10:00")
businessEndTime = Self.normalizedTime(snapshot.businessEndTime, fallback: "20:00")
customTTSText = appStore.scenicQueueRemark
presetVoices = appStore.scenicQueuePresetVoices()
}
var selectedPunchSpotDisplayText: String {
if let selectedPunchSpotId,
let option = punchSpotOptions.first(where: { $0.id == selectedPunchSpotId }),
!option.label.isEmpty {
return option.label
}
if !selectedPunchSpotLabel.isEmpty {
return selectedPunchSpotLabel
}
if let selectedPunchSpotId, !selectedPunchSpotId.isEmpty {
return "打卡点ID \(selectedPunchSpotId)"
}
return "请选择打卡点"
}
func openSettingChangeLog() {
onNavigateLog?()
}
///
func loadPunchSpotOptions(api: ScenicQueueAPIProtocol) async {
guard appStore.currentScenicId > 0 else {
onShowMessage?("请先选择景区")
return
}
do {
let response = try await api.scenicSpotListAll(scenicId: String(appStore.currentScenicId))
punchSpotOptions = response.list.map {
ScenicQueuePunchSpotOption(id: String($0.id), label: $0.name)
}
if punchSpotOptions.isEmpty {
onShowMessage?("暂无可选打卡点")
}
notifyStateChange()
} catch {
onShowMessage?(error.localizedDescription)
}
}
///
func setPunchSpot(_ option: ScenicQueuePunchSpotOption, api: ScenicQueueAPIProtocol) async {
selectedPunchSpotId = option.id
selectedPunchSpotLabel = option.label.trimmingCharacters(in: .whitespacesAndNewlines)
highlightedInvalidFieldKeys.remove("punchSpot")
notifyStateChange()
await fetchQueueSettingAfterPunchSpotSelected(option.id, api: api)
}
func setSettingsTab(_ tab: ScenicQueueSettingsTab) {
settingsTab = tab
notifyStateChange()
}
func setShootMinute(_ value: Int) { shootMinute = value.clamped(to: Limits.shootMinute); notifyStateChange() }
func setShootSecond(_ value: Int) { shootSecond = value.clamped(to: Limits.shootSecond); notifyStateChange() }
func setFirstAheadCount(_ value: Int) { firstAheadCount = value.clamped(to: Limits.ahead); notifyStateChange() }
func setSecondAheadCount(_ value: Int) { secondAheadCount = value.clamped(to: Limits.ahead); notifyStateChange() }
func setBroadcastIntervalSec(_ value: Int) { broadcastIntervalSec = value.clamped(to: Limits.broadcastInterval); notifyStateChange() }
func setCountdownThresholdSec(_ value: Int) { countdownThresholdSec = value.clamped(to: Limits.readableThreshold); notifyStateChange() }
func setQueueDistanceMeter(_ value: Int) { queueDistanceMeter = value.clamped(to: Limits.queueDistance); notifyStateChange() }
func setQueueTakeLimit(_ value: Int) { queueTakeLimit = value.clamped(to: Limits.queueTakeLimit); notifyStateChange() }
func setMissCallRequeueOffset(_ value: Int) { missCallRequeueOffset = value.clamped(to: Limits.missCallRequeueOffset); notifyStateChange() }
func setAutoCallAheadCount(_ value: Int) { autoCallAheadCount = value.clamped(to: Limits.autoCallAheadCount); notifyStateChange() }
func toggleShowStartShootingButton() { showStartShootingButton.toggle(); notifyStateChange() }
func toggleQuickCallButtonEnabled() { quickCallButtonEnabled.toggle(); notifyStateChange() }
func togglePrepareCallButtonEnabled() { prepareCallButtonEnabled.toggle(); notifyStateChange() }
func toggleBusinessOpen() { businessOpen.toggle(); notifyStateChange() }
func toggleFirstSms() { firstSms.toggle(); notifyStateChange() }
func toggleFirstPhone() { firstPhone.toggle(); notifyStateChange() }
func toggleSecondSms() { secondSms.toggle(); notifyStateChange() }
func toggleSecondPhone() { secondPhone.toggle(); notifyStateChange() }
func setBusinessStartTime(_ value: String) {
businessStartTime = Self.normalizedTime(value, fallback: businessStartTime)
notifyStateChange()
}
func setBusinessEndTime(_ value: String) {
businessEndTime = Self.normalizedTime(value, fallback: businessEndTime)
notifyStateChange()
}
func setCustomTTSText(_ value: String) {
customTTSText = String(value.prefix(Limits.remarkMaxLen))
notifyStateChange()
}
/// TTS
func toggleCustomTTSPlayback() {
if ttsManager.customTextLooping {
ttsManager.stopCustomTextLoop()
ttsLoopAnchorText = nil
notifyStateChange()
return
}
let text = customTTSText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else {
onShowMessage?("请输入要播报的文字")
return
}
Task {
let ok = await ttsManager.startCustomTextLoop(text)
if ok {
ttsLoopAnchorText = text
} else {
ttsLoopAnchorText = nil
onShowMessage?("播报失败,请检查网络与语音服务")
}
notifyStateChange()
}
}
///
func playBluetoothTestSound() {
Task {
let ok = await ttsManager.speakPlainTextOnce("蓝牙音响测试音,请确认外放音量是否合适。")
if !ok {
onShowMessage?("测试音播放失败,请检查网络与语音服务")
}
}
}
///
func saveCurrentTextAsPresetVoiceLocal() {
guard appStore.currentScenicId > 0, selectedPunchSpotId?.nonEmptyTrimmed != nil else {
onShowMessage?("请先选择打卡点")
return
}
let text = customTTSText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else {
onShowMessage?("请输入要播报的文字")
return
}
if presetVoices.count >= 5 {
onShowMessage?("最多保存5个语音")
return
}
if presetVoices.contains(text) {
onShowMessage?("该文案已在列表中")
return
}
presetVoices.append(text)
appStore.saveScenicQueuePresetVoices(presetVoices)
onShowMessage?("已保存到本地")
notifyStateChange()
}
func deletePresetVoice(at index: Int) {
guard presetVoices.indices.contains(index) else { return }
let removed = presetVoices.remove(at: index)
appStore.saveScenicQueuePresetVoices(presetVoices)
if ttsLoopAnchorText == removed {
ttsManager.stopCustomTextLoop()
ttsLoopAnchorText = nil
}
notifyStateChange()
}
///
func saveShootQueueQRCode(api: ScenicQueueAPIProtocol) async {
guard let ids = currentScenicAndSpotIdsForSelected() else {
onShowMessage?("请先选择打卡点")
return
}
do {
let data = try await api.shootQueueQrcode(scenicId: ids.scenicId, scenicSpotId: ids.scenicSpotId)
guard let url = data.qrcodeUrl?.trimmingCharacters(in: .whitespacesAndNewlines), !url.isEmpty else {
onShowMessage?("服务端未返回二维码图片地址")
return
}
try await ScenicQueueQRCodeSaver.saveImage(from: url)
onShowMessage?("保存成功")
} catch {
onShowMessage?((error as? LocalizedError)?.errorDescription ?? error.localizedDescription)
}
}
///
func save(api: ScenicQueueAPIProtocol) async {
highlightedInvalidFieldKeys = []
guard let ids = currentScenicAndSpotIdsForSelected() else {
highlightedInvalidFieldKeys = ["punchSpot"]
settingsTab = .basic
onShowMessage?("请选择打卡点")
notifyStateChange()
return
}
let validation = buildSaveValidation()
guard validation.messages.isEmpty else {
highlightedInvalidFieldKeys = validation.keys
settingsTab = tabForValidationKeys(validation.keys)
onShowMessage?(validation.messages.joined(separator: "\n"))
notifyStateChange()
return
}
let remark = customTTSText.trimmingCharacters(in: .whitespacesAndNewlines)
let request = ScenicQueueSaveSettingRequest(
scenicId: ids.scenicId,
scenicSpotId: ids.scenicSpotId,
photoEstimateMin: shootMinute,
photoEstimateSec: shootSecond,
firstNoticeThresholdPos: firstAheadCount,
firstNoticeSmsEnabled: firstSms ? 1 : 0,
firstNoticeCallEnabled: firstPhone ? 1 : 0,
secondNoticeThresholdPos: secondAheadCount,
secondNoticeSmsEnabled: secondSms ? 1 : 0,
secondNoticeCallEnabled: secondPhone ? 1 : 0,
countdownBroadcastIntervalSec: broadcastIntervalSec,
countdownReadableThresholdSec: countdownThresholdSec,
queueDistanceMeter: queueDistanceMeter,
queueTakeLimit: queueTakeLimit,
missCallRequeueOffset: missCallRequeueOffset,
showStartShootButton: showStartShootingButton ? 1 : 0,
autoCallNextCount: autoCallAheadCount,
businessStartTime: businessStartTime,
businessEndTime: businessEndTime,
voiceBroadcasts: presetVoices.enumerated().map { ScenicQueueVoiceBroadcastItem(content: $0.element, sortOrder: $0.offset + 1) },
status: businessOpen ? 1 : 0,
remark: remark.isEmpty ? nil : remark
)
do {
try await api.saveSetting(request)
appStore.scenicQueuePunchSpotId = String(ids.scenicSpotId)
appStore.scenicQueuePunchSpotName = selectedPunchSpotLabel
appStore.scenicQueueRemark = remark
appStore.saveScenicQueuePresetVoices(presetVoices)
appStore.saveScenicQueueSettingsSnapshot(currentSnapshot())
_ = try? await api.stats(scenicId: ids.scenicId, scenicSpotId: ids.scenicSpotId)
onShowMessage?("保存成功")
onNavigateBack?()
} catch {
onShowMessage?(error.localizedDescription)
}
}
private func fetchQueueSettingAfterPunchSpotSelected(_ spotId: String, api: ScenicQueueAPIProtocol) async {
guard let scenicId = Int64("\(appStore.currentScenicId)"),
let scenicSpotId = Int64(spotId),
scenicId > 0,
scenicSpotId > 0 else { return }
punchSpotSettingRequestGeneration += 1
let generation = punchSpotSettingRequestGeneration
do {
let data = try await api.setting(scenicId: scenicId, scenicSpotId: scenicSpotId)
guard generation == punchSpotSettingRequestGeneration,
selectedPunchSpotId == spotId,
data.exists,
let setting = data.setting else { return }
applyServerSettingToForm(setting)
} catch {
// Keep local form values if remote setting cannot be loaded.
}
}
private func applyServerSettingToForm(_ setting: ScenicQueueSettingItem) {
let fallback = ScenicQueueSettingsSnapshot(
showStartShootingButton: showStartShootingButton,
autoCallAheadCount: autoCallAheadCount,
quickCallButtonEnabled: quickCallButtonEnabled,
prepareCallButtonEnabled: prepareCallButtonEnabled
)
let snapshot = setting.toSnapshot(fallback: fallback)
apply(snapshot)
customTTSText = String((setting.remark ?? "").prefix(Limits.remarkMaxLen))
if let voices = setting.voiceBroadcasts {
presetVoices = voices
.sorted { ($0.sortOrder ?? Int.max) < ($1.sortOrder ?? Int.max) }
.compactMap { $0.content?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmptyTrimmed }
.prefix(5)
.map { $0 }
}
if let name = setting.scenicSpotName?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmptyTrimmed {
selectedPunchSpotLabel = name
}
highlightedInvalidFieldKeys = []
notifyStateChange()
}
private func apply(_ snapshot: ScenicQueueSettingsSnapshot) {
shootMinute = snapshot.shootMinute.clamped(to: Limits.shootMinute)
shootSecond = snapshot.shootSecond.clamped(to: Limits.shootSecond)
firstAheadCount = snapshot.firstAheadCount.clamped(to: Limits.ahead)
firstSms = snapshot.firstSms
firstPhone = snapshot.firstPhone
secondAheadCount = snapshot.secondAheadCount.clamped(to: Limits.ahead)
secondSms = snapshot.secondSms
secondPhone = snapshot.secondPhone
broadcastIntervalSec = snapshot.broadcastIntervalSec.clamped(to: Limits.broadcastInterval)
countdownThresholdSec = snapshot.countdownThresholdSec.clamped(to: Limits.readableThreshold)
queueDistanceMeter = snapshot.queueDistanceMeter.clamped(to: Limits.queueDistance)
queueTakeLimit = snapshot.queueTakeLimit.clamped(to: Limits.queueTakeLimit)
missCallRequeueOffset = snapshot.missCallRequeueOffset.clamped(to: Limits.missCallRequeueOffset)
showStartShootingButton = snapshot.showStartShootingButton
autoCallAheadCount = snapshot.autoCallAheadCount.clamped(to: Limits.autoCallAheadCount)
quickCallButtonEnabled = snapshot.quickCallButtonEnabled
prepareCallButtonEnabled = snapshot.prepareCallButtonEnabled
businessOpen = snapshot.businessOpen
businessStartTime = Self.normalizedTime(snapshot.businessStartTime, fallback: "10:00")
businessEndTime = Self.normalizedTime(snapshot.businessEndTime, fallback: "20:00")
}
private func currentSnapshot() -> ScenicQueueSettingsSnapshot {
ScenicQueueSettingsSnapshot(
shootMinute: shootMinute,
shootSecond: shootSecond,
firstAheadCount: firstAheadCount,
firstSms: firstSms,
firstPhone: firstPhone,
secondAheadCount: secondAheadCount,
secondSms: secondSms,
secondPhone: secondPhone,
broadcastIntervalSec: broadcastIntervalSec,
countdownThresholdSec: countdownThresholdSec,
queueDistanceMeter: queueDistanceMeter,
queueTakeLimit: queueTakeLimit,
missCallRequeueOffset: missCallRequeueOffset,
showStartShootingButton: showStartShootingButton,
autoCallAheadCount: autoCallAheadCount,
quickCallButtonEnabled: quickCallButtonEnabled,
prepareCallButtonEnabled: prepareCallButtonEnabled,
businessOpen: businessOpen,
businessStartTime: businessStartTime,
businessEndTime: businessEndTime
)
}
private func buildSaveValidation() -> (messages: [String], keys: Set<String>) {
var messages: [String] = []
var keys: Set<String> = []
if !Limits.shootMinute.contains(shootMinute) {
messages.append("拍摄时长:分钟须在 030且按 1 分钟递增")
keys.insert(ScenicQueueNumericFieldKey.shootMinute.rawValue)
}
if !Limits.shootSecond.contains(shootSecond) {
messages.append("拍摄时长:秒须在 059")
keys.insert(ScenicQueueNumericFieldKey.shootSecond.rawValue)
}
if shootMinute == 0 && shootSecond == 0 {
messages.append("拍摄时长须大于 0")
keys.insert(ScenicQueueNumericFieldKey.shootMinute.rawValue)
keys.insert(ScenicQueueNumericFieldKey.shootSecond.rawValue)
}
if !Limits.broadcastInterval.contains(broadcastIntervalSec) {
messages.append("播报间隔时间须在 4060 秒")
keys.insert(ScenicQueueNumericFieldKey.broadcastIntervalSec.rawValue)
}
if !Limits.readableThreshold.contains(countdownThresholdSec) {
messages.append("进入读秒倒计时阈值须在 1030 秒")
keys.insert(ScenicQueueNumericFieldKey.countdownReadableThresholdSec.rawValue)
}
return (messages, keys)
}
private func tabForValidationKeys(_ keys: Set<String>) -> ScenicQueueSettingsTab {
if keys.contains("punchSpot")
|| keys.contains(ScenicQueueNumericFieldKey.queueDistanceMeter.rawValue)
|| keys.contains(ScenicQueueNumericFieldKey.shootMinute.rawValue)
|| keys.contains(ScenicQueueNumericFieldKey.shootSecond.rawValue)
|| keys.contains(ScenicQueueNumericFieldKey.queueTakeLimit.rawValue)
|| keys.contains(ScenicQueueNumericFieldKey.missCallRequeueOffset.rawValue) {
return .basic
}
if keys.contains(ScenicQueueNumericFieldKey.firstNoticeAhead.rawValue)
|| keys.contains(ScenicQueueNumericFieldKey.secondNoticeAhead.rawValue) {
return .notify
}
return .voice
}
private func currentScenicAndSpotIdsForSelected() -> (scenicId: Int64, scenicSpotId: Int64)? {
guard let scenicId = Int64("\(appStore.currentScenicId)"), scenicId > 0,
let spotIdText = selectedPunchSpotId?.trimmingCharacters(in: .whitespacesAndNewlines),
let scenicSpotId = Int64(spotIdText), scenicSpotId > 0 else { return nil }
return (scenicId, scenicSpotId)
}
private static func normalizedTime(_ raw: String, fallback: String) -> String {
let text = raw.trimmingCharacters(in: .whitespacesAndNewlines)
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh_CN")
for format in ["HH:mm", "HH:mm:ss"] {
formatter.dateFormat = format
if let date = formatter.date(from: text) {
formatter.dateFormat = "HH:mm"
return formatter.string(from: date)
}
}
return fallback
}
private func notifyStateChange() {
onStateChange?()
}
}
private extension Int {
func clamped(to range: ClosedRange<Int>) -> Int {
Swift.min(Swift.max(self, range.lowerBound), range.upperBound)
}
}
private extension String {
var nonEmptyTrimmed: String? {
isEmpty ? nil : self
}
}

View File

@ -0,0 +1,682 @@
//
// ScenicQueueViewModel.swift
// suixinkan
//
import Foundation
/// ViewModel Android `ScenicQueueViewModel`
final class ScenicQueueViewModel {
private enum Constants {
static let pageSize = 10
static let typeCurrent = 1
static let typeFinished = 2
static let prepareCallLoopGapNanos: UInt64 = 800_000_000
}
private(set) var summary: ScenicQueueSummary = .empty
private(set) var currentQueue: [ScenicQueueTicket] = []
private(set) var skippedQueue: [ScenicQueueSkippedTicket] = []
private(set) var currentRefreshing = false
private(set) var skippedRefreshing = false
private(set) var currentLoadingMore = false
private(set) var skippedLoadingMore = false
private(set) var currentCanLoadMore = false
private(set) var skippedCanLoadMore = false
private(set) var queueGatePassed = false
private(set) var selectedPunchSpotLine = "--"
private(set) var shootingTimedQueueNo: String?
private(set) var shootingRemainSeconds = 0
private(set) var showStartShootingButton = true
private(set) var quickCallButtonEnabled = false
private(set) var prepareCallButtonEnabled = false
private(set) var prepareCallPlaying = false
private(set) var pendingSkip: ScenicQueuePendingSkip?
private(set) var pendingCall: ScenicQueuePendingCall?
private(set) var pendingFinish: ScenicQueuePendingFinish?
private(set) var pendingMark: ScenicQueuePendingMark?
private(set) var pendingRequeue: ScenicQueuePendingRequeue?
var onStateChange: (() -> Void)?
var onShowMessage: ((String) -> Void)?
var onRequireSettings: (() -> Void)?
var onNavigateSettings: (() -> Void)?
var onNavigateBack: (() -> Void)?
private let appStore: AppStore
private let ttsManager: ScenicQueueTTSManaging
private let socketClient: ScenicQueueSocketClient
private var currentListTotal = 0
private var skippedListTotal = 0
private var currentLastLoadedPage = 0
private var skippedLastLoadedPage = 0
private var pendingRemoteCalledRecordIds: Set<Int64> = []
private var handledRemoteCallEventIds: Set<String> = []
private var shootingTask: Task<Void, Never>?
private var prepareCallTask: Task<Void, Never>?
init(
appStore: AppStore = .shared,
ttsManager: ScenicQueueTTSManaging = AliyunNLSTTSManager.shared,
socketClient: ScenicQueueSocketClient = ScenicQueueSocketClient()
) {
self.appStore = appStore
self.ttsManager = ttsManager
self.socketClient = socketClient
self.socketClient.onMessage = { [weak self] message in
self?.handleSocketMessage(message)
}
refreshSelectedPunchSpotLine()
refreshQueueGateLocally()
}
deinit {
stopQueueStatsPolling()
shootingTask?.cancel()
prepareCallTask?.cancel()
ttsManager.stopQueueCallLoop()
ttsManager.stopCustomTextLoop()
}
/// gate
func refreshQueueGate(api: ScenicQueueAPIProtocol) async {
refreshSelectedPunchSpotLine()
refreshQueueGateLocally()
if queueGatePassed {
await syncQueueSettingFromServerIfMatchesLocal(api: api)
await refreshQueueStats(api: api)
await refreshCurrentQueue(api: api, reset: true)
await refreshSkippedQueue(api: api, reset: true)
await ttsManager.prepareQueueTTSEngine(api: api as? ScenicQueueAPI)
} else {
resetQueues()
onRequireSettings?()
}
}
/// WebSocket
func startQueueStatsPolling(api: ScenicQueueAPIProtocol) {
guard queueGatePassed,
let scenicId = Int64("\(appStore.currentScenicId)"),
let scenicSpotId = Int64(appStore.scenicQueuePunchSpotId),
scenicId > 0,
scenicSpotId > 0 else { return }
Task {
do {
let token = try await api.socketToken().socketToken
socketClient.connect(socketToken: token, scenicId: scenicId, scenicSpotId: scenicSpotId)
} catch {
onShowMessage?(error.localizedDescription)
}
}
}
/// WebSocket
func stopQueueStatsPolling() {
socketClient.disconnect()
}
///
func openSettings() {
if shootingTimedQueueNo != nil {
onShowMessage?("请先完成上一位拍摄,才可以进入设置页面。")
return
}
onNavigateSettings?()
}
/// 退
func exitQueueModule() {
onNavigateBack?()
}
///
func refreshCurrentQueue(api: ScenicQueueAPIProtocol, reset: Bool = true) async {
await loadHomeList(api: api, type: Constants.typeCurrent, page: 1, append: false, isRefresh: reset)
}
///
func loadMoreCurrentQueue(api: ScenicQueueAPIProtocol) async {
guard currentCanLoadMore, !currentRefreshing, !currentLoadingMore else { return }
await loadHomeList(api: api, type: Constants.typeCurrent, page: currentLastLoadedPage + 1, append: true, isRefresh: false)
}
///
func refreshSkippedQueue(api: ScenicQueueAPIProtocol, reset: Bool = true) async {
await loadHomeList(api: api, type: Constants.typeFinished, page: 1, append: false, isRefresh: reset)
}
///
func loadMoreSkippedQueue(api: ScenicQueueAPIProtocol) async {
guard skippedCanLoadMore, !skippedRefreshing, !skippedLoadingMore else { return }
await loadHomeList(api: api, type: Constants.typeFinished, page: skippedLastLoadedPage + 1, append: true, isRefresh: false)
}
///
func refreshQueueStats(api: ScenicQueueAPIProtocol) async {
guard let ids = currentScenicAndSpotIds() else { return }
do {
let data = try await api.stats(scenicId: ids.scenicId, scenicSpotId: ids.scenicSpotId)
let avg = data.avgWaitMin.isFinite ? max(0, Int(data.avgWaitMin.rounded())) : 0
summary = ScenicQueueSummary(peopleInQueue: max(0, data.queueCount), avgWaitMinutes: avg)
notifyStateChange()
} catch {
// Android ignores stats errors silently.
}
}
///
func onTicketMarkClick(recordId: Int64, queueNo: String, uid: Int64) {
guard recordId > 0, uid > 0, !queueNo.isEmpty,
let ticket = currentQueue.first(where: { $0.recordId == recordId }) else { return }
pendingMark = ScenicQueuePendingMark(
uid: uid,
queueNo: queueNo,
phoneMasked: ticket.phoneMasked,
markAsFreelancePhotog: ticket.markAsFreelancePhotog
)
notifyStateChange()
}
func dismissMarkDialog() {
pendingMark = nil
notifyStateChange()
}
///
func confirmUserMark(api: ScenicQueueAPIProtocol, markAsFreelancePhotog: Bool, queueBanDays: Int) async {
guard let pendingMark else { return }
guard appStore.currentScenicId > 0 else {
onShowMessage?("请先选择景区")
return
}
let request = ScenicQueueUserMarkRequest(
uid: pendingMark.uid,
scenicId: Int64(appStore.currentScenicId),
markAsFreelancePhotog: markAsFreelancePhotog ? 1 : 0,
queueBanDays: markAsFreelancePhotog ? min(max(queueBanDays, 0), 999) : nil,
operatorId: Int(appStore.userId)
)
do {
try await api.userMark(request)
dismissMarkDialog()
await refreshCurrentQueue(api: api, reset: true)
} catch {
onShowMessage?(error.localizedDescription)
}
}
func requestSkipTicket(recordId: Int64, queueNo: String) {
guard recordId > 0, !queueNo.isEmpty else { return }
pendingSkip = ScenicQueuePendingSkip(recordId: recordId, queueNo: queueNo)
notifyStateChange()
}
func dismissSkipDialog() {
pendingSkip = nil
notifyStateChange()
}
///
func confirmSkipTicket(api: ScenicQueueAPIProtocol) async {
guard let pending = pendingSkip else { return }
dismissSkipDialog()
ttsManager.stopQueueCallLoop()
do {
_ = try await api.pass(recordId: pending.recordId)
clearShootingSession(for: pending.queueNo)
removeTicketFromCurrentList(recordId: pending.recordId)
await refreshQueueStats(api: api)
await refreshSkippedQueue(api: api, reset: true)
} catch {
onShowMessage?(error.localizedDescription)
}
}
func requestFinishConfirm(recordId: Int64, queueNo: String) {
guard recordId > 0, !queueNo.isEmpty else { return }
if let active = shootingTimedQueueNo, active != queueNo {
onShowMessage?("请先完成上一位拍摄。")
return
}
pendingFinish = ScenicQueuePendingFinish(recordId: recordId, queueNo: queueNo)
notifyStateChange()
}
func dismissFinishDialog() {
pendingFinish = nil
notifyStateChange()
}
///
func confirmFinishTicket(api: ScenicQueueAPIProtocol) async {
guard let pending = pendingFinish else { return }
dismissFinishDialog()
await finishTicket(api: api, pending: pending)
}
func requestRequeueConfirm(recordId: Int64, queueNo: String) {
guard recordId > 0, !queueNo.isEmpty else { return }
pendingRequeue = ScenicQueuePendingRequeue(recordId: recordId, queueNo: queueNo)
notifyStateChange()
}
func dismissRequeueDialog() {
pendingRequeue = nil
notifyStateChange()
}
///
func confirmRequeueTicket(api: ScenicQueueAPIProtocol) async {
guard let pending = pendingRequeue else { return }
dismissRequeueDialog()
guard let operatorId = Int(appStore.userId), operatorId > 0 else {
onShowMessage?("请先登录")
return
}
do {
try await api.requeueInsertBefore(recordId: pending.recordId, operatorId: operatorId)
await refreshQueueStats(api: api)
await refreshCurrentQueue(api: api, reset: true)
await refreshSkippedQueue(api: api, reset: true)
} catch {
onShowMessage?(error.localizedDescription)
}
}
func requestCallConfirm(recordId: Int64, queueNo: String, isRecall: Bool = false) {
if shootingTimedQueueNo != nil {
onShowMessage?("请先完成上一位拍摄,再进行叫号。")
return
}
guard recordId > 0, !queueNo.isEmpty else { return }
pendingCall = ScenicQueuePendingCall(recordId: recordId, queueNo: queueNo, isRecall: isRecall)
notifyStateChange()
}
func dismissCallConfirmDialog() {
pendingCall = nil
notifyStateChange()
}
///
func confirmCallTicket(api: ScenicQueueAPIProtocol) async {
guard let pending = pendingCall else { return }
dismissCallConfirmDialog()
stopPrepareCallPlayback()
await callTicketDirectly(api: api, recordId: pending.recordId, queueNo: pending.queueNo)
}
///
func quickCallFirstTicket(api: ScenicQueueAPIProtocol) async {
if shootingTimedQueueNo != nil {
onShowMessage?("请先完成上一位拍摄,再进行叫号。")
return
}
guard let first = currentQueue.first else {
onShowMessage?("暂无可叫号的排队用户")
return
}
stopPrepareCallPlayback()
await callTicketDirectly(api: api, recordId: first.recordId, queueNo: first.queueNo)
}
///
func togglePrepareCallPlayback() {
if prepareCallPlaying {
stopPrepareCallPlayback()
return
}
let queueNos = prepareCallQueueNos()
guard !queueNos.isEmpty else {
onShowMessage?("暂无可播报的排队用户")
return
}
prepareCallTask?.cancel()
prepareCallPlaying = true
notifyStateChange()
prepareCallTask = Task { [weak self] in
guard let self else { return }
while !Task.isCancelled {
let latest = self.prepareCallQueueNos()
if latest.isEmpty { break }
_ = await self.ttsManager.speakPlainTextOnce(self.prepareCallAnnouncementText(latest))
try? await Task.sleep(nanoseconds: Constants.prepareCallLoopGapNanos)
}
self.prepareCallPlaying = false
self.prepareCallTask = nil
self.notifyStateChange()
}
}
///
func startShooting(api: ScenicQueueAPIProtocol, recordId: Int64, queueNo: String) {
guard recordId > 0, !queueNo.isEmpty, shootingTimedQueueNo == nil else { return }
stopPrepareCallPlayback()
ttsManager.stopQueueCallLoop()
let timing = resolveShootingTiming()
guard timing.totalSeconds > 0 else {
onShowMessage?("请先在排队配置中设置拍摄时长")
return
}
onShowMessage?("开始计时拍摄")
shootingTimedQueueNo = queueNo
shootingRemainSeconds = timing.totalSeconds
notifyStateChange()
shootingTask?.cancel()
shootingTask = Task { [weak self] in
guard let self else { return }
await self.speakFollowingTickets(after: queueNo)
let start = Date()
while !Task.isCancelled {
let elapsed = Int(Date().timeIntervalSince(start).rounded(.down))
let remain = max(0, timing.totalSeconds - elapsed)
self.shootingRemainSeconds = remain
self.notifyStateChange()
if remain <= 0 { break }
if remain == timing.readableThresholdSeconds {
_ = await self.ttsManager.speakPlainTextOnce("当前剩余拍摄时间还剩\(remain)")
} else if remain < timing.readableThresholdSeconds && remain > 0 {
_ = await self.ttsManager.speakPlainTextOnce("\(remain)")
} else if timing.intervalSeconds > 0 && elapsed > 0 && elapsed % timing.intervalSeconds == 0 {
_ = await self.ttsManager.speakPlainTextOnce(self.shootingRemainAnnouncementText(queueNo: queueNo, remainSeconds: remain))
}
try? await Task.sleep(nanoseconds: 1_000_000_000)
}
self.ttsManager.interruptShootingAnnouncement()
self.shootingTimedQueueNo = nil
self.shootingRemainSeconds = 0
self.shootingTask = nil
self.notifyStateChange()
if !Task.isCancelled {
await self.finishTicket(api: api, pending: ScenicQueuePendingFinish(recordId: recordId, queueNo: queueNo))
}
}
}
private func refreshSelectedPunchSpotLine() {
selectedPunchSpotLine = appStore.hasScenicQueuePunchSpotSaved()
? appStore.scenicQueuePunchSpotName.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty ?? "--"
: "--"
refreshShootingCallConfig()
}
private func refreshQueueGateLocally() {
queueGatePassed = appStore.hasScenicQueuePunchSpotSaved()
}
private func refreshShootingCallConfig() {
let snapshot = appStore.scenicQueueSettingsSnapshot() ?? ScenicQueueSettingsSnapshot()
showStartShootingButton = snapshot.showStartShootingButton
quickCallButtonEnabled = snapshot.quickCallButtonEnabled
prepareCallButtonEnabled = snapshot.prepareCallButtonEnabled
}
private func syncQueueSettingFromServerIfMatchesLocal(api: ScenicQueueAPIProtocol) async {
guard let ids = currentScenicAndSpotIds() else { return }
do {
let data = try await api.setting(scenicId: ids.scenicId, scenicSpotId: ids.scenicSpotId)
guard data.exists, let setting = data.setting,
setting.scenicId == nil || setting.scenicId == ids.scenicId,
setting.scenicSpotId == nil || setting.scenicSpotId == ids.scenicSpotId else { return }
let local = appStore.scenicQueueSettingsSnapshot() ?? ScenicQueueSettingsSnapshot()
appStore.saveScenicQueueSettingsSnapshot(setting.toSnapshot(fallback: local))
appStore.scenicQueueRemark = setting.remark ?? ""
if let voices = setting.voiceBroadcasts {
appStore.saveScenicQueuePresetVoices(
voices
.sorted { ($0.sortOrder ?? Int.max) < ($1.sortOrder ?? Int.max) }
.compactMap { $0.content?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty }
)
}
if let name = setting.scenicSpotName?.trimmingCharacters(in: .whitespacesAndNewlines).nonEmpty {
appStore.scenicQueuePunchSpotName = name
selectedPunchSpotLine = name
}
refreshShootingCallConfig()
notifyStateChange()
} catch {
// Android keeps local snapshot if sync fails.
}
}
private func loadHomeList(api: ScenicQueueAPIProtocol, type: Int, page: Int, append: Bool, isRefresh: Bool) async {
guard let ids = currentScenicAndSpotIds() else { return }
let isCurrent = type == Constants.typeCurrent
if isRefresh {
if isCurrent {
guard !currentRefreshing else { return }
currentRefreshing = true
} else {
guard !skippedRefreshing else { return }
skippedRefreshing = true
}
} else {
if isCurrent {
guard !currentLoadingMore else { return }
currentLoadingMore = true
} else {
guard !skippedLoadingMore else { return }
skippedLoadingMore = true
}
}
notifyStateChange()
defer {
if isRefresh {
if isCurrent { currentRefreshing = false } else { skippedRefreshing = false }
} else {
if isCurrent { currentLoadingMore = false } else { skippedLoadingMore = false }
}
notifyStateChange()
}
do {
let data = try await api.home(
scenicId: ids.scenicId,
scenicSpotId: ids.scenicSpotId,
type: type,
page: page,
pageSize: Constants.pageSize
)
guard let block = data.list else { return }
if isCurrent {
let mapped = block.list.map { $0.toCurrentTicket() }
currentQueue = append ? appendUnique(existing: currentQueue, incoming: mapped, key: \.recordId) : mapped
currentListTotal = max(0, block.total)
currentLastLoadedPage = max(1, block.page)
currentCanLoadMore = currentQueue.count < currentListTotal && !block.list.isEmpty
consumePendingRemoteCalledTickets()
} else {
let mapped = block.list.map { $0.toSkippedTicket() }
skippedQueue = append ? appendUnique(existing: skippedQueue, incoming: mapped, key: \.recordId) : mapped
skippedListTotal = max(0, block.total)
skippedLastLoadedPage = max(1, block.page)
skippedCanLoadMore = skippedQueue.count < skippedListTotal && !block.list.isEmpty
}
} catch {
onShowMessage?(error.localizedDescription)
}
}
private func handleSocketMessage(_ message: ScenicQueueSocketMessage) {
guard let params = message.data?.params,
let changedSpotId = params.scenicSpotId,
let currentSpotId = Int64(appStore.scenicQueuePunchSpotId),
changedSpotId == currentSpotId else { return }
switch message.data?.action {
case ScenicQueueSocketAction.queueUpdated.rawValue:
NotificationCenter.default.post(name: NotificationName.scenicQueueDidUpdate, object: nil)
case ScenicQueueSocketAction.ticketCalled.rawValue:
handleRemoteTicketCalled(params)
NotificationCenter.default.post(name: NotificationName.scenicQueueDidUpdate, object: nil)
default:
break
}
}
private func handleRemoteTicketCalled(_ params: ScenicQueueSocketParams) {
guard let recordId = params.recordId, recordId > 0 else { return }
if let myUid = Int64(appStore.userId), let operatorUid = params.operatorUid, myUid == operatorUid {
return
}
let eventId = params.eventId?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if !eventId.isEmpty, handledRemoteCallEventIds.contains(eventId) {
return
}
if !eventId.isEmpty {
handledRemoteCallEventIds.insert(eventId)
}
pendingRemoteCalledRecordIds.insert(recordId)
}
private func consumePendingRemoteCalledTickets() {
guard let called = currentQueue.first(where: { pendingRemoteCalledRecordIds.contains($0.recordId) && $0.status == .called }) else { return }
pendingRemoteCalledRecordIds.remove(called.recordId)
stopPrepareCallPlayback()
ttsManager.startQueueCallLoop(queueNo: called.queueNo)
}
private func callTicketDirectly(api: ScenicQueueAPIProtocol, recordId: Int64, queueNo: String) async {
do {
let data = try await api.call(recordId: recordId)
applyCallSuccessLocally(recordId: recordId, queueNo: queueNo, statusText: data.statusText)
} catch {
onShowMessage?(error.localizedDescription)
}
}
private func applyCallSuccessLocally(recordId: Int64, queueNo: String, statusText: String) {
let shouldShowStartButton = currentShowStartShootingButton()
if shouldShowStartButton {
ttsManager.startQueueCallLoop(queueNo: queueNo)
}
currentQueue = currentQueue.map { ticket in
ticket.recordId == recordId || ticket.queueNo == queueNo
? ticket.markedCalled(statusText: statusText)
: ticket
}
notifyStateChange()
}
private func finishTicket(api: ScenicQueueAPIProtocol, pending: ScenicQueuePendingFinish) async {
do {
let data = try await api.finish(recordId: pending.recordId)
ttsManager.stopQueueCallLoop()
clearShootingSession(for: pending.queueNo)
removeTicketFromCurrentList(recordId: pending.recordId)
if !data.statusText.isEmpty {
onShowMessage?(data.statusText)
}
await refreshQueueStats(api: api)
await refreshSkippedQueue(api: api, reset: true)
} catch {
onShowMessage?(error.localizedDescription)
}
}
private func removeTicketFromCurrentList(recordId: Int64) {
currentQueue.removeAll { $0.recordId == recordId }
currentListTotal = max(0, currentListTotal - 1)
currentCanLoadMore = currentListTotal > 0 && currentQueue.count < currentListTotal
notifyStateChange()
}
private func clearShootingSession(for queueNo: String) {
guard shootingTimedQueueNo == queueNo else { return }
shootingTask?.cancel()
shootingTask = nil
ttsManager.interruptShootingAnnouncement()
shootingTimedQueueNo = nil
shootingRemainSeconds = 0
notifyStateChange()
}
private func stopPrepareCallPlayback() {
prepareCallTask?.cancel()
prepareCallTask = nil
ttsManager.interruptShootingAnnouncement()
prepareCallPlaying = false
notifyStateChange()
}
private func prepareCallQueueNos() -> [String] {
let active = shootingTimedQueueNo?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
return currentQueue
.map { $0.queueNo.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty && (active.isEmpty || $0 != active) }
.prefix(3)
.map { $0 }
}
private func prepareCallAnnouncementText(_ queueNos: [String]) -> String {
let joined = queueNos.map(AliyunNLSTTSManager.formatQueueNoForTTS).joined(separator: "")
return "\(joined),请提前做好拍摄准备。"
}
private func resolveShootingTiming() -> (totalSeconds: Int, intervalSeconds: Int, readableThresholdSeconds: Int) {
let snapshot = appStore.scenicQueueSettingsSnapshot() ?? ScenicQueueSettingsSnapshot()
let total = max(0, snapshot.shootMinute * 60 + snapshot.shootSecond)
let interval = (40...60).contains(snapshot.broadcastIntervalSec) ? snapshot.broadcastIntervalSec : 50
let readable = (10...30).contains(snapshot.countdownThresholdSec) ? snapshot.countdownThresholdSec : 15
return (total, interval, readable)
}
private func currentShowStartShootingButton() -> Bool {
refreshShootingCallConfig()
return showStartShootingButton
}
private func speakFollowingTickets(after queueNo: String) async {
let count = (appStore.scenicQueueSettingsSnapshot() ?? ScenicQueueSettingsSnapshot()).autoCallAheadCount.clamped(to: 0...5)
guard count > 0, let index = currentQueue.firstIndex(where: { $0.queueNo == queueNo }) else { return }
let nextNos = currentQueue.dropFirst(index + 1).prefix(count).map(\.queueNo).filter { !$0.isEmpty }
guard !nextNos.isEmpty else { return }
_ = await ttsManager.speakPlainTextOnce("\(nextNos.map(AliyunNLSTTSManager.formatQueueNoForTTS).joined(separator: ""))提前做好拍摄准备。")
}
private func shootingRemainAnnouncementText(queueNo: String, remainSeconds: Int) -> String {
"\(AliyunNLSTTSManager.formatQueueNoForTTS(queueNo)),当前剩余拍摄时间还剩\(remainSeconds)"
}
private func currentScenicAndSpotIds() -> (scenicId: Int64, scenicSpotId: Int64)? {
let scenicId = Int64(appStore.currentScenicId)
guard scenicId > 0,
let scenicSpotId = Int64(appStore.scenicQueuePunchSpotId),
scenicSpotId > 0 else { return nil }
return (scenicId, scenicSpotId)
}
private func resetQueues() {
summary = .empty
currentQueue = []
skippedQueue = []
currentListTotal = 0
skippedListTotal = 0
currentLastLoadedPage = 0
skippedLastLoadedPage = 0
currentCanLoadMore = false
skippedCanLoadMore = false
notifyStateChange()
}
private func appendUnique<Item, Key: Hashable>(existing: [Item], incoming: [Item], key: KeyPath<Item, Key>) -> [Item] {
var seen = Set(existing.map { $0[keyPath: key] })
return existing + incoming.filter { seen.insert($0[keyPath: key]).inserted }
}
private func notifyStateChange() {
onStateChange?()
}
}
private extension String {
var nonEmpty: String? {
isEmpty ? nil : self
}
}
private extension Int {
func clamped(to range: ClosedRange<Int>) -> Int {
Swift.min(Swift.max(self, range.lowerBound), range.upperBound)
}
}