Initial commit: suixinkan_ios UIKit rewrite project.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
42
suixinkan_ios/Features/Auth/API/AuthAPI.swift
Normal file
42
suixinkan_ios/Features/Auth/API/AuthAPI.swift
Normal file
@ -0,0 +1,42 @@
|
||||
//
|
||||
// AuthAPI.swift
|
||||
// suixinkan
|
||||
//
|
||||
// Created by Codex on 2026/6/18.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
@MainActor
|
||||
/// 登录认证 API,封装 v9 登录和账号选择相关接口。
|
||||
final class AuthAPI {
|
||||
private let client: APIClient
|
||||
|
||||
/// 初始化登录 API,并注入共享网络客户端。
|
||||
init(client: APIClient) {
|
||||
self.client = client
|
||||
}
|
||||
|
||||
/// 使用手机号和密码发起 v9 登录,返回临时 token 及可选账号列表。
|
||||
func login(username: String, password: String) async throws -> V9AuthResponse {
|
||||
try await client.send(
|
||||
APIRequest(
|
||||
method: .post,
|
||||
path: "/api/app/v9/login",
|
||||
body: LoginRequest(username: username, password: password)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// 选择具体景区或门店账号,换取正式登录 token。
|
||||
func setUser(_ request: SetUserRequest, tokenOverride: String? = nil) async throws -> V9AuthResponse {
|
||||
try await client.send(
|
||||
APIRequest(
|
||||
method: .post,
|
||||
path: "/api/app/v9/set-user",
|
||||
body: request
|
||||
),
|
||||
tokenOverride: tokenOverride
|
||||
)
|
||||
}
|
||||
}
|
||||
63
suixinkan_ios/Features/Auth/Auth.md
Normal file
63
suixinkan_ios/Features/Auth/Auth.md
Normal file
@ -0,0 +1,63 @@
|
||||
# Auth 模块业务逻辑
|
||||
|
||||
## 模块职责
|
||||
|
||||
Auth 模块负责登录页、手机号密码登录、多账号选择和账号选择后的正式登录确认。
|
||||
|
||||
该模块只处理登录流程本身:
|
||||
- 表单输入、校验和协议确认。
|
||||
- 调用 v9 登录接口获取临时 token 和账号列表。
|
||||
- 单账号时自动调用 set-user。
|
||||
- 多账号时展示账号选择页。
|
||||
- 选择账号后调用 set-user 换取正式 token。
|
||||
|
||||
正式 token 存储、账号快照和全局登录态写入由 App 模块的 `AuthSessionCoordinator` 统一处理。
|
||||
|
||||
## 核心对象
|
||||
|
||||
- `LoginView`:登录页 UI,展示手机号、密码、协议确认和登录按钮。
|
||||
- `AccountSelectionView`:多账号选择弹窗,展示景区账号和门店账号。
|
||||
- `LoginViewModel`:维护表单状态、校验状态、登录请求状态和多账号选择状态。
|
||||
- `AuthAPI`:封装 `/api/app/v9/login` 和 `/api/app/v9/set-user`。
|
||||
- `LoginRequest`:登录请求体。
|
||||
- `SetUserRequest`:账号选择请求体。
|
||||
- `V9AuthResponse`:v9 登录和 set-user 响应。
|
||||
- `V9ScenicUser` / `V9StoreUser`:后端返回的景区账号和门店账号。
|
||||
- `AccountSwitchAccount`:统一后的可选择账号模型。
|
||||
|
||||
## 登录流程
|
||||
|
||||
1. 用户输入手机号和密码。
|
||||
2. `LoginViewModel.validateForLogin` 校验手机号、密码和协议勾选状态。
|
||||
3. 未勾选协议时,`LoginView` 弹出协议确认 Sheet。
|
||||
4. 校验通过后,`LoginViewModel.login` 调用 `AuthAPI.login`。
|
||||
5. 登录接口返回临时 token 和可用账号列表。
|
||||
6. `LoginViewModel` 过滤掉业务账号 ID 无效的账号。
|
||||
7. 没有可用账号时抛出 `LoginFlowError.noAvailableAccount`。
|
||||
8. 只有一个账号时,自动调用 `AuthAPI.setUser`,并返回 `.completed`。
|
||||
9. 多个账号时,保存 `AccountSelectionPayload`,并返回 `.needsAccountSelection`。
|
||||
10. `LoginView` 展示 `AccountSelectionView`。
|
||||
11. 用户确认账号后,`LoginViewModel.selectAccount` 使用临时 token 调用 set-user。
|
||||
12. set-user 返回正式 token 后,`LoginView` 调用 `AuthSessionCoordinator.completeLogin` 写入 token,并同步用户资料、角色权限、景区和门店。
|
||||
|
||||
## 账号模型转换
|
||||
|
||||
后端景区账号和门店账号字段不完全一致,统一转换为 `AccountSwitchAccount`:
|
||||
- 景区账号通过 `ssUserId`、`scenicUserId`、`userId`、`id` 兜底生成业务账号 ID。
|
||||
- 门店账号通过 `storeUserId`、`userId`、`id` 兜底生成业务账号 ID。
|
||||
- `AccountSwitchAccount.toSetUserRequest` 根据账号类型生成 `store_user_id` 或 `ss_user_id`。
|
||||
|
||||
`V9AuthResponse` 还会派生:
|
||||
- `accounts`:合并后的账号选择列表。
|
||||
- `primaryProfile`:登录后用于全局展示的账号资料。
|
||||
- `scenicScopes`:当前账号可用景区作用域。
|
||||
- `storeScopes`:当前账号可用门店作用域。
|
||||
|
||||
## 缓存规则
|
||||
|
||||
Auth 模块不直接写缓存。登录成功后的缓存由 `AuthSessionCoordinator` 负责:
|
||||
- 正式 token 写 Keychain。
|
||||
- 上次手机号和协议状态写 UserDefaults。
|
||||
- 账号资料、当前角色和业务作用域写入账号快照。
|
||||
|
||||
临时 token 只存在于 `AccountSelectionPayload`,不落盘。
|
||||
409
suixinkan_ios/Features/Auth/Models/AuthModels.swift
Normal file
409
suixinkan_ios/Features/Auth/Models/AuthModels.swift
Normal file
@ -0,0 +1,409 @@
|
||||
//
|
||||
// AuthModels.swift
|
||||
// suixinkan
|
||||
//
|
||||
// Created by Codex on 2026/6/18.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// 登录请求实体,表示手机号密码登录接口需要的参数。
|
||||
struct LoginRequest: Encodable {
|
||||
let username: String
|
||||
let type: Int
|
||||
let password: String
|
||||
let mobile: String
|
||||
let code: String
|
||||
|
||||
/// 创建手机号密码登录请求,并填充后端要求的默认字段。
|
||||
init(username: String, password: String) {
|
||||
self.username = username
|
||||
self.type = 1
|
||||
self.password = password
|
||||
self.mobile = ""
|
||||
self.code = ""
|
||||
}
|
||||
}
|
||||
|
||||
/// 账号选择请求实体,表示 set-user 接口需要的景区账号或门店账号 ID。
|
||||
struct SetUserRequest: Encodable, Equatable {
|
||||
let storeUserId: Int?
|
||||
let ssUserId: Int?
|
||||
|
||||
/// set-user 请求的 JSON 字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case storeUserId = "store_user_id"
|
||||
case ssUserId = "ss_user_id"
|
||||
}
|
||||
|
||||
/// 创建账号选择请求,门店账号传 storeUserId,景区账号传 ssUserId。
|
||||
init(storeUserId: Int? = nil, ssUserId: Int? = nil) {
|
||||
self.storeUserId = storeUserId
|
||||
self.ssUserId = ssUserId
|
||||
}
|
||||
}
|
||||
|
||||
/// 可切换账号实体,统一表示登录返回的景区账号和门店账号。
|
||||
struct AccountSwitchAccount: Identifiable, Hashable {
|
||||
let accountType: String
|
||||
let businessUserId: Int
|
||||
let title: String
|
||||
let subtitle: String
|
||||
let phone: String
|
||||
let avatar: String
|
||||
let scenicName: String
|
||||
let storeId: Int?
|
||||
let storeName: String
|
||||
let scenicId: Int?
|
||||
let isCurrent: Bool
|
||||
|
||||
var id: String {
|
||||
"\(accountType)_\(businessUserId)"
|
||||
}
|
||||
|
||||
var isStoreUser: Bool {
|
||||
accountType == V9StoreUser.accountTypeValue
|
||||
}
|
||||
|
||||
var accountTypeLabel: String {
|
||||
isStoreUser ? "门店账号" : "景区账号"
|
||||
}
|
||||
|
||||
/// 转换为 set-user 接口请求参数。
|
||||
func toSetUserRequest() -> SetUserRequest {
|
||||
if isStoreUser {
|
||||
return SetUserRequest(storeUserId: businessUserId)
|
||||
}
|
||||
return SetUserRequest(ssUserId: businessUserId)
|
||||
}
|
||||
}
|
||||
|
||||
/// 登录账号选择载荷,保存临时 token 和待用户选择的账号列表。
|
||||
struct AccountSelectionPayload: Equatable, Identifiable {
|
||||
let id = UUID()
|
||||
let tempToken: String
|
||||
let accounts: [AccountSwitchAccount]
|
||||
|
||||
var hasTempToken: Bool {
|
||||
!tempToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
}
|
||||
}
|
||||
|
||||
/// v9 登录响应实体,包含 token、景区账号列表和门店账号列表。
|
||||
struct V9AuthResponse: Decodable, Equatable {
|
||||
let token: String
|
||||
let scenicUsers: [V9ScenicUser]
|
||||
let storeUsers: [V9StoreUser]
|
||||
|
||||
/// 合并景区账号和门店账号,供账号选择页展示。
|
||||
var accounts: [AccountSwitchAccount] {
|
||||
scenicUsers.map { $0.toAccountSwitchAccount() } + storeUsers.map { $0.toAccountSwitchAccount() }
|
||||
}
|
||||
|
||||
/// 提取当前或首个账号作为全局账号资料。
|
||||
var primaryProfile: AccountProfile? {
|
||||
if let storeUser = storeUsers.first(where: \.isCurrent) ?? storeUsers.first {
|
||||
return AccountProfile(
|
||||
userId: String(storeUser.userId),
|
||||
displayName: storeUser.displayName,
|
||||
phone: storeUser.phone.nonEmpty,
|
||||
avatarURL: storeUser.avatar.nonEmpty
|
||||
)
|
||||
}
|
||||
|
||||
if let scenicUser = scenicUsers.first(where: \.isCurrent) ?? scenicUsers.first {
|
||||
return AccountProfile(
|
||||
userId: String(scenicUser.userId),
|
||||
displayName: scenicUser.displayName,
|
||||
phone: scenicUser.phone.nonEmpty,
|
||||
avatarURL: nil
|
||||
)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
/// 提取登录响应中的景区作用域,并按当前账号优先排序。
|
||||
var scenicScopes: [BusinessScope] {
|
||||
var seen = Set<Int>()
|
||||
let scenicFromScenicUsers = scenicUsers
|
||||
.sorted { $0.isCurrent && !$1.isCurrent }
|
||||
.compactMap { user -> BusinessScope? in
|
||||
guard user.scenicId > 0, seen.insert(user.scenicId).inserted else { return nil }
|
||||
return BusinessScope(id: user.scenicId, name: user.scenicName, kind: .scenic)
|
||||
}
|
||||
let scenicFromStoreUsers = storeUsers
|
||||
.sorted { $0.isCurrent && !$1.isCurrent }
|
||||
.compactMap { user -> BusinessScope? in
|
||||
guard user.scenicId > 0, seen.insert(user.scenicId).inserted else { return nil }
|
||||
return BusinessScope(id: user.scenicId, name: user.scenicName, kind: .scenic)
|
||||
}
|
||||
return scenicFromScenicUsers + scenicFromStoreUsers
|
||||
}
|
||||
|
||||
/// 提取登录响应中的门店作用域,并按当前账号优先排序。
|
||||
var storeScopes: [BusinessScope] {
|
||||
var seen = Set<Int>()
|
||||
return storeUsers
|
||||
.sorted { $0.isCurrent && !$1.isCurrent }
|
||||
.compactMap { user -> BusinessScope? in
|
||||
guard user.storeId > 0, seen.insert(user.storeId).inserted else { return nil }
|
||||
return BusinessScope(
|
||||
id: user.storeId,
|
||||
name: user.storeName,
|
||||
kind: .store,
|
||||
parentScenicId: user.scenicId > 0 ? user.scenicId : nil
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// v9 登录响应的 JSON 字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case token
|
||||
case scenicUsers = "scenic_users"
|
||||
case storeUsers = "store_users"
|
||||
}
|
||||
|
||||
/// 创建空响应或测试响应。
|
||||
init(token: String = "", scenicUsers: [V9ScenicUser] = [], storeUsers: [V9StoreUser] = []) {
|
||||
self.token = token
|
||||
self.scenicUsers = scenicUsers
|
||||
self.storeUsers = storeUsers
|
||||
}
|
||||
|
||||
/// 自定义解码,兼容后端账号数组缺失的情况。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
token = try container.decodeLossyString(forKey: .token)
|
||||
scenicUsers = (try? container.decodeIfPresent([V9ScenicUser].self, forKey: .scenicUsers)) ?? []
|
||||
storeUsers = (try? container.decodeIfPresent([V9StoreUser].self, forKey: .storeUsers)) ?? []
|
||||
}
|
||||
}
|
||||
|
||||
/// v9 景区账号实体,表示用户可进入的某个景区身份。
|
||||
struct V9ScenicUser: Decodable, Equatable {
|
||||
static let accountTypeValue = "scenic_user"
|
||||
|
||||
let accountType: String
|
||||
let id: Int
|
||||
let userId: Int
|
||||
let scenicUserId: Int
|
||||
let ssUserId: Int
|
||||
let username: String
|
||||
let realName: String
|
||||
let nickname: String
|
||||
let phone: String
|
||||
let scenicId: Int
|
||||
let scenicName: String
|
||||
let isCurrent: Bool
|
||||
|
||||
/// set-user 使用的业务账号 ID,按后端可用字段优先级兜底。
|
||||
var businessUserId: Int {
|
||||
[ssUserId, scenicUserId, userId, id].first { $0 > 0 } ?? 0
|
||||
}
|
||||
|
||||
/// 用于界面展示的景区账号名称。
|
||||
var displayName: String {
|
||||
scenicName.nonEmpty ?? nickname.nonEmpty ?? realName.nonEmpty ?? username
|
||||
}
|
||||
|
||||
/// 转换为账号选择页使用的统一账号实体。
|
||||
func toAccountSwitchAccount() -> AccountSwitchAccount {
|
||||
AccountSwitchAccount(
|
||||
accountType: accountType.nonEmpty ?? Self.accountTypeValue,
|
||||
businessUserId: businessUserId,
|
||||
title: scenicName.nonEmpty ?? nickname.nonEmpty ?? realName.nonEmpty ?? "景区账号",
|
||||
subtitle: [realName.nonEmpty, nickname.nonEmpty]
|
||||
.compactMap(\.self)
|
||||
.joined(separator: " · "),
|
||||
phone: phone,
|
||||
avatar: "",
|
||||
scenicName: scenicName,
|
||||
storeId: nil,
|
||||
storeName: "",
|
||||
scenicId: scenicId > 0 ? scenicId : nil,
|
||||
isCurrent: isCurrent
|
||||
)
|
||||
}
|
||||
|
||||
/// 景区账号响应的 JSON 字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case accountType = "account_type"
|
||||
case id
|
||||
case userId = "user_id"
|
||||
case scenicUserId = "scenic_user_id"
|
||||
case ssUserId = "ss_user_id"
|
||||
case username
|
||||
case realName = "real_name"
|
||||
case nickname
|
||||
case phone
|
||||
case scenicId = "scenic_id"
|
||||
case scenicName = "scenic_name"
|
||||
case isCurrent = "is_current"
|
||||
}
|
||||
|
||||
/// 自定义解码,兼容 ID 字段类型不稳定和字段缺失。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
accountType = try container.decodeLossyString(forKey: .accountType).nonEmpty ?? Self.accountTypeValue
|
||||
id = try container.decodeLossyInt(forKey: .id) ?? 0
|
||||
userId = try container.decodeLossyInt(forKey: .userId) ?? 0
|
||||
scenicUserId = try container.decodeLossyInt(forKey: .scenicUserId) ?? 0
|
||||
ssUserId = try container.decodeLossyInt(forKey: .ssUserId) ?? 0
|
||||
username = try container.decodeLossyString(forKey: .username)
|
||||
realName = try container.decodeLossyString(forKey: .realName)
|
||||
nickname = try container.decodeLossyString(forKey: .nickname)
|
||||
phone = try container.decodeLossyString(forKey: .phone)
|
||||
scenicId = try container.decodeLossyInt(forKey: .scenicId) ?? 0
|
||||
scenicName = try container.decodeLossyString(forKey: .scenicName)
|
||||
isCurrent = try container.decodeLossyBool(forKey: .isCurrent) ?? false
|
||||
}
|
||||
}
|
||||
|
||||
/// v9 门店账号实体,表示用户可进入的某个门店身份。
|
||||
struct V9StoreUser: Decodable, Equatable {
|
||||
static let accountTypeValue = "store_user"
|
||||
|
||||
let accountType: String
|
||||
let id: Int
|
||||
let userId: Int
|
||||
let storeUserId: Int
|
||||
let username: String
|
||||
let userName: String
|
||||
let realName: String
|
||||
let phone: String
|
||||
let avatar: String
|
||||
let scenicId: Int
|
||||
let scenicName: String
|
||||
let storeId: Int
|
||||
let storeName: String
|
||||
let isCurrent: Bool
|
||||
|
||||
/// set-user 使用的业务账号 ID,按后端可用字段优先级兜底。
|
||||
var businessUserId: Int {
|
||||
[storeUserId, userId, id].first { $0 > 0 } ?? 0
|
||||
}
|
||||
|
||||
/// 用于界面展示的门店账号名称。
|
||||
var displayName: String {
|
||||
storeName.nonEmpty ?? scenicName.nonEmpty ?? realName.nonEmpty ?? userName.nonEmpty ?? username
|
||||
}
|
||||
|
||||
/// 转换为账号选择页使用的统一账号实体。
|
||||
func toAccountSwitchAccount() -> AccountSwitchAccount {
|
||||
AccountSwitchAccount(
|
||||
accountType: accountType.nonEmpty ?? Self.accountTypeValue,
|
||||
businessUserId: businessUserId,
|
||||
title: storeName.nonEmpty ?? scenicName.nonEmpty ?? realName.nonEmpty ?? userName.nonEmpty ?? "门店账号",
|
||||
subtitle: [scenicName.nonEmpty, realName.nonEmpty ?? userName.nonEmpty]
|
||||
.compactMap(\.self)
|
||||
.joined(separator: " · "),
|
||||
phone: phone,
|
||||
avatar: avatar,
|
||||
scenicName: scenicName,
|
||||
storeId: storeId > 0 ? storeId : nil,
|
||||
storeName: storeName,
|
||||
scenicId: scenicId > 0 ? scenicId : nil,
|
||||
isCurrent: isCurrent
|
||||
)
|
||||
}
|
||||
|
||||
/// 门店账号响应的 JSON 字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case accountType = "account_type"
|
||||
case id
|
||||
case userId = "user_id"
|
||||
case storeUserId = "store_user_id"
|
||||
case username
|
||||
case userName = "user_name"
|
||||
case realName = "real_name"
|
||||
case phone
|
||||
case avatar
|
||||
case scenicId = "scenic_id"
|
||||
case scenicName = "scenic_name"
|
||||
case storeId = "store_id"
|
||||
case storeName = "store_name"
|
||||
case isCurrent = "is_current"
|
||||
}
|
||||
|
||||
/// 自定义解码,兼容 ID 字段类型不稳定和字段缺失。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
accountType = try container.decodeLossyString(forKey: .accountType).nonEmpty ?? Self.accountTypeValue
|
||||
id = try container.decodeLossyInt(forKey: .id) ?? 0
|
||||
userId = try container.decodeLossyInt(forKey: .userId) ?? 0
|
||||
storeUserId = try container.decodeLossyInt(forKey: .storeUserId) ?? 0
|
||||
username = try container.decodeLossyString(forKey: .username)
|
||||
userName = try container.decodeLossyString(forKey: .userName)
|
||||
realName = try container.decodeLossyString(forKey: .realName)
|
||||
phone = try container.decodeLossyString(forKey: .phone)
|
||||
avatar = try container.decodeLossyString(forKey: .avatar)
|
||||
scenicId = try container.decodeLossyInt(forKey: .scenicId) ?? 0
|
||||
scenicName = try container.decodeLossyString(forKey: .scenicName)
|
||||
storeId = try container.decodeLossyInt(forKey: .storeId) ?? 0
|
||||
storeName = try container.decodeLossyString(forKey: .storeName)
|
||||
isCurrent = try container.decodeLossyBool(forKey: .isCurrent) ?? false
|
||||
}
|
||||
}
|
||||
|
||||
private extension KeyedDecodingContainer {
|
||||
/// 将 String、数字和 Bool 宽松解码为字符串。
|
||||
func decodeLossyString(forKey key: Key) throws -> String {
|
||||
if let value = try? decodeIfPresent(String.self, forKey: key) {
|
||||
return value
|
||||
}
|
||||
if let value = try? decodeIfPresent(Int.self, forKey: key) {
|
||||
return String(value)
|
||||
}
|
||||
if let value = try? decodeIfPresent(Double.self, forKey: key) {
|
||||
return String(value)
|
||||
}
|
||||
if let value = try? decodeIfPresent(Bool.self, forKey: key) {
|
||||
return value ? "true" : "false"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
/// 将 Int、Double 或数字字符串宽松解码为整数。
|
||||
func decodeLossyInt(forKey key: Key) throws -> Int? {
|
||||
if let value = try? decodeIfPresent(Int.self, forKey: key) {
|
||||
return value
|
||||
}
|
||||
if let value = try? decodeIfPresent(String.self, forKey: key) {
|
||||
let text = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if let intValue = Int(text) {
|
||||
return intValue
|
||||
}
|
||||
if let doubleValue = Double(text) {
|
||||
return Int(doubleValue)
|
||||
}
|
||||
}
|
||||
if let value = try? decodeIfPresent(Double.self, forKey: key) {
|
||||
return Int(value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// 将 Bool、数字或布尔字符串宽松解码为布尔值。
|
||||
func decodeLossyBool(forKey key: Key) throws -> Bool? {
|
||||
if let value = try? decodeIfPresent(Bool.self, forKey: key) {
|
||||
return value
|
||||
}
|
||||
if let value = try? decodeIfPresent(Int.self, forKey: key) {
|
||||
return value != 0
|
||||
}
|
||||
if let value = try? decodeIfPresent(String.self, forKey: key) {
|
||||
let normalized = value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
|
||||
if ["1", "true", "yes"].contains(normalized) { return true }
|
||||
if ["0", "false", "no"].contains(normalized) { return false }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private extension String {
|
||||
var nonEmpty: String? {
|
||||
let text = trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return text.isEmpty ? nil : text
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,291 @@
|
||||
//
|
||||
// AccountSelectionViewController.swift
|
||||
// suixinkan
|
||||
//
|
||||
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
@MainActor
|
||||
/// 多账号登录时的账号选择页,展示景区/门店账号列表并提交选择。
|
||||
final class AccountSelectionViewController: UIViewController {
|
||||
|
||||
private let payload: AccountSelectionPayload
|
||||
private var isLoading: Bool
|
||||
private let onCancel: () -> Void
|
||||
private let onConfirm: (AccountSwitchAccount) -> Void
|
||||
|
||||
private var selectedAccountId: String?
|
||||
private let tableView = UITableView(frame: .zero, style: .plain)
|
||||
private let confirmButton = UIButton(type: .system)
|
||||
private let bottomBar = UIView()
|
||||
|
||||
init(
|
||||
payload: AccountSelectionPayload,
|
||||
isLoading: Bool,
|
||||
onCancel: @escaping () -> Void,
|
||||
onConfirm: @escaping (AccountSwitchAccount) -> Void
|
||||
) {
|
||||
self.payload = payload
|
||||
self.isLoading = isLoading
|
||||
self.onCancel = onCancel
|
||||
self.onConfirm = onConfirm
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
title = "选择账号"
|
||||
view.backgroundColor = UIColor(hex: 0xF5F7FB)
|
||||
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancelTapped))
|
||||
isModalInPresentation = isLoading
|
||||
|
||||
selectedAccountId = payload.accounts.first?.id
|
||||
configureTableView()
|
||||
configureBottomBar()
|
||||
}
|
||||
|
||||
func updateLoading(_ loading: Bool) {
|
||||
isLoading = loading
|
||||
isModalInPresentation = loading
|
||||
confirmButton.isEnabled = canConfirm
|
||||
confirmButton.backgroundColor = canConfirm ? AppDesign.primary : UIColor(hex: 0xC9CED6)
|
||||
}
|
||||
|
||||
private var selectedAccount: AccountSwitchAccount? {
|
||||
payload.accounts.first { $0.id == selectedAccountId }
|
||||
}
|
||||
|
||||
private var canConfirm: Bool {
|
||||
selectedAccount != nil && !isLoading
|
||||
}
|
||||
|
||||
private func configureTableView() {
|
||||
tableView.backgroundColor = .clear
|
||||
tableView.separatorStyle = .none
|
||||
tableView.dataSource = self
|
||||
tableView.delegate = self
|
||||
tableView.register(AccountSelectionCell.self, forCellReuseIdentifier: AccountSelectionCell.reuseIdentifier)
|
||||
view.addSubview(tableView)
|
||||
tableView.snp.makeConstraints { make in
|
||||
make.top.leading.trailing.equalToSuperview()
|
||||
make.bottom.equalTo(view.safeAreaLayoutGuide).inset(90)
|
||||
}
|
||||
}
|
||||
|
||||
private func configureBottomBar() {
|
||||
bottomBar.backgroundColor = .white
|
||||
|
||||
let divider = UIView()
|
||||
divider.backgroundColor = UIColor.separator
|
||||
|
||||
confirmButton.setTitle("进入系统", for: .normal)
|
||||
confirmButton.titleLabel?.font = .systemFont(ofSize: AppMetrics.FontSize.body, weight: .semibold)
|
||||
confirmButton.setTitleColor(.white, for: .normal)
|
||||
confirmButton.layer.cornerRadius = AppMetrics.CornerRadius.button
|
||||
confirmButton.addTarget(self, action: #selector(confirmTapped), for: .touchUpInside)
|
||||
updateLoading(isLoading)
|
||||
|
||||
view.addSubview(bottomBar)
|
||||
bottomBar.addSubview(divider)
|
||||
bottomBar.addSubview(confirmButton)
|
||||
|
||||
bottomBar.snp.makeConstraints { make in
|
||||
make.leading.trailing.bottom.equalToSuperview()
|
||||
}
|
||||
|
||||
divider.snp.makeConstraints { make in
|
||||
make.top.leading.trailing.equalToSuperview()
|
||||
make.height.equalTo(0.5)
|
||||
}
|
||||
|
||||
confirmButton.snp.makeConstraints { make in
|
||||
make.top.equalTo(divider.snp.bottom).offset(AppMetrics.Spacing.medium)
|
||||
make.leading.trailing.equalToSuperview().inset(AppMetrics.Spacing.medium)
|
||||
make.bottom.equalTo(view.safeAreaLayoutGuide).inset(AppMetrics.Spacing.medium)
|
||||
make.height.equalTo(AppMetrics.ControlSize.primaryButtonHeight)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func cancelTapped() {
|
||||
onCancel()
|
||||
dismiss(animated: true)
|
||||
}
|
||||
|
||||
@objc private func confirmTapped() {
|
||||
guard let selectedAccount else { return }
|
||||
onConfirm(selectedAccount)
|
||||
}
|
||||
}
|
||||
|
||||
extension AccountSelectionViewController: UITableViewDataSource, UITableViewDelegate {
|
||||
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
payload.accounts.count
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
guard let cell = tableView.dequeueReusableCell(
|
||||
withIdentifier: AccountSelectionCell.reuseIdentifier,
|
||||
for: indexPath
|
||||
) as? AccountSelectionCell else {
|
||||
return UITableViewCell()
|
||||
}
|
||||
let account = payload.accounts[indexPath.row]
|
||||
cell.configure(account: account, selected: account.id == selectedAccountId)
|
||||
return cell
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
|
||||
selectedAccountId = payload.accounts[indexPath.row].id
|
||||
tableView.reloadData()
|
||||
confirmButton.isEnabled = canConfirm
|
||||
confirmButton.backgroundColor = canConfirm ? AppDesign.primary : UIColor(hex: 0xC9CED6)
|
||||
}
|
||||
}
|
||||
|
||||
/// 账号选择列表 Cell。
|
||||
private final class AccountSelectionCell: UITableViewCell {
|
||||
static let reuseIdentifier = "AccountSelectionCell"
|
||||
|
||||
private let avatarView = UIView()
|
||||
private let avatarLabel = UILabel()
|
||||
private let titleLabel = UILabel()
|
||||
private let subtitleLabel = UILabel()
|
||||
private let phoneLabel = UILabel()
|
||||
private let typeTag = UILabel()
|
||||
private let currentTag = UILabel()
|
||||
private let checkmark = UIImageView()
|
||||
|
||||
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
|
||||
super.init(style: style, reuseIdentifier: reuseIdentifier)
|
||||
selectionStyle = .none
|
||||
backgroundColor = .clear
|
||||
contentView.backgroundColor = .white
|
||||
contentView.layer.cornerRadius = AppMetrics.CornerRadius.button
|
||||
contentView.layer.masksToBounds = true
|
||||
|
||||
avatarView.layer.cornerRadius = AppMetrics.ControlSize.primaryButtonHeight / 2
|
||||
avatarLabel.font = .systemFont(ofSize: AppMetrics.FontSize.callout, weight: .semibold)
|
||||
|
||||
titleLabel.font = .systemFont(ofSize: AppMetrics.FontSize.body, weight: .semibold)
|
||||
titleLabel.textColor = AppDesign.textPrimary
|
||||
|
||||
subtitleLabel.font = .systemFont(ofSize: AppMetrics.FontSize.footnote)
|
||||
subtitleLabel.textColor = AppDesign.textSecondary
|
||||
|
||||
phoneLabel.font = .systemFont(ofSize: AppMetrics.FontSize.caption)
|
||||
phoneLabel.textColor = UIColor(hex: 0x9AA1AA)
|
||||
|
||||
typeTag.font = .systemFont(ofSize: 11, weight: .semibold)
|
||||
typeTag.textAlignment = .center
|
||||
typeTag.layer.cornerRadius = AppMetrics.Spacing.xxSmall
|
||||
typeTag.clipsToBounds = true
|
||||
|
||||
currentTag.font = .systemFont(ofSize: 11, weight: .semibold)
|
||||
currentTag.textAlignment = .center
|
||||
currentTag.text = "当前"
|
||||
currentTag.textColor = AppDesign.primary
|
||||
currentTag.backgroundColor = AppDesign.primarySoft
|
||||
currentTag.layer.cornerRadius = AppMetrics.Spacing.xxSmall
|
||||
currentTag.clipsToBounds = true
|
||||
currentTag.isHidden = true
|
||||
|
||||
checkmark.contentMode = .scaleAspectFit
|
||||
|
||||
contentView.addSubview(avatarView)
|
||||
avatarView.addSubview(avatarLabel)
|
||||
contentView.addSubview(titleLabel)
|
||||
contentView.addSubview(subtitleLabel)
|
||||
contentView.addSubview(phoneLabel)
|
||||
contentView.addSubview(typeTag)
|
||||
contentView.addSubview(currentTag)
|
||||
contentView.addSubview(checkmark)
|
||||
|
||||
avatarView.snp.makeConstraints { make in
|
||||
make.leading.equalToSuperview().inset(AppMetrics.FontSize.subheadline)
|
||||
make.centerY.equalToSuperview()
|
||||
make.width.height.equalTo(AppMetrics.ControlSize.primaryButtonHeight)
|
||||
}
|
||||
|
||||
avatarLabel.snp.makeConstraints { make in
|
||||
make.center.equalToSuperview()
|
||||
}
|
||||
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.top.equalToSuperview().inset(AppMetrics.FontSize.subheadline)
|
||||
make.leading.equalTo(avatarView.snp.trailing).offset(AppMetrics.FontSize.footnote)
|
||||
make.trailing.lessThanOrEqualTo(checkmark.snp.leading).offset(-8)
|
||||
}
|
||||
|
||||
currentTag.snp.makeConstraints { make in
|
||||
make.leading.equalTo(titleLabel.snp.trailing).offset(AppMetrics.Spacing.xSmall)
|
||||
make.centerY.equalTo(titleLabel)
|
||||
make.height.equalTo(AppMetrics.Spacing.sheet)
|
||||
}
|
||||
|
||||
subtitleLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(titleLabel.snp.bottom).offset(AppMetrics.Spacing.xxSmall)
|
||||
make.leading.equalTo(titleLabel)
|
||||
make.trailing.equalTo(checkmark.snp.leading).offset(-8)
|
||||
}
|
||||
|
||||
phoneLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(subtitleLabel.snp.bottom).offset(AppMetrics.Spacing.xxSmall)
|
||||
make.leading.equalTo(titleLabel)
|
||||
make.bottom.equalToSuperview().inset(AppMetrics.FontSize.subheadline)
|
||||
}
|
||||
|
||||
typeTag.snp.makeConstraints { make in
|
||||
make.trailing.equalTo(checkmark.snp.leading).offset(-AppMetrics.Spacing.xSmall)
|
||||
make.top.equalTo(titleLabel)
|
||||
make.height.equalTo(AppMetrics.Spacing.sheet)
|
||||
}
|
||||
|
||||
checkmark.snp.makeConstraints { make in
|
||||
make.trailing.equalToSuperview().inset(AppMetrics.FontSize.subheadline)
|
||||
make.centerY.equalToSuperview()
|
||||
make.width.height.equalTo(AppMetrics.ControlSize.passwordIcon)
|
||||
}
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
nil
|
||||
}
|
||||
|
||||
func configure(account: AccountSwitchAccount, selected: Bool) {
|
||||
titleLabel.text = account.title.isEmpty ? account.accountTypeLabel : account.title
|
||||
subtitleLabel.text = account.subtitle
|
||||
subtitleLabel.isHidden = account.subtitle.isEmpty
|
||||
phoneLabel.text = account.phone
|
||||
phoneLabel.isHidden = account.phone.isEmpty
|
||||
currentTag.isHidden = !account.isCurrent
|
||||
|
||||
if account.isStoreUser {
|
||||
avatarView.backgroundColor = UIColor(hex: 0xE8F8F1)
|
||||
avatarLabel.text = "店"
|
||||
avatarLabel.textColor = UIColor(hex: 0x0F9F6E)
|
||||
typeTag.text = " 门店 "
|
||||
typeTag.textColor = UIColor(hex: 0x0F9F6E)
|
||||
typeTag.backgroundColor = UIColor(hex: 0xE8F8F1)
|
||||
} else {
|
||||
avatarView.backgroundColor = UIColor(hex: 0xF3ECFF)
|
||||
avatarLabel.text = "景"
|
||||
avatarLabel.textColor = UIColor(hex: 0x7C3AED)
|
||||
typeTag.text = " 景区 "
|
||||
typeTag.textColor = UIColor(hex: 0x7C3AED)
|
||||
typeTag.backgroundColor = UIColor(hex: 0xF3ECFF)
|
||||
}
|
||||
|
||||
let symbolName = selected ? "checkmark.circle.fill" : "circle"
|
||||
checkmark.image = UIImage(systemName: symbolName)
|
||||
checkmark.tintColor = selected ? AppDesign.primary : UIColor(hex: 0xB6BECA)
|
||||
|
||||
contentView.layer.borderWidth = selected ? 1.4 : 1
|
||||
contentView.layer.borderColor = (selected ? AppDesign.primary : UIColor(hex: 0xE6ECF4)).cgColor
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,532 @@
|
||||
//
|
||||
// LoginViewController.swift
|
||||
// suixinkan
|
||||
//
|
||||
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
@MainActor
|
||||
/// 登录页,展示手机号/密码表单、协议勾选和多账号选择入口。
|
||||
final class LoginViewController: UIViewController {
|
||||
|
||||
private let services: AppServices
|
||||
private let viewModel = LoginViewModel()
|
||||
|
||||
private let scrollView = UIScrollView()
|
||||
private let contentView = UIView()
|
||||
private let backgroundImageView = UIImageView(image: UIImage(named: "LoginBackground"))
|
||||
private let titleLabel = UILabel()
|
||||
private let cardView = UIView()
|
||||
private let usernameField = LoginInputField(iconName: "person", placeholder: "请输入手机号", isSecure: false)
|
||||
private let passwordField = LoginInputField(iconName: "lock", placeholder: "请输入密码", isSecure: true)
|
||||
private let privacyButton = UIButton(type: .custom)
|
||||
private let privacyLabel = UILabel()
|
||||
private let userAgreementButton = UIButton(type: .system)
|
||||
private let privacyPolicyButton = UIButton(type: .system)
|
||||
private let loginButton = UIButton(type: .system)
|
||||
|
||||
init(services: AppServices) {
|
||||
self.services = services
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
view.backgroundColor = UIColor(hex: 0x0B1220)
|
||||
configureViews()
|
||||
bindViewModel()
|
||||
viewModel.applyPreferences(services.authSessionCoordinator.loginPreferences())
|
||||
}
|
||||
|
||||
private func configureViews() {
|
||||
backgroundImageView.contentMode = .scaleAspectFill
|
||||
backgroundImageView.clipsToBounds = true
|
||||
|
||||
titleLabel.text = "欢迎使用\n随心瞰商家版"
|
||||
titleLabel.font = .systemFont(ofSize: AppMetrics.FontSize.largeTitle, weight: .semibold)
|
||||
titleLabel.textColor = .white
|
||||
titleLabel.numberOfLines = 0
|
||||
|
||||
cardView.backgroundColor = .white
|
||||
cardView.layer.cornerRadius = AppMetrics.CornerRadius.card
|
||||
cardView.layer.shadowColor = UIColor.black.cgColor
|
||||
cardView.layer.shadowOpacity = 0.12
|
||||
cardView.layer.shadowRadius = 18
|
||||
cardView.layer.shadowOffset = CGSize(width: 0, height: 8)
|
||||
|
||||
usernameField.textField.keyboardType = .phonePad
|
||||
usernameField.textField.textContentType = .telephoneNumber
|
||||
usernameField.textField.autocorrectionType = .no
|
||||
usernameField.textField.autocapitalizationType = .none
|
||||
usernameField.textField.returnKeyType = .next
|
||||
usernameField.textField.accessibilityIdentifier = "login.username"
|
||||
usernameField.textField.delegate = self
|
||||
usernameField.textField.addTarget(self, action: #selector(usernameChanged), for: .editingChanged)
|
||||
|
||||
passwordField.textField.autocorrectionType = .no
|
||||
passwordField.textField.autocapitalizationType = .none
|
||||
passwordField.textField.returnKeyType = .go
|
||||
passwordField.textField.accessibilityIdentifier = "login.password"
|
||||
passwordField.textField.delegate = self
|
||||
passwordField.textField.addTarget(self, action: #selector(passwordChanged), for: .editingChanged)
|
||||
passwordField.onToggleVisibility = { [weak self] in
|
||||
self?.viewModel.showsPassword.toggle()
|
||||
}
|
||||
|
||||
privacyButton.accessibilityIdentifier = "login.privacy"
|
||||
privacyButton.addTarget(self, action: #selector(togglePrivacy), for: .touchUpInside)
|
||||
|
||||
configureAgreementText()
|
||||
|
||||
loginButton.setTitle("登录", for: .normal)
|
||||
loginButton.titleLabel?.font = .systemFont(ofSize: AppMetrics.FontSize.body, weight: .medium)
|
||||
loginButton.layer.cornerRadius = AppMetrics.CornerRadius.button
|
||||
loginButton.accessibilityIdentifier = "login.submit"
|
||||
loginButton.addTarget(self, action: #selector(loginTapped), for: .touchUpInside)
|
||||
|
||||
view.addSubview(backgroundImageView)
|
||||
view.addSubview(scrollView)
|
||||
scrollView.addSubview(contentView)
|
||||
contentView.addSubview(titleLabel)
|
||||
contentView.addSubview(cardView)
|
||||
|
||||
cardView.addSubview(usernameField)
|
||||
cardView.addSubview(passwordField)
|
||||
cardView.addSubview(privacyButton)
|
||||
cardView.addSubview(privacyLabel)
|
||||
cardView.addSubview(loginButton)
|
||||
|
||||
backgroundImageView.snp.makeConstraints { make in
|
||||
make.edges.equalToSuperview()
|
||||
}
|
||||
|
||||
scrollView.snp.makeConstraints { make in
|
||||
make.edges.equalToSuperview()
|
||||
}
|
||||
|
||||
contentView.snp.makeConstraints { make in
|
||||
make.edges.equalTo(scrollView.contentLayoutGuide)
|
||||
make.width.equalTo(scrollView.frameLayoutGuide)
|
||||
}
|
||||
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(contentView.safeAreaLayoutGuide).offset(72)
|
||||
make.leading.trailing.equalToSuperview().inset(24)
|
||||
}
|
||||
titleLabel.accessibilityIdentifier = "login.title"
|
||||
|
||||
cardView.snp.makeConstraints { make in
|
||||
make.top.equalTo(titleLabel.snp.bottom).offset(AppMetrics.Spacing.xxLarge)
|
||||
make.leading.trailing.equalToSuperview().inset(20)
|
||||
make.bottom.equalToSuperview().inset(AppMetrics.Spacing.xxLarge)
|
||||
}
|
||||
|
||||
usernameField.snp.makeConstraints { make in
|
||||
make.top.leading.trailing.equalToSuperview().inset(AppMetrics.Spacing.medium)
|
||||
make.height.equalTo(AppMetrics.ControlSize.inputHeight)
|
||||
}
|
||||
|
||||
passwordField.snp.makeConstraints { make in
|
||||
make.top.equalTo(usernameField.snp.bottom).offset(AppMetrics.Spacing.xSmall)
|
||||
make.leading.trailing.equalTo(usernameField)
|
||||
make.height.equalTo(AppMetrics.ControlSize.inputHeight)
|
||||
}
|
||||
|
||||
privacyButton.snp.makeConstraints { make in
|
||||
make.top.equalTo(passwordField.snp.bottom).offset(AppMetrics.ControlSize.checkboxTapArea)
|
||||
make.leading.equalToSuperview().inset(AppMetrics.Spacing.medium)
|
||||
make.width.height.equalTo(AppMetrics.ControlSize.checkboxTapArea)
|
||||
}
|
||||
|
||||
privacyLabel.snp.makeConstraints { make in
|
||||
make.leading.equalTo(privacyButton.snp.trailing)
|
||||
make.trailing.equalToSuperview().inset(AppMetrics.Spacing.medium)
|
||||
make.top.equalTo(privacyButton).offset(AppMetrics.Spacing.xxSmall)
|
||||
}
|
||||
|
||||
loginButton.snp.makeConstraints { make in
|
||||
make.top.equalTo(privacyLabel.snp.bottom).offset(AppMetrics.Spacing.mediumLarge)
|
||||
make.leading.trailing.bottom.equalToSuperview().inset(AppMetrics.Spacing.medium)
|
||||
make.height.equalTo(AppMetrics.ControlSize.primaryButtonHeight)
|
||||
}
|
||||
|
||||
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
|
||||
tap.cancelsTouchesInView = false
|
||||
view.addGestureRecognizer(tap)
|
||||
}
|
||||
|
||||
private func configureAgreementText() {
|
||||
privacyLabel.numberOfLines = 0
|
||||
privacyLabel.font = .systemFont(ofSize: AppMetrics.FontSize.subheadline)
|
||||
|
||||
userAgreementButton.setTitle("《用户协议》", for: .normal)
|
||||
userAgreementButton.titleLabel?.font = .systemFont(ofSize: AppMetrics.FontSize.subheadline)
|
||||
userAgreementButton.setTitleColor(UIColor(hex: 0x208BFF), for: .normal)
|
||||
userAgreementButton.accessibilityIdentifier = "login.userAgreement"
|
||||
userAgreementButton.addTarget(self, action: #selector(openUserAgreement), for: .touchUpInside)
|
||||
|
||||
privacyPolicyButton.setTitle("《隐私政策》", for: .normal)
|
||||
privacyPolicyButton.titleLabel?.font = .systemFont(ofSize: AppMetrics.FontSize.subheadline)
|
||||
privacyPolicyButton.setTitleColor(UIColor(hex: 0x208BFF), for: .normal)
|
||||
privacyPolicyButton.accessibilityIdentifier = "login.privacyPolicy"
|
||||
privacyPolicyButton.addTarget(self, action: #selector(openPrivacyPolicy), for: .touchUpInside)
|
||||
|
||||
let prefix = UILabel()
|
||||
prefix.text = "已阅读并同意"
|
||||
prefix.font = .systemFont(ofSize: AppMetrics.FontSize.subheadline)
|
||||
prefix.textColor = UIColor(hex: 0x666666)
|
||||
|
||||
let separator = UILabel()
|
||||
separator.text = "与"
|
||||
separator.font = .systemFont(ofSize: AppMetrics.FontSize.subheadline)
|
||||
separator.textColor = UIColor(hex: 0x666666)
|
||||
|
||||
let row = UIStackView(arrangedSubviews: [prefix, userAgreementButton, separator, privacyPolicyButton])
|
||||
row.axis = .horizontal
|
||||
row.spacing = 0
|
||||
row.alignment = .center
|
||||
privacyLabel.addSubview(row)
|
||||
row.snp.makeConstraints { make in
|
||||
make.edges.equalToSuperview()
|
||||
}
|
||||
}
|
||||
|
||||
private func bindViewModel() {
|
||||
viewModel.onChange = { [weak self] in
|
||||
self?.renderViewModel()
|
||||
}
|
||||
renderViewModel()
|
||||
}
|
||||
|
||||
private func renderViewModel() {
|
||||
if usernameField.textField.text != viewModel.username {
|
||||
usernameField.textField.text = viewModel.username
|
||||
}
|
||||
if passwordField.textField.text != viewModel.password {
|
||||
passwordField.textField.text = viewModel.password
|
||||
}
|
||||
|
||||
passwordField.setSecureEntry(!viewModel.showsPassword)
|
||||
|
||||
let checkboxImage = viewModel.privacyChecked ? "LoginCheckboxChecked" : "LoginCheckboxUnchecked"
|
||||
privacyButton.setImage(UIImage(named: checkboxImage), for: .normal)
|
||||
|
||||
loginButton.isEnabled = viewModel.canSubmit && !viewModel.isLoading
|
||||
loginButton.backgroundColor = viewModel.canSubmit ? AppDesign.primary : .gray
|
||||
loginButton.setTitleColor(.white, for: .normal)
|
||||
loginButton.alpha = viewModel.isLoading ? 0.7 : 1
|
||||
|
||||
if viewModel.showsAgreementSheet {
|
||||
viewModel.showsAgreementSheet = false
|
||||
presentAgreementSheet()
|
||||
}
|
||||
|
||||
if let payload = viewModel.pendingAccountSelection {
|
||||
if let controller = accountSelectionController {
|
||||
controller.updateLoading(viewModel.isSelectingAccount)
|
||||
} else if presentedViewController == nil {
|
||||
presentAccountSelection(payload)
|
||||
}
|
||||
} else if accountSelectionController != nil {
|
||||
dismiss(animated: true)
|
||||
accountSelectionController = nil
|
||||
}
|
||||
}
|
||||
|
||||
private weak var accountSelectionController: AccountSelectionViewController?
|
||||
|
||||
@objc private func usernameChanged() {
|
||||
viewModel.username = usernameField.textField.text ?? ""
|
||||
viewModel.normalizeUsernameCountryCodeIfNeeded()
|
||||
services.toastCenter.dismiss()
|
||||
}
|
||||
|
||||
@objc private func passwordChanged() {
|
||||
viewModel.password = passwordField.textField.text ?? ""
|
||||
services.toastCenter.dismiss()
|
||||
}
|
||||
|
||||
@objc private func togglePrivacy() {
|
||||
viewModel.privacyChecked.toggle()
|
||||
}
|
||||
|
||||
@objc private func openUserAgreement() {
|
||||
showToast("用户协议页面待接入")
|
||||
}
|
||||
|
||||
@objc private func openPrivacyPolicy() {
|
||||
showToast("隐私政策页面待接入")
|
||||
}
|
||||
|
||||
@objc private func loginTapped() {
|
||||
view.endEditing(true)
|
||||
performLogin()
|
||||
}
|
||||
|
||||
@objc private func dismissKeyboard() {
|
||||
view.endEditing(true)
|
||||
}
|
||||
|
||||
private func performLogin() {
|
||||
if let validationError = viewModel.validateForLogin() {
|
||||
if validationError == .privacyUnchecked {
|
||||
presentAgreementSheet()
|
||||
} else {
|
||||
showToast(validationError.message)
|
||||
if validationError.focusField == .username {
|
||||
usernameField.textField.becomeFirstResponder()
|
||||
} else if validationError.focusField == .password {
|
||||
passwordField.textField.becomeFirstResponder()
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Task {
|
||||
do {
|
||||
try await services.globalLoading.withLoading(message: "登录中...") {
|
||||
let resolution = try await viewModel.login(authAPI: services.authAPI)
|
||||
switch resolution {
|
||||
case let .completed(response):
|
||||
await completeLogin(with: response)
|
||||
case .needsAccountSelection:
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch is CancellationError {
|
||||
return
|
||||
} catch {
|
||||
showToast(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func presentAgreementSheet() {
|
||||
let controller = LoginAgreementConsentViewController(
|
||||
onOpenAgreement: { [weak self] title in
|
||||
self?.showToast("\(title)页面待接入")
|
||||
},
|
||||
onAgreeAndContinue: { [weak self] in
|
||||
self?.viewModel.acceptAgreement()
|
||||
self?.performLogin()
|
||||
}
|
||||
)
|
||||
if let sheet = controller.sheetPresentationController {
|
||||
sheet.detents = [.custom(resolver: { _ in 240 })]
|
||||
sheet.prefersGrabberVisible = true
|
||||
}
|
||||
present(controller, animated: true)
|
||||
}
|
||||
|
||||
private func presentAccountSelection(_ payload: AccountSelectionPayload) {
|
||||
let controller = AccountSelectionViewController(
|
||||
payload: payload,
|
||||
isLoading: viewModel.isSelectingAccount,
|
||||
onCancel: { [weak self] in
|
||||
self?.viewModel.clearPendingAccountSelection()
|
||||
self?.accountSelectionController = nil
|
||||
},
|
||||
onConfirm: { [weak self] account in
|
||||
self?.selectAccount(account)
|
||||
}
|
||||
)
|
||||
accountSelectionController = controller
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
navigation.modalPresentationStyle = .formSheet
|
||||
present(navigation, animated: true)
|
||||
}
|
||||
|
||||
private func selectAccount(_ account: AccountSwitchAccount) {
|
||||
Task {
|
||||
do {
|
||||
try await services.globalLoading.withLoading(message: "账号切换中...") {
|
||||
let response = try await viewModel.selectAccount(account, authAPI: services.authAPI)
|
||||
await completeLogin(with: response)
|
||||
accountSelectionController = nil
|
||||
dismiss(animated: true)
|
||||
}
|
||||
} catch is CancellationError {
|
||||
return
|
||||
} catch {
|
||||
showToast(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func completeLogin(with response: V9AuthResponse) async {
|
||||
do {
|
||||
try await services.authSessionCoordinator.completeLogin(
|
||||
with: response,
|
||||
username: viewModel.normalizedUsername,
|
||||
privacyAgreementAccepted: viewModel.privacyChecked,
|
||||
appSession: services.appSession,
|
||||
accountContext: services.accountContext,
|
||||
permissionContext: services.permissionContext,
|
||||
profileAPI: services.profileAPI,
|
||||
accountContextAPI: services.accountContextAPI
|
||||
)
|
||||
} catch {
|
||||
showToast(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension LoginViewController: UITextFieldDelegate {
|
||||
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
|
||||
if textField === usernameField.textField {
|
||||
passwordField.textField.becomeFirstResponder()
|
||||
} else if viewModel.canSubmit, !viewModel.isLoading {
|
||||
performLogin()
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// 登录输入框,包含图标、文本框和密码可见切换。
|
||||
private final class LoginInputField: UIView {
|
||||
let textField = UITextField()
|
||||
var onToggleVisibility: (() -> Void)?
|
||||
|
||||
private let toggleButton = UIButton(type: .custom)
|
||||
private var isSecure = false
|
||||
|
||||
init(iconName: String, placeholder: String, isSecure: Bool) {
|
||||
self.isSecure = isSecure
|
||||
super.init(frame: .zero)
|
||||
backgroundColor = UIColor(hex: 0xF1F5F9)
|
||||
layer.cornerRadius = AppMetrics.CornerRadius.input
|
||||
layer.borderWidth = 1
|
||||
layer.borderColor = UIColor(hex: 0xDDE3EA).cgColor
|
||||
|
||||
let icon = UIImageView(image: UIImage(systemName: iconName))
|
||||
icon.tintColor = AppDesign.textSecondary
|
||||
icon.contentMode = .scaleAspectFit
|
||||
|
||||
textField.placeholder = placeholder
|
||||
textField.font = .systemFont(ofSize: AppMetrics.FontSize.body)
|
||||
textField.textColor = AppDesign.textPrimary
|
||||
textField.tintColor = AppDesign.primary
|
||||
textField.borderStyle = .none
|
||||
textField.isSecureTextEntry = isSecure
|
||||
|
||||
addSubview(icon)
|
||||
addSubview(textField)
|
||||
|
||||
icon.snp.makeConstraints { make in
|
||||
make.leading.equalToSuperview().inset(AppMetrics.Spacing.medium)
|
||||
make.centerY.equalToSuperview()
|
||||
make.width.height.equalTo(AppMetrics.ControlSize.smallIcon)
|
||||
}
|
||||
|
||||
if isSecure {
|
||||
toggleButton.addTarget(self, action: #selector(toggleVisibility), for: .touchUpInside)
|
||||
addSubview(toggleButton)
|
||||
toggleButton.snp.makeConstraints { make in
|
||||
make.trailing.equalToSuperview().inset(AppMetrics.Spacing.small)
|
||||
make.centerY.equalToSuperview()
|
||||
make.width.height.equalTo(AppMetrics.ControlSize.iconTapArea)
|
||||
}
|
||||
textField.snp.makeConstraints { make in
|
||||
make.leading.equalTo(icon.snp.trailing).offset(AppMetrics.Spacing.xSmall)
|
||||
make.trailing.equalTo(toggleButton.snp.leading)
|
||||
make.centerY.equalToSuperview()
|
||||
}
|
||||
} else {
|
||||
textField.snp.makeConstraints { make in
|
||||
make.leading.equalTo(icon.snp.trailing).offset(AppMetrics.Spacing.xSmall)
|
||||
make.trailing.equalToSuperview().inset(AppMetrics.Spacing.medium)
|
||||
make.centerY.equalToSuperview()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
nil
|
||||
}
|
||||
|
||||
func setSecureEntry(_ secure: Bool) {
|
||||
textField.isSecureTextEntry = secure
|
||||
let imageName = secure ? "LoginPwdInvisible" : "LoginPwdVisible"
|
||||
toggleButton.setImage(UIImage(named: imageName), for: .normal)
|
||||
}
|
||||
|
||||
@objc private func toggleVisibility() {
|
||||
onToggleVisibility?()
|
||||
}
|
||||
}
|
||||
|
||||
/// 协议确认弹窗,引导用户勾选协议后继续登录。
|
||||
private final class LoginAgreementConsentViewController: UIViewController {
|
||||
|
||||
private let onOpenAgreement: (String) -> Void
|
||||
private let onAgreeAndContinue: () -> Void
|
||||
|
||||
init(onOpenAgreement: @escaping (String) -> Void, onAgreeAndContinue: @escaping () -> Void) {
|
||||
self.onOpenAgreement = onOpenAgreement
|
||||
self.onAgreeAndContinue = onAgreeAndContinue
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
nil
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
view.backgroundColor = .systemBackground
|
||||
|
||||
let titleLabel = UILabel()
|
||||
titleLabel.text = "请先阅读并同意相关协议"
|
||||
titleLabel.font = .systemFont(ofSize: AppMetrics.FontSize.title3, weight: .semibold)
|
||||
titleLabel.textColor = AppDesign.textPrimary
|
||||
titleLabel.textAlignment = .center
|
||||
|
||||
let descriptionLabel = UILabel()
|
||||
descriptionLabel.text = "为了保障你的账号安全和服务体验,请阅读并同意用户协议和隐私政策。"
|
||||
descriptionLabel.font = .systemFont(ofSize: AppMetrics.FontSize.subheadline)
|
||||
descriptionLabel.textColor = AppDesign.textSecondary
|
||||
descriptionLabel.numberOfLines = 0
|
||||
descriptionLabel.textAlignment = .center
|
||||
|
||||
let continueButton = UIButton(type: .system)
|
||||
continueButton.setTitle("同意并继续", for: .normal)
|
||||
continueButton.titleLabel?.font = .systemFont(ofSize: AppMetrics.FontSize.body, weight: .medium)
|
||||
continueButton.backgroundColor = AppDesign.primary
|
||||
continueButton.setTitleColor(.white, for: .normal)
|
||||
continueButton.layer.cornerRadius = AppMetrics.CornerRadius.button
|
||||
continueButton.accessibilityIdentifier = "login.agreement.continue"
|
||||
continueButton.addTarget(self, action: #selector(continueTapped), for: .touchUpInside)
|
||||
|
||||
view.addSubview(titleLabel)
|
||||
view.addSubview(descriptionLabel)
|
||||
view.addSubview(continueButton)
|
||||
|
||||
titleLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(view.safeAreaLayoutGuide).offset(AppMetrics.Spacing.sheet)
|
||||
make.leading.trailing.equalToSuperview().inset(AppMetrics.Spacing.large)
|
||||
}
|
||||
|
||||
descriptionLabel.snp.makeConstraints { make in
|
||||
make.top.equalTo(titleLabel.snp.bottom).offset(AppMetrics.Spacing.small)
|
||||
make.leading.trailing.equalTo(titleLabel)
|
||||
}
|
||||
|
||||
continueButton.snp.makeConstraints { make in
|
||||
make.leading.trailing.equalTo(titleLabel)
|
||||
make.bottom.equalTo(view.safeAreaLayoutGuide).inset(AppMetrics.Spacing.mediumLarge)
|
||||
make.height.equalTo(AppMetrics.ControlSize.sheetButtonHeight)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func continueTapped() {
|
||||
dismiss(animated: true) { [onAgreeAndContinue] in
|
||||
onAgreeAndContinue()
|
||||
}
|
||||
}
|
||||
}
|
||||
212
suixinkan_ios/Features/Auth/ViewModels/LoginViewModel.swift
Normal file
212
suixinkan_ios/Features/Auth/ViewModels/LoginViewModel.swift
Normal file
@ -0,0 +1,212 @@
|
||||
//
|
||||
// LoginViewModel.swift
|
||||
// suixinkan
|
||||
//
|
||||
// Created by Codex on 2026/6/18.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// 登录输入焦点实体,标识当前需要聚焦的输入框。
|
||||
enum LoginField: Hashable {
|
||||
case username
|
||||
case password
|
||||
}
|
||||
|
||||
/// 登录表单校验错误实体,负责提供用户提示和焦点位置。
|
||||
enum LoginValidationError: Equatable {
|
||||
case invalidPhone
|
||||
case emptyPassword
|
||||
case privacyUnchecked
|
||||
|
||||
var message: String {
|
||||
switch self {
|
||||
case .invalidPhone:
|
||||
"请输入有效的手机号码"
|
||||
case .emptyPassword:
|
||||
"请输入密码"
|
||||
case .privacyUnchecked:
|
||||
"请先阅读并同意相关协议"
|
||||
}
|
||||
}
|
||||
|
||||
var focusField: LoginField? {
|
||||
switch self {
|
||||
case .invalidPhone:
|
||||
.username
|
||||
case .emptyPassword:
|
||||
.password
|
||||
case .privacyUnchecked:
|
||||
nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 登录结果实体,区分已完成登录和需要用户选择账号两种情况。
|
||||
enum LoginResolution {
|
||||
case completed(V9AuthResponse)
|
||||
case needsAccountSelection(AccountSelectionPayload)
|
||||
}
|
||||
|
||||
/// 登录流程错误实体,表示 token、账号列表或账号 ID 异常。
|
||||
enum LoginFlowError: LocalizedError {
|
||||
case missingToken
|
||||
case noAvailableAccount
|
||||
case invalidAccount
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .missingToken:
|
||||
"登录响应缺少 token"
|
||||
case .noAvailableAccount:
|
||||
"当前账号没有可用的景区账号或门店账号,请联系管理员"
|
||||
case .invalidAccount:
|
||||
"账号信息异常,请重新选择账号"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
/// 登录页 ViewModel,负责表单状态、登录请求和多账号选择流程。
|
||||
final class LoginViewModel {
|
||||
var onChange: (() -> Void)?
|
||||
var username = "" { didSet { onChange?() } }
|
||||
var password = "" { didSet { onChange?() } }
|
||||
var privacyChecked = false { didSet { onChange?() } }
|
||||
var isLoading = false { didSet { onChange?() } }
|
||||
var isSelectingAccount = false { didSet { onChange?() } }
|
||||
var showsPassword = false { didSet { onChange?() } }
|
||||
var showsAgreementSheet = false { didSet { onChange?() } }
|
||||
var pendingAccountSelection: AccountSelectionPayload? { didSet { onChange?() } }
|
||||
|
||||
var canSubmit: Bool {
|
||||
isValidPhone && !trimmedPassword.isEmpty
|
||||
}
|
||||
|
||||
var trimmedPassword: String {
|
||||
password.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
var normalizedUsername: String {
|
||||
normalizedPhoneNumber(username)
|
||||
}
|
||||
|
||||
var isValidPhone: Bool {
|
||||
normalizedUsername.count == 11 && normalizedUsername.first == "1"
|
||||
}
|
||||
|
||||
/// 应用本地登录偏好,只恢复手机号和协议状态,不恢复密码。
|
||||
func applyPreferences(_ preferences: LoginPreferences) {
|
||||
if username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||||
let lastUsername = preferences.lastUsername {
|
||||
username = lastUsername
|
||||
}
|
||||
privacyChecked = preferences.privacyAgreementAccepted
|
||||
}
|
||||
|
||||
/// 校验登录表单,并返回第一个需要处理的错误。
|
||||
func validateForLogin() -> LoginValidationError? {
|
||||
guard isValidPhone else {
|
||||
return .invalidPhone
|
||||
}
|
||||
guard !trimmedPassword.isEmpty else {
|
||||
return .emptyPassword
|
||||
}
|
||||
guard privacyChecked else {
|
||||
return .privacyUnchecked
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// 用户同意协议后关闭协议确认弹窗。
|
||||
func acceptAgreement() {
|
||||
privacyChecked = true
|
||||
showsAgreementSheet = false
|
||||
}
|
||||
|
||||
/// 当输入包含 +86 前缀时,把手机号规范化为 11 位国内手机号。
|
||||
func normalizeUsernameCountryCodeIfNeeded() {
|
||||
let digits = username.filter(\.isNumber)
|
||||
let normalizedPhone = normalizedPhoneNumber(username)
|
||||
guard normalizedPhone != digits, normalizedPhone.count == 11 else { return }
|
||||
username = normalizedPhone
|
||||
}
|
||||
|
||||
/// 发起登录,并根据账号数量决定直接完成或进入账号选择。
|
||||
func login(authAPI: AuthAPI) async throws -> LoginResolution {
|
||||
guard !isLoading else {
|
||||
throw CancellationError()
|
||||
}
|
||||
|
||||
isLoading = true
|
||||
defer { isLoading = false }
|
||||
|
||||
let response = try await authAPI.login(
|
||||
username: normalizedUsername,
|
||||
password: trimmedPassword
|
||||
)
|
||||
return try await resolveLoginResponse(response, authAPI: authAPI)
|
||||
}
|
||||
|
||||
/// 选择一个账号并调用 set-user 换取正式 token。
|
||||
func selectAccount(_ account: AccountSwitchAccount, authAPI: AuthAPI) async throws -> V9AuthResponse {
|
||||
guard let payload = pendingAccountSelection, payload.hasTempToken else {
|
||||
throw LoginFlowError.missingToken
|
||||
}
|
||||
guard account.businessUserId > 0 else {
|
||||
throw LoginFlowError.invalidAccount
|
||||
}
|
||||
guard !isSelectingAccount else {
|
||||
throw CancellationError()
|
||||
}
|
||||
|
||||
isSelectingAccount = true
|
||||
defer { isSelectingAccount = false }
|
||||
|
||||
let response = try await authAPI.setUser(account.toSetUserRequest(), tokenOverride: payload.tempToken)
|
||||
guard !response.token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw LoginFlowError.missingToken
|
||||
}
|
||||
pendingAccountSelection = nil
|
||||
return response
|
||||
}
|
||||
|
||||
/// 清空待选账号信息,通常在用户取消账号选择时调用。
|
||||
func clearPendingAccountSelection() {
|
||||
pendingAccountSelection = nil
|
||||
}
|
||||
|
||||
/// 解析登录响应,单账号自动 set-user,多账号保留选择载荷。
|
||||
private func resolveLoginResponse(_ response: V9AuthResponse, authAPI: AuthAPI) async throws -> LoginResolution {
|
||||
let token = response.token.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !token.isEmpty else {
|
||||
throw LoginFlowError.missingToken
|
||||
}
|
||||
|
||||
let accounts = response.accounts.filter { $0.businessUserId > 0 }
|
||||
guard !accounts.isEmpty else {
|
||||
throw LoginFlowError.noAvailableAccount
|
||||
}
|
||||
|
||||
if accounts.count == 1, let account = accounts.first {
|
||||
let finalResponse = try await authAPI.setUser(account.toSetUserRequest(), tokenOverride: token)
|
||||
guard !finalResponse.token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
throw LoginFlowError.missingToken
|
||||
}
|
||||
return .completed(finalResponse)
|
||||
}
|
||||
|
||||
let payload = AccountSelectionPayload(tempToken: token, accounts: accounts)
|
||||
pendingAccountSelection = payload
|
||||
return .needsAccountSelection(payload)
|
||||
}
|
||||
|
||||
/// 过滤手机号中的非数字字符,并去掉 86 国家码前缀。
|
||||
private func normalizedPhoneNumber(_ value: String) -> String {
|
||||
var digits = value.filter(\.isNumber)
|
||||
if digits.hasPrefix("86"), digits.count == 13 {
|
||||
digits.removeFirst(2)
|
||||
}
|
||||
return digits
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user