You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

120 lines
3.0 KiB

/**
* 租户状态管理
* 使用 Zustand + AsyncStorage 持久化
*/
import { create } from 'zustand';
// import { useShallow } from 'zustand/react/shallow';
import storageManager, { STORAGE_KEYS } from '@/utils/storageManager';
import { tenantService } from '@/services';
import { get, find } from 'lodash-es';
/**
* 租户信息接口
*/
export interface Tenant {
tid: number;
proxy: number;
create_time: string;
domain_addr: string;
logo_manage: Record<string, any>[];
}
// 状态
interface State {
tenantInfo: Tenant | null;
}
// 操作
interface Actions {
setTenantInfo: (data: Tenant) => void;
}
/**
* 租户状态 Store
*/
const useTenantStore = create<State & Actions>()((set, get) => ({
// 初始状态
tenantInfo: null,
// 设置租户信息(通用方法,包含持久化逻辑)
setTenantInfo: (data: any) => {
set({ tenantInfo: data });
// 手动持久化
storageManager.session.setItem(STORAGE_KEYS.TENANT_STORE, get());
storageManager.session.setItem(STORAGE_KEYS.TENANT_TID, data?.tid ?? '');
if (__DEV__) {
console.log('💾 Tenant info saved:', data);
}
},
}));
// 从 AsyncStorage 恢复状态的函数
export const restoreTenantState = async () => {
try {
const stored = storageManager.session.getItem(STORAGE_KEYS.TENANT_STORE);
if (stored) {
const state = JSON.parse(stored);
useTenantStore.setState(state);
if (__DEV__) {
console.log('✅ Tenant state restored from storage');
}
}
} catch (error) {
console.error('Failed to restore tenant state:', error);
}
};
/**
* 选择器 Hooks(优化性能,避免不必要的重渲染)
*/
// 获取 store state 租户信息
export const useTenantInfo = () => useTenantStore((state) => state.tenantInfo);
// 租户数据是否加载完成
export const useTenantLoad = () =>
useTenantStore((state) => !!state.tenantInfo?.tid || !!state.tenantInfo?.create_time);
// 获取 logo
export const useLogo = (): string =>
useTenantStore((state) => {
return get(
find(state.tenantInfo?.logo_manage, (item) => item.message_id === 29 && item.pic_addr),
'pic_addr'
);
});
// 获取 download logo
export const useDownloadLogo = (): string =>
useTenantStore((state) => {
return get(
find(state.tenantInfo?.logo_manage, (item) => item.message_id === 34 && item.pic_addr),
'pic_addr'
);
});
// 获取租户信息
export const requestTenantInfo = async (): Promise<Tenant> => {
try {
// 使用 getState() 而不是 hook
const { setTenantInfo } = useTenantStore.getState();
const params = {
domain_addr: 'https://51zhh5.notbug.org',
};
const { data } = await tenantService.getPlatformData(params);
setTenantInfo(data);
if (__DEV__) {
console.log('✅ Tenant info loaded:', data);
}
return Promise.resolve(data);
} catch (error) {
console.error('Failed to request tenant info:', error);
return Promise.reject(error);
}
};
export default useTenantStore;