实现权限驱动的首页 Tab 并对齐 Android

This commit is contained in:
2026-07-06 17:27:54 +08:00
parent e04ad8f8f0
commit d79d3003e3
27 changed files with 2573 additions and 10 deletions

View File

@ -45,6 +45,20 @@ enum AppRoleCode: String, CaseIterable, Equatable {
self == .photographer
}
/// 线//
static let homeMinimalTopRoles: Set<AppRoleCode> = [
.storeAdmin,
.editor,
.scenicCS,
.scenicAdmin,
.scenicOperation,
]
/// 使
var usesHomeMinimalTopLayout: Bool {
AppRoleCode.homeMinimalTopRoles.contains(self)
}
/// role_code
static func fromCode(_ code: String?) -> AppRoleCode? {
let normalized = code?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""

View File

@ -0,0 +1,66 @@
//
// HomeAPI.swift
// suixinkan
//
import Foundation
@MainActor
/// API
final class HomeAPI {
private let client: APIClient
init(client: APIClient) {
self.client = client
}
///
func rolePermissions() async throws -> [RolePermissionResponse] {
try await client.send(
APIRequest(method: .get, path: "/api/yf-handset-app/role-permission")
)
}
///
func storeList() async throws -> StoreListResponse {
try await client.send(
APIRequest(method: .get, path: "/api/app/store/all")
)
}
///
func locationDetail(staffId: String) async throws -> LocationDetailResponse {
try await client.send(
APIRequest(
method: .get,
path: "/api/yf-handset-app/photog/loacation/detail",
queryItems: [URLQueryItem(name: "staff_id", value: staffId)]
)
)
}
///
func reportLocation(
staffId: String,
latitude: Double,
longitude: Double,
address: String,
type: Int,
scenicId: String
) async throws -> LocationReportResponse {
try await client.send(
APIRequest(
method: .post,
path: "/api/yf-handset-app/photog/loacation/report",
queryItems: [
URLQueryItem(name: "staff_id", value: staffId),
URLQueryItem(name: "latitude", value: String(latitude)),
URLQueryItem(name: "longitude", value: String(longitude)),
URLQueryItem(name: "address", value: address),
URLQueryItem(name: "type", value: String(type)),
URLQueryItem(name: "scenic_id", value: scenicId),
]
)
)
}
}

View File

@ -0,0 +1,28 @@
//
// HomeMenuItem.swift
// suixinkan
//
import Foundation
/// URI catalog
struct HomeMenuItem: Equatable, Hashable, Sendable {
let uri: String
let title: String
let iconName: String
let serverName: String
init(uri: String, title: String, iconName: String, serverName: String = "") {
self.uri = uri
self.title = title
self.iconName = iconName
self.serverName = serverName
}
///
static let moreFunctions = HomeMenuItem(
uri: "more_functions",
title: "更多功能",
iconName: "square.grid.2x2"
)
}

View File

@ -0,0 +1,38 @@
//
// LocationModels.swift
// suixinkan
//
import Foundation
/// Android `LocationDetailResponse`
struct LocationDetailResponse: Decodable, Sendable {
let status: Int
let needReport: Bool
let expireTime: Int64
enum CodingKeys: String, CodingKey {
case status
case needReport = "need_report"
case expireTime = "expire_time"
}
init(status: Int = 0, needReport: Bool = true, expireTime: Int64 = 0) {
self.status = status
self.needReport = needReport
self.expireTime = expireTime
}
}
/// Android `LocationReportResponse`
struct LocationReportResponse: Decodable, Sendable {
let staffId: String
let expired: Int64
let status: Int
enum CodingKeys: String, CodingKey {
case staffId = "staff_id"
case expired
case status
}
}

View File

@ -0,0 +1,143 @@
//
// RolePermissionModels.swift
// suixinkan
//
import Foundation
/// Android `RolePermissionResponse`
struct RolePermissionResponse: Codable, Equatable, Sendable {
let role: RoleInfo
let scenic: [ScenicInfo]
init(role: RoleInfo, scenic: [ScenicInfo] = []) {
self.role = role
self.scenic = scenic
}
}
///
struct RoleInfo: Codable, Equatable, Sendable {
let id: Int
let name: String
let roleCode: String
let notes: String?
let permission: [PermissionItem]
enum CodingKeys: String, CodingKey {
case id
case name
case roleCode = "role_code"
case notes
case permission
}
init(
id: Int = 0,
name: String = "",
roleCode: String = "",
notes: String? = nil,
permission: [PermissionItem] = []
) {
self.id = id
self.name = name
self.roleCode = roleCode
self.notes = notes
self.permission = permission
}
}
///
struct PermissionItem: Codable, Equatable, Sendable {
let id: Int
let pid: Int
let name: String
let uri: String
let iconSrc: String?
let children: [PermissionItem]?
enum CodingKeys: String, CodingKey {
case id
case pid
case name
case uri
case iconSrc = "icon_src"
case children
}
init(
id: Int = 0,
pid: Int = 0,
name: String = "",
uri: String = "",
iconSrc: String? = nil,
children: [PermissionItem]? = nil
) {
self.id = id
self.pid = pid
self.name = name
self.uri = uri
self.iconSrc = iconSrc
self.children = children
}
}
///
struct ScenicInfo: Codable, Equatable, Sendable, Hashable {
let id: Int
let name: String
let status: Int
let location: ScenicLocationInfo?
let coverImg: String?
enum CodingKeys: String, CodingKey {
case id
case name
case status
case location
case coverImg = "cover_img"
}
init(
id: Int = 0,
name: String = "",
status: Int = 0,
location: ScenicLocationInfo? = nil,
coverImg: String? = nil
) {
self.id = id
self.name = name
self.status = status
self.location = location
self.coverImg = coverImg
}
}
///
struct ScenicLocationInfo: Codable, Equatable, Sendable, Hashable {
let lng: Double
let lat: Double
let address: String
}
/// 使
struct HomePermissionItem: Codable, Equatable, Sendable, Hashable {
let id: String
let name: String
let uri: String
let pid: Int
init(id: String, name: String, uri: String, pid: Int = 0) {
self.id = id
self.name = name
self.uri = uri
self.pid = pid
}
init(from item: PermissionItem) {
self.id = String(item.id)
self.name = item.name
self.uri = item.uri
self.pid = item.pid
}
}

View File

@ -0,0 +1,52 @@
//
// StoreModels.swift
// suixinkan
//
import Foundation
/// Android `StoreItem`
struct StoreItem: Codable, Equatable, Sendable {
let id: Int
let scenicId: Int
let name: String
let address: String
let status: Int
let statusText: String
enum CodingKeys: String, CodingKey {
case id
case scenicId = "scenic_id"
case name
case address
case status
case statusText = "status_text"
}
init(
id: Int = 0,
scenicId: Int = 0,
name: String = "",
address: String = "",
status: Int = 0,
statusText: String = ""
) {
self.id = id
self.scenicId = scenicId
self.name = name
self.address = address
self.status = status
self.statusText = statusText
}
}
/// Android `ListResponse<StoreItem>`
struct StoreListResponse: Codable, Sendable {
let total: Int
let list: [StoreItem]
init(total: Int = 0, list: [StoreItem] = []) {
self.total = total
self.list = list
}
}

View File

@ -0,0 +1,50 @@
//
// HomeCommonMenuStore.swift
// suixinkan
//
import Foundation
/// URI
final class HomeCommonMenuStore {
private let defaults: UserDefaults
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}
/// URI
func savedCommonURIs(accountScope: String, roleCode: String) -> [String] {
defaults.stringArray(forKey: storageKey(accountScope: accountScope, roleCode: roleCode)) ?? []
}
/// URI
func saveCommonURIs(_ uris: [String], accountScope: String, roleCode: String) {
defaults.set(uris, forKey: storageKey(accountScope: accountScope, roleCode: roleCode))
}
/// URI 4
static func defaultCommonURIs(from permissions: [HomePermissionItem]) -> [String] {
let uris = permissions.map(\.uri)
return uris.count > 4 ? Array(uris.prefix(4)) : uris
}
///
func commonMenus(
from allMenus: [HomeMenuItem],
permissions: [HomePermissionItem],
accountScope: String,
roleCode: String
) -> [HomeMenuItem] {
let saved = savedCommonURIs(accountScope: accountScope, roleCode: roleCode)
let defaultURIs = Self.defaultCommonURIs(from: permissions)
let commonURIs = saved.isEmpty ? defaultURIs : saved
let commonSet = Set(commonURIs)
return allMenus.filter { commonSet.contains($0.uri) }
}
private func storageKey(accountScope: String, roleCode: String) -> String {
"\(accountScope)_role_\(roleCode)_common_uris"
}
}

