// 认证状态管理 - 使用Zustand import { create } from 'zustand' import { persist } from 'zustand/middleware' interface User { id: number username: string name: string role: string department?: string } interface AuthState { token: string | null user: User | null isAuthenticated: boolean loading: boolean error: string | null // Actions login: (username: string, password: string) => Promise logout: () => void setToken: (token: string) => void setUser: (user: User) => void clearError: () => void } export const useAuthStore = create()( persist( (set) => ({ token: null, user: null, isAuthenticated: false, loading: false, error: null, login: async (username: string, password: string) => { set({ loading: true, error: null }) try { const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }) const result = await response.json() if (result.success) { set({ token: result.data.token, user: result.data.user, isAuthenticated: true, loading: false }) } else { set({ error: result.error || '登录失败', loading: false }) throw new Error(result.error || '登录失败') } } catch (error) { set({ error: error instanceof Error ? error.message : '登录失败', loading: false }) throw error } }, logout: () => { set({ token: null, user: null, isAuthenticated: false, error: null }) }, setToken: (token: string) => { set({ token, isAuthenticated: true }) }, setUser: (user: User) => { set({ user }) }, clearError: () => { set({ error: null }) } }), { name: 'auth-storage', partialize: (state) => ({ token: state.token, user: state.user, isAuthenticated: state.isAuthenticated }) } ) )