stores.ts 1.36 KB
import type { UsAppBoundLocationDto } from '../types/usAppBound'
import { getBoundLocations } from './authSession'

export type StoreInfo = UsAppBoundLocationDto

export { getBoundLocations } from './authSession'

export const STORE_CHANGED_EVENT = 'store:changed'

export function getCurrentStoreId(): string {
  return uni.getStorageSync('storeId') || ''
}

export function getCurrentStoreName(): string {
  const saved = uni.getStorageSync('storeName')
  return typeof saved === 'string' ? saved.trim() : ''
}

export function switchStore(id: string, storeName: string, locationCode?: string) {
  const nextId = String(id || '').trim()
  const nextName = String(storeName || '').trim()
  const nextCode = String(locationCode || '').trim()
  uni.setStorageSync('storeId', nextId)
  uni.setStorageSync('storeName', nextName)
  if (nextCode) {
    uni.setStorageSync('storeLocationCode', nextCode)
  } else {
    uni.removeStorageSync('storeLocationCode')
  }
  uni.$emit(STORE_CHANGED_EVENT, {
    id: nextId,
    storeName: nextName,
    locationCode: nextCode,
  })
}

/** 顶部药丸展示用,如 LOC-1 */
export function getCurrentLocationCode(): string {
  const saved = uni.getStorageSync('storeLocationCode')
  if (saved) return saved
  const id = getCurrentStoreId()
  if (!id) return ''
  const row = getBoundLocations().find((l) => l.id === id)
  return row?.locationCode || ''
}