View File

@ -0,0 +1,97 @@
//
// HomeLocationProvider.swift
// suixinkan
//
import CoreLocation
///
struct HomeLocationSnapshot: Sendable {
let latitude: Double
let longitude: Double
let address: String
}
/// CoreLocation
final class HomeLocationProvider: NSObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
private var coordinateContinuation: CheckedContinuation<CLLocationCoordinate2D, Error>?
override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
}
///
func requestSnapshot() async throws -> HomeLocationSnapshot {
let status = manager.authorizationStatus
if status == .notDetermined {
manager.requestWhenInUseAuthorization()
try await Task.sleep(nanoseconds: 300_000_000)
}
let resolvedStatus = manager.authorizationStatus
guard resolvedStatus == .authorizedWhenInUse || resolvedStatus == .authorizedAlways else {
throw HomeLocationProviderError.permissionDenied
}
let coordinate = try await requestCoordinate()
let address = await reverseGeocode(latitude: coordinate.latitude, longitude: coordinate.longitude)
return HomeLocationSnapshot(
latitude: coordinate.latitude,
longitude: coordinate.longitude,
address: address
)
}
private func requestCoordinate() async throws -> CLLocationCoordinate2D {
try await withCheckedThrowingContinuation { continuation in
self.coordinateContinuation = continuation
manager.requestLocation()
}
}
private func reverseGeocode(latitude: Double, longitude: Double) async -> String {
let location = CLLocation(latitude: latitude, longitude: longitude)
let geocoder = CLGeocoder()
do {
let placemarks = try await geocoder.reverseGeocodeLocation(location)
return placemarks.first?.formattedAddress ?? ""
} catch {
return ""
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
coordinateContinuation?.resume(returning: location.coordinate)
coordinateContinuation = nil
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
coordinateContinuation?.resume(throwing: error)
coordinateContinuation = nil
}
}
///
enum HomeLocationProviderError: LocalizedError {
case permissionDenied
var errorDescription: String? {
switch self {
case .permissionDenied: "需要位置权限才能上线"
}
}
}
private extension CLPlacemark {
var formattedAddress: String {
[subLocality, locality, administrativeArea]
.compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
.joined(separator: "")
}
}

