Files
suixinkan_ios_new/suixinkan/Features/Profile/ViewModels/AccountSwitchViewModel.swift
汉秋 26f4d0e671 Migrate from iOS 17 Observation to iOS 16-compatible Combine architecture.
Lower deployment target to iOS 16, replace @Observable with ObservableObject, add navigation and UI compatibility shims, and include login smoke UI tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-26 10:16:35 +08:00

78 lines
2.6 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.

//
// AccountSwitchViewModel.swift
// suixinkan
//
// Created by Codex on 2026/6/22.
//
import Foundation
import Combine
@MainActor
/// ViewModel
final class AccountSwitchViewModel: ObservableObject {
@Published private(set) var accounts: [AccountSwitchAccount] = []
@Published var selectedAccountId: String?
@Published private(set) var loading = false
@Published private(set) var switching = false
@Published private var didLoad = false
///
var selectedAccount: AccountSwitchAccount? {
accounts.first { $0.id == selectedAccountId }
}
///
func load(api: ProfileAPI, force: Bool = false, currentAccountId: String? = nil) async throws {
guard force || !didLoad else { return }
didLoad = true
loading = true
defer { loading = false }
let response = try await api.switchableAccounts()
accounts = response.accounts.filter { $0.businessUserId > 0 }
selectedAccountId = accounts.first(where: { $0.isCurrent || isCurrent($0, currentAccountId: currentAccountId) })?.id
?? accounts.first?.id
}
///
func select(_ account: AccountSwitchAccount) {
selectedAccountId = account.id
}
/// set-user token
func switchAccount(_ account: AccountSwitchAccount, api: AuthAPI) async throws -> V9AuthResponse {
guard !switching else {
throw AccountSwitchError.submitting
}
guard account.businessUserId > 0 else {
throw AccountSwitchError.invalidAccount
}
switching = true
defer { switching = false }
return try await api.setUser(account.toSetUserRequest())
}
///
func isCurrent(_ account: AccountSwitchAccount, currentAccountId: String?) -> Bool {
guard let currentAccountId else { return false }
return account.id == currentAccountId || String(account.businessUserId) == currentAccountId
}
}
///
enum AccountSwitchError: LocalizedError, Equatable {
case submitting
case invalidAccount
var errorDescription: String? {
switch self {
case .submitting:
"账号正在切换,请稍候"
case .invalidAccount:
"账号信息异常,请重新选择账号"
}
}
}