import { Toast } from "tdesign-mobile-vue"; import { useUserStore } from "timi-web"; import StoreAPI from "@/api/StoreAPI"; import type { Store } from "@/types/Store"; import { getCurrentStoreId, readStoredCurrentStoreId, setCurrentStoreId } from "@/utils/store"; export const useCurrentStoreStore = defineStore("currentStore", () => { const userStore = useUserStore(); const storeList = ref([]); const currentStoreId = ref(readStoredCurrentStoreId()); const loginStore = ref(); const loginStoreUserId = ref(""); const isLoading = ref(false); let loginStoreRequest: Promise | undefined; let loginStoreRequestUserId = ""; const currentStore = computed(() => storeList.value.find(item => item.id === currentStoreId.value)); const currentStoreName = computed(() => currentStore.value?.name || "默认门店"); async function loadStoreList(): Promise { if (isLoading.value) { return; } isLoading.value = true; try { const result = await StoreAPI.list({ index: 0, size: 1000, equalsExample: { status: "ACTIVE" }, orderMap: { sort: "ASC", createdAt: "DESC" } }); storeList.value = result.list || []; normalizeCurrentStoreId(); } catch { Toast.error("门店列表加载失败"); } finally { isLoading.value = false; } } async function loadLoginStore(): Promise { const loginUserId = userStore.loginUser.user?.id || userStore.loginUser.id || ""; if (loginStore.value?.id && loginStoreUserId.value === loginUserId) { return loginStore.value; } if (!loginStoreRequest || loginStoreRequestUserId !== loginUserId) { loginStoreRequestUserId = loginUserId; loginStoreRequest = loadLoginStoreRequest(loginUserId); } const request = loginStoreRequest; try { return await request; } finally { if (loginStoreRequest === request) { loginStoreRequest = undefined; } } } async function loadLoginStoreRequest(loginUserId: string): Promise { const result = await StoreAPI.loginStore(); loginStore.value = result; loginStoreUserId.value = loginUserId; if (result.id) { selectStore(result.id); } return result; } function selectStore(storeId: string): void { if (!storeId) { return; } currentStoreId.value = storeId; setCurrentStoreId(storeId); } function normalizeCurrentStoreId(): void { const storedStoreId = getCurrentStoreId(); if (storeList.value.some(item => item.id === storedStoreId)) { selectStore(storedStoreId); return; } const firstStoreId = storeList.value[0]?.id; if (firstStoreId) { selectStore(firstStoreId); } } return { storeList, currentStoreId, currentStore, loginStore, currentStoreName, isLoading, loadStoreList, loadLoginStore, selectStore }; });