View File

@ -0,0 +1,139 @@
//
// HomeLocationStateStore.swift
// suixinkan
//
import Foundation
/// 线 2 Android `LocationStateRepository`
final class HomeLocationStateStore {
static let onlineDurationMillis: Int64 = 2 * 60 * 60 * 1000
private(set) var isOnline = false
private(set) var elapsedSeconds: Int64 = 0
private(set) var nextReportCountdownSeconds: Int64 = 0
private(set) var reminderMinutes = 0
var onStateChange: (() -> Void)?
private let store: AppStore
private var countdownTask: Task<Void, Never>?
private var anchorTimestamp: Int64?
init(store: AppStore = .shared) {
self.store = store
reminderMinutes = store.locationReminderMinutes
isOnline = store.onlineStatus
}
/// 线
func restoreStateIfNeeded() {
guard store.onlineStatus else { return }
let lastTime = store.lastLocationReportTime
guard lastTime > 0 else { return }
let now = Int64(Date().timeIntervalSince1970 * 1000)
let elapsed = now - lastTime
if elapsed >= Self.onlineDurationMillis {
updateOnlineStatus(false)
store.clearLastLocationReportTime()
notifyChange()
return
}
anchorTimestamp = lastTime
let remaining = Self.onlineDurationMillis - elapsed
elapsedSeconds = max(0, elapsed / 1000)
nextReportCountdownSeconds = max(0, remaining / 1000)
startCountdown(anchorTime: lastTime)
notifyChange()
}
/// 线
func updateOnlineStatus(_ online: Bool) {
isOnline = online
store.onlineStatus = online
if !online {
stopCountdown()
store.clearLastLocationReportTime()
}
notifyChange()
}
///
func updateReminderMinutes(_ minutes: Int) {
reminderMinutes = minutes
store.locationReminderMinutes = minutes
notifyChange()
}
///
func startLocationReport(at timestamp: Int64 = Int64(Date().timeIntervalSince1970 * 1000)) {
anchorTimestamp = timestamp
store.lastLocationReportTime = timestamp
isOnline = true
store.onlineStatus = true
elapsedSeconds = 0
nextReportCountdownSeconds = Self.onlineDurationMillis / 1000
startCountdown(anchorTime: timestamp)
notifyChange()
}
/// `HH:MM:SS`
func formattedCountdown(from seconds: Int64) -> String {
let hours = seconds / 3600
let minutes = (seconds % 3600) / 60
let secs = seconds % 60
return String(format: "%02d:%02d:%02d", hours, minutes, secs)
}
var countdownDisplayText: String {
formattedCountdown(from: nextReportCountdownSeconds)
}
///
func shouldTriggerTimeoutReminder() -> Bool {
guard reminderMinutes > 0, isOnline else { return false }
let reminderSeconds = Int64(reminderMinutes * 60)
return nextReportCountdownSeconds > 0 && nextReportCountdownSeconds <= reminderSeconds
}
private func startCountdown(anchorTime: Int64) {
countdownTask?.cancel()
countdownTask = Task { [weak self] in
while !Task.isCancelled {
guard let self else { return }
guard self.isOnline else { return }
let now = Int64(Date().timeIntervalSince1970 * 1000)
let elapsed = now - anchorTime
let remaining = Self.onlineDurationMillis - elapsed
let elapsedSeconds = max(0, elapsed / 1000)
self.elapsedSeconds = elapsedSeconds
if remaining <= 0 {
self.nextReportCountdownSeconds = 0
self.updateOnlineStatus(false)
self.store.clearLastLocationReportTime()
return
}
self.nextReportCountdownSeconds = max(0, remaining / 1000)
self.notifyChange()
try? await Task.sleep(nanoseconds: 1_000_000_000)
}
}
}
private func stopCountdown() {
countdownTask?.cancel()
countdownTask = nil
anchorTimestamp = nil
elapsedSeconds = 0
nextReportCountdownSeconds = 0
}
private func notifyChange() {
onStateChange?()
}
}

