import React, { createContext, useContext, ReactNode, useEffect } from 'react';
import useGlobalStore from '@/store/globalStore';
import type { User } from '@pwc-ra/components';

// 租户类型
interface Tenant {
  id: string;
  code: string;
  name: string;
}

// 全局上下文类型
interface GlobalContextType {
  currentUser: User | null;
  selectedTenant: Tenant | null;
  loading: boolean;
  error: string | null;
  setSelectedTenant: (tenant: Tenant | null) => void;
}

// 创建全局上下文
const GlobalContext = createContext<GlobalContextType | undefined>(undefined);

// 全局上下文提供者属性
interface GlobalProviderProps {
  children: ReactNode;
}

// 全局上下文提供者
export const GlobalProvider: React.FC<GlobalProviderProps> = ({ children }) => {
  // 从全局状态获取数据
  const { 
    currentUser, 
    selectedTenant, 
    loading, 
    error, 
    setSelectedTenant,
    initialize 
  } = useGlobalStore();
  
  // 确保全局状态在组件挂载时初始化
  useEffect(() => {
    initialize();
  }, [initialize]);
  
  // 提供全局上下文
  const value = {
    currentUser,
    selectedTenant,
    loading,
    error,
    setSelectedTenant
  };
  
  return (
    <GlobalContext.Provider value={value}>
      {children}
    </GlobalContext.Provider>
  );
};

// 使用全局上下文的钩子
export const useGlobal = (): GlobalContextType => {
  const context = useContext(GlobalContext);
  if (context === undefined) {
    throw new Error('useGlobal must be used within a GlobalProvider');
  }
  return context;
}; 