import React, { createContext, useContext, useState, useEffect } from 'react';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [permissions, setPermissions] = useState([]);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    // 从localStorage加载用户和权限信息
    const storedUser = localStorage.getItem('user');
    const storedPermissions = localStorage.getItem('permissions');
    
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    }
    
    if (storedPermissions) {
      setPermissions(JSON.parse(storedPermissions));
    }
    
    setLoading(false);
  }, []);
  
  // 检查用户是否有特定权限
  const hasPermission = (permissionName) => {
    return permissions.includes(permissionName);
  };
  
  // 检查用户是否有特定角色
  const hasRole = (roleName) => {
    return user?.role === roleName;
  };
  
  return (
    <AuthContext.Provider value={{ user, permissions, hasPermission, hasRole, loading }}>
      {children}
    </AuthContext.Provider>
  );
};

// 自定义hook方便使用
export const useAuth = () => useContext(AuthContext);