View File

@ -0,0 +1,58 @@
//
// HomeMenuCatalog.swift
// suixinkan
//
import Foundation
/// catalog permission URI
enum HomeMenuCatalog {
/// Android `Constants.menuList`
static let allItems: [HomeMenuItem] = [
HomeMenuItem(uri: "space_settings", title: "空间设置", iconName: "gearshape"),
HomeMenuItem(uri: "wallet", title: "我的钱包", iconName: "wallet.pass"),
HomeMenuItem(uri: "cloud_management", title: "相册云盘", iconName: "icloud"),
HomeMenuItem(uri: "asset_management", title: "素材管理", iconName: "photo.on.rectangle"),
HomeMenuItem(uri: "task_management", title: "任务管理", iconName: "checklist"),
HomeMenuItem(uri: "task_management_editor", title: "任务管理", iconName: "checklist"),
HomeMenuItem(uri: "schedule_management", title: "日程管理", iconName: "calendar"),
HomeMenuItem(uri: "system_settings", title: "设置中心", iconName: "slider.horizontal.3"),
HomeMenuItem(uri: "message_center", title: "消息中心", iconName: "bell"),
HomeMenuItem(uri: "checkin_points", title: "打卡点管理", iconName: "mappin.and.ellipse"),
HomeMenuItem(uri: "sample_management", title: "样片管理", iconName: "photo.stack"),
HomeMenuItem(uri: "live_stream_management", title: "直播管理", iconName: "video"),
HomeMenuItem(uri: "verification_order", title: "核销订单", iconName: "checkmark.seal"),
HomeMenuItem(uri: "live_album", title: "直播相册", iconName: "photo.on.rectangle.angled"),
HomeMenuItem(uri: "pm", title: "项目管理", iconName: "folder"),
HomeMenuItem(uri: "pm_manager", title: "项目管理", iconName: "folder"),
HomeMenuItem(uri: "location_report", title: "位置上报", iconName: "location"),
HomeMenuItem(uri: "registration_invitation", title: "注册邀请", iconName: "person.badge.plus"),
HomeMenuItem(uri: "store", title: "店铺管理", iconName: "building.2"),
HomeMenuItem(uri: "fly", title: "飞行管理", iconName: "airplane"),
HomeMenuItem(uri: "pilot_cert", title: "飞手认证", iconName: "person.text.rectangle"),
HomeMenuItem(uri: "pilot_controller", title: "飞控", iconName: "gamecontroller"),
HomeMenuItem(uri: "/scenic-queue", title: "排队管理", iconName: "person.3"),
HomeMenuItem(uri: "operating-area", title: "运营区域", iconName: "map"),
HomeMenuItem(uri: "/scenic-order-manage", title: "景区订单", iconName: "doc.text"),
HomeMenuItem(uri: "cooperation_order", title: "合作订单", iconName: "person.2"),
]
///
static func visibleMenus(from permissions: [HomePermissionItem]) -> [HomeMenuItem] {
permissions.compactMap { permission in
guard let catalog = allItems.first(where: { $0.uri == permission.uri }) else { return nil }
return HomeMenuItem(
uri: catalog.uri,
title: catalog.title,
iconName: catalog.iconName,
serverName: permission.name
)
}
}
/// catalog
static func item(for uri: String) -> HomeMenuItem? {
allItems.first { $0.uri == uri }
}
}

