import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../api/api_client.dart'; import '../api/auth_api.dart'; import '../models/user.dart'; final apiClientProvider = Provider((ref) => ApiClient()); final authApiProvider = Provider((ref) { return AuthApi(ref.read(apiClientProvider)); }); class AuthState { final bool isLoggedIn; final User? user; final String? token; final bool isLoading; final String? error; const AuthState({ this.isLoggedIn = false, this.user, this.token, this.isLoading = false, this.error, }); AuthState copyWith({ bool? isLoggedIn, User? user, String? token, bool? isLoading, String? error, }) { return AuthState( isLoggedIn: isLoggedIn ?? this.isLoggedIn, user: user ?? this.user, token: token ?? this.token, isLoading: isLoading ?? this.isLoading, error: error ?? this.error, ); } } class AuthNotifier extends StateNotifier { final AuthApi _api; final ApiClient _client; AuthNotifier(this._api, this._client) : super(const AuthState()); Future login(String phone, String password) async { state = state.copyWith(isLoading: true, error: null); try { final res = await _api.login(phone, password); if (res['success'] == true) { final token = res['data']['token'] as String; final user = User.fromJson(res['data']['user']); await _client.saveToken(token); state = AuthState(isLoggedIn: true, user: user, token: token); } else { state = state.copyWith(isLoading: false, error: res['error'] as String?); } } catch (e) { state = state.copyWith(isLoading: false, error: '网络错误: $e'); } } Future register(String phone, String password, String nickname) async { state = state.copyWith(isLoading: true, error: null); try { final res = await _api.register(phone, password, nickname); if (res['success'] == true) { final token = res['data']['token'] as String; final user = User.fromJson(res['data']['user']); await _client.saveToken(token); state = AuthState(isLoggedIn: true, user: user, token: token); } else { state = state.copyWith(isLoading: false, error: res['error'] as String?); } } catch (e) { state = state.copyWith(isLoading: false, error: '网络错误: $e'); } } Future logout() async { await _client.clearToken(); state = const AuthState(); } Future restoreSession() async { final token = await _client.getToken(); if (token == null) return; try { final res = await _api.getProfile(); if (res['success'] == true) { state = AuthState(isLoggedIn: true, user: User.fromJson(res['data']), token: token); } else { await _client.clearToken(); } } catch (_) { // offline - keep token for retry } } void clearError() { state = state.copyWith(error: null); } } final authProvider = StateNotifierProvider((ref) { final api = ref.read(authApiProvider); final client = ref.read(apiClientProvider); return AuthNotifier(api, client); });