View File

@ -0,0 +1,108 @@
//
// HomeRouteHandler.swift
// suixinkan
//
import UIKit
/// permission URI
enum HomeRouteHandler {
///
@MainActor
static func open(
uri: String,
from viewController: UIViewController,
storeItem: StoreItem?
) {
if uri == "pilot_controller" || uri == "more_functions" {
showDeveloping(from: viewController)
return
}
if uri != "pilot_controller", AppStore.shared.currentScenicId <= 0 {
showToast("请先选择景区", from: viewController)
return
}
switch uri {
case "verification_order":
selectTab(.orders, from: viewController)
case "photographer_stats":
selectTab(.statistics, from: viewController)
case "system_settings", "space_settings":
selectTab(.profile, from: viewController)
case "pilot_cert":
let controller = RealNameAuthViewController()
viewController.navigationController?.pushViewController(controller, animated: true)
case "operating-area":
handleOperatingArea(from: viewController, storeItem: storeItem)
case "cooperation_order":
if !hasCooperationOrderPermission() {
showToast("暂无合作订单权限", from: viewController)
return
}
showDeveloping(from: viewController)
default:
showDeveloping(from: viewController)
}
}
@MainActor
private static func handleOperatingArea(from viewController: UIViewController, storeItem: StoreItem?) {
guard let role = AppStore.shared.currentAppRole else {
showToast("当前账号暂不支持运营区域", from: viewController)
return
}
switch role {
case .storeAdmin:
guard let storeItem, storeItem.id > 0 else {
showToast("请先选择店铺", from: viewController)
return
}
showDeveloping(from: viewController)
case .scenicAdmin:
guard AppStore.shared.currentScenicId > 0 else {
showToast("请先选择景区", from: viewController)
return
}
showDeveloping(from: viewController)
default:
showToast("当前账号暂不支持运营区域", from: viewController)
}
}
private static func hasCooperationOrderPermission() -> Bool {
let permissions = AppStore.shared.permissionItems()
return permissions.contains { $0.uri == "cooperation_order" }
|| permissions.contains(where: { containsCooperationOrder(in: $0) })
}
private static func containsCooperationOrder(in item: HomePermissionItem) -> Bool {
item.uri == "cooperation_order"
}
@MainActor
private static func selectTab(_ tab: AppTab, from viewController: UIViewController) {
guard let tabBar = viewController.tabBarController as? MainTabBarController else { return }
tabBar.selectTab(tab)
}
@MainActor
private static func showDeveloping(from viewController: UIViewController) {
showToast("功能开发中", from: viewController)
}
@MainActor
private static func showToast(_ message: String, from viewController: UIViewController) {
if let base = viewController as? BaseViewController {
base.showToast(message)
return
}
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
viewController.present(alert, animated: true)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
alert.dismiss(animated: true)
}
}
}

View File

@ -0,0 +1,39 @@
//
// RolePermissionMatcher.swift
// suixinkan
//
import Foundation
/// `role-permission`
enum RolePermissionMatcher {
/// role_code legacy id role_name
static func match(
in list: [RolePermissionResponse],
roleCode: String,
roleName: String,
legacyRoleId: Int = 0
) -> RolePermissionResponse? {
if let role = AppRoleCode.fromCode(roleCode),
let matched = list.first(where: { AppRoleCode.fromCode($0.role.roleCode) == role }) {
return matched
}
if legacyRoleId > 0,
let matched = list.first(where: { $0.role.id == legacyRoleId }) {
return matched
}
let trimmedName = roleName.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmedName.isEmpty {
return list.first { item in
let itemName = item.role.name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !itemName.isEmpty else { return false }
return itemName.contains(trimmedName) || trimmedName.contains(itemName)
}
}
return nil
}
}

View File

@ -0,0 +1,418 @@
//
// HomeViewModel.swift
// suixinkan
//
import Foundation
/// ViewModel Android `HomeViewModel`
final class HomeViewModel {
private(set) var currentScenicName = ""
private(set) var currentAppRole: AppRoleCode?
private(set) var commonMenus: [HomeMenuItem] = []
private(set) var storeItem: StoreItem?
private(set) var showPermissionDialog = false
private(set) var showScenicDialog = false
private(set) var showLocationTimeoutDialog = false
private(set) var showOnlineStatusDialog = false
private(set) var showLocationReportSuccessDialog = false
private(set) var isMinimalTopRole = false
private(set) var locationInfoText = "定位中..."
private(set) var reportTimeText = ""
private(set) var isLocationReporting = false
private(set) var needsPermissionReload = false
var onStateChange: (() -> Void)?
var onShowMessage: ((String) -> Void)?
let locationStateStore: HomeLocationStateStore
private let appStore: AppStore
private let commonMenuStore: HomeCommonMenuStore
private let locationProvider: HomeLocationProvider
private var lastOnlineStatusSwitchTime: Int64 = 0
private var lastLocationReportTime: Int64 = 0
private var timeoutDialogTriggered = false
private var dismissedLocationTimeoutDialog = false
private let operationIntervalMillis: Int64 = 30_000
init(
appStore: AppStore = .shared,
locationStateStore: HomeLocationStateStore = HomeLocationStateStore(),
commonMenuStore: HomeCommonMenuStore = HomeCommonMenuStore(),
locationProvider: HomeLocationProvider = HomeLocationProvider()
) {
self.appStore = appStore
self.locationStateStore = locationStateStore
self.commonMenuStore = commonMenuStore
self.locationProvider = locationProvider
self.locationStateStore.onStateChange = { [weak self] in
self?.notifyStateChange()
}
}
var isOnline: Bool { locationStateStore.isOnline }
var countdownDisplayText: String { locationStateStore.countdownDisplayText }
var reminderMinutes: Int { locationStateStore.reminderMinutes }
/// 线
func initialize(api: HomeAPI) async {
locationStateStore.restoreStateIfNeeded()
refreshLocalDisplayState()
await loadPermissions(api: api, force: true)
}
///
func markNeedsPermissionReload() {
needsPermissionReload = true
}
///
func reloadIfNeeded(api: HomeAPI) async {
guard needsPermissionReload else {
refreshLocalDisplayState()
rebuildCommonMenus()
await loadStoreListIfNeeded(api: api)
notifyStateChange()
return
}
needsPermissionReload = false
await loadPermissions(api: api, force: true)
}
/// role-permission
func loadPermissions(api: HomeAPI, force: Bool = false) async {
if !force, !appStore.permissionItems().isEmpty {
rebuildCommonMenus()
await loadStoreListIfNeeded(api: api)
notifyStateChange()
return
}
do {
let rolePermissionList = try await api.rolePermissions()
if rolePermissionList.isEmpty {
appStore.savePermissionItems([])
showPermissionDialog = true
rebuildCommonMenus()
notifyStateChange()
return
}
appStore.saveRolePermissionList(rolePermissionList)
let matched = appStore.matchRolePermissionItem(in: rolePermissionList) ?? rolePermissionList[0]
if !matched.role.name.isEmpty {
appStore.roleName = matched.role.name
}
appStore.saveRoleScenicList(matched.scenic)
let permissions = matched.role.permission.map(HomePermissionItem.init)
appStore.savePermissionItems(permissions)
showPermissionDialog = false
refreshLocalDisplayState()
rebuildCommonMenus()
await loadStoreListIfNeeded(api: api)
notifyStateChange()
} catch is CancellationError {
return
} catch {
appStore.savePermissionItems([])
showPermissionDialog = true
rebuildCommonMenus()
onShowMessage?(error.localizedDescription)
notifyStateChange()
}
}
///
func loadStoreListIfNeeded(api: HomeAPI) async {
guard currentAppRole == .storeAdmin else {
storeItem = nil
notifyStateChange()
return
}
guard appStore.currentScenicId > 0 else {
storeItem = nil
notifyStateChange()
return
}
do {
let response = try await api.storeList()
let scenicId = appStore.currentScenicId
let savedStoreId = appStore.currentStoreId
let savedMatch = savedStoreId > 0 ? response.list.first { $0.id == savedStoreId } : nil
let matched = savedMatch ?? response.list.first { $0.scenicId == scenicId }
storeItem = matched
if let matched {
appStore.currentStoreId = matched.id
}
notifyStateChange()
} catch is CancellationError {
return
} catch {
storeItem = nil
notifyStateChange()
}
}
/// > >
func evaluateDialogs(api: HomeAPI) async {
if showPermissionDialog {
showScenicDialog = false
return
}
let hasScenic = appStore.currentScenicId > 0
showScenicDialog = !hasScenic
if showScenicDialog || dismissedLocationTimeoutDialog {
showLocationTimeoutDialog = false
notifyStateChange()
return
}
guard !isMinimalTopRole else {
showLocationTimeoutDialog = false
notifyStateChange()
return
}
try? await Task.sleep(nanoseconds: 500_000_000)
await checkLocationTimeout(api: api)
}
///
func checkLocationTimeout(api: HomeAPI) async {
guard reminderMinutes > 0 else {
showLocationTimeoutDialog = false
notifyStateChange()
return
}
let staffId = appStore.userId.trimmingCharacters(in: .whitespacesAndNewlines)
guard !staffId.isEmpty else {
showLocationTimeoutDialog = true
notifyStateChange()
return
}
do {
let detail = try await api.locationDetail(staffId: staffId)
if detail.expireTime <= 0 {
showLocationTimeoutDialog = true
notifyStateChange()
return
}
let currentMillis = Int64(Date().timeIntervalSince1970 * 1000)
let expireMillis = detail.expireTime * 1000
let threshold = expireMillis - Int64(reminderMinutes * 60 * 1000)
showLocationTimeoutDialog = currentMillis >= threshold
notifyStateChange()
} catch is CancellationError {
return
} catch {
showLocationTimeoutDialog = true
notifyStateChange()
}
}
///
func refreshLocalDisplayState() {
currentScenicName = appStore.currentScenicName.trimmingCharacters(in: .whitespacesAndNewlines)
currentAppRole = appStore.currentAppRole
isMinimalTopRole = currentAppRole?.usesHomeMinimalTopLayout ?? false
}
///
func rebuildCommonMenus() {
let permissions = appStore.permissionItems()
let allMenus = HomeMenuCatalog.visibleMenus(from: permissions)
commonMenus = commonMenuStore.commonMenus(
from: allMenus,
permissions: permissions,
accountScope: appStore.accountCachePrefix,
roleCode: appStore.roleCode
)
}
func hidePermissionDialog() {
showPermissionDialog = false
notifyStateChange()
}
func hideScenicDialog() {
showScenicDialog = false
notifyStateChange()
}
func showOnlineStatusSwitchDialog() {
showOnlineStatusDialog = true
notifyStateChange()
}
func hideOnlineStatusSwitchDialog() {
showOnlineStatusDialog = false
notifyStateChange()
}
func hideLocationTimeoutDialog() {
showLocationTimeoutDialog = false
dismissedLocationTimeoutDialog = true
timeoutDialogTriggered = false
locationStateStore.updateOnlineStatus(false)
notifyStateChange()
}
func hideLocationReportSuccessDialog() {
showLocationReportSuccessDialog = false
notifyStateChange()
}
func updateReminderMinutes(_ minutes: Int) {
locationStateStore.updateReminderMinutes(minutes)
notifyStateChange()
}
/// 线/线
func switchOnlineStatus(api: HomeAPI) async {
let now = currentTimestampMillis()
if now - lastOnlineStatusSwitchTime < operationIntervalMillis {
let remaining = Int((operationIntervalMillis - (now - lastOnlineStatusSwitchTime)) / 1000)
onShowMessage?("操作过于频繁,请\(remaining)秒后再试")
hideOnlineStatusSwitchDialog()
return
}
guard appStore.currentScenicId > 0 else {
onShowMessage?("请先选择景区")
hideOnlineStatusSwitchDialog()
return
}
let goingOnline = !isOnline
if goingOnline {
do {
_ = try await locationProvider.requestSnapshot()
} catch {
onShowMessage?(error.localizedDescription)
hideOnlineStatusSwitchDialog()
return
}
locationStateStore.updateOnlineStatus(true)
timeoutDialogTriggered = false
dismissedLocationTimeoutDialog = false
lastOnlineStatusSwitchTime = now
onShowMessage?("已切换到在线状态,正在上报位置")
hideOnlineStatusSwitchDialog()
await reportLocation(api: api, type: 1)
} else {
locationStateStore.updateOnlineStatus(false)
lastOnlineStatusSwitchTime = now
onShowMessage?("已切换到离线状态")
hideOnlineStatusSwitchDialog()
await reportLocation(api: api, type: 3)
}
}
///
func manualReportLocation(api: HomeAPI) async {
let now = currentTimestampMillis()
if now - lastLocationReportTime < operationIntervalMillis {
let remaining = Int((operationIntervalMillis - (now - lastLocationReportTime)) / 1000)
onShowMessage?("操作过于频繁,请\(remaining)秒后再试")
return
}
await reportLocation(api: api, type: 1)
}
///
func confirmLocationTimeoutReport(api: HomeAPI) async {
showLocationTimeoutDialog = false
dismissedLocationTimeoutDialog = false
await reportLocation(api: api, type: 1)
}
///
func triggerLocationTimeoutIfNeeded() {
guard locationStateStore.shouldTriggerTimeoutReminder() else { return }
guard !timeoutDialogTriggered else { return }
timeoutDialogTriggered = true
showLocationTimeoutDialog = true
notifyStateChange()
}
///
func refreshLocationInfo() async {
isLocationReporting = true
notifyStateChange()
defer {
isLocationReporting = false
notifyStateChange()
}
do {
let snapshot = try await locationProvider.requestSnapshot()
locationInfoText = snapshot.address.isEmpty
? String(format: "%.5f, %.5f", snapshot.latitude, snapshot.longitude)
: snapshot.address
} catch {
locationInfoText = "定位失败"
}
}
private func reportLocation(api: HomeAPI, type: Int) async {
guard appStore.currentScenicId > 0 else {
onShowMessage?("请先选择景区")
return
}
let staffId = appStore.userId.trimmingCharacters(in: .whitespacesAndNewlines)
guard !staffId.isEmpty else {
onShowMessage?("获取用户ID失败")
return
}
isLocationReporting = true
notifyStateChange()
defer {
isLocationReporting = false
notifyStateChange()
}
do {
let snapshot = try await locationProvider.requestSnapshot()
locationInfoText = snapshot.address.isEmpty
? String(format: "%.5f, %.5f", snapshot.latitude, snapshot.longitude)
: snapshot.address
_ = try await api.reportLocation(
staffId: staffId,
latitude: snapshot.latitude,
longitude: snapshot.longitude,
address: snapshot.address,
type: type,
scenicId: String(appStore.currentScenicId)
)
lastLocationReportTime = currentTimestampMillis()
if type != 3 {
locationStateStore.startLocationReport()
reportTimeText = formattedNow()
showLocationReportSuccessDialog = true
timeoutDialogTriggered = false
dismissedLocationTimeoutDialog = false
}
notifyStateChange()
} catch is CancellationError {
return
} catch {
onShowMessage?(error.localizedDescription)
}
}
private func formattedNow() -> String {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.string(from: Date())
}
private func currentTimestampMillis() -> Int64 {
Int64(Date().timeIntervalSince1970 * 1000)
}
private func notifyStateChange() {
onStateChange?()
}
}