import 'package:dio/dio.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'shop_models.dart'; import 'shop_repository.dart'; enum ShopStatus { initial, loading, loaded, error } class ShopState extends Equatable { final ShopStatus status; final ShopData? data; final bool busy; // در حال انجام یک عملیات (خرید/انتخاب) const ShopState({this.status = ShopStatus.initial, this.data, this.busy = false}); ShopState copyWith({ShopStatus? status, ShopData? data, bool? busy}) => ShopState( status: status ?? this.status, data: data ?? this.data, busy: busy ?? this.busy, ); @override List get props => [status, data, busy]; } class ShopCubit extends Cubit { final ShopRepository _repo; ShopCubit(this._repo) : super(const ShopState()); Future load() async { emit(state.copyWith(status: ShopStatus.loading)); try { emit(state.copyWith(status: ShopStatus.loaded, data: await _repo.getShop())); } catch (_) { emit(state.copyWith(status: ShopStatus.error)); } } /// یک عملیات را اجرا، فروشگاه را بازخوانی و پیام نتیجه را برمی‌گرداند. Future _run(Future Function() action, String okMsg) async { if (state.busy) return ''; emit(state.copyWith(busy: true)); try { await action(); final data = await _repo.getShop(); emit(state.copyWith(status: ShopStatus.loaded, data: data, busy: false)); return okMsg; } on DioException catch (e) { emit(state.copyWith(busy: false)); final d = e.response?.data; if (d is Map && d['message'] != null) return d['message'].toString(); return 'خطا در ارتباط با سرور'; } catch (_) { emit(state.copyWith(busy: false)); return 'خطای نامشخص'; } } Future buyCard(String id) => _run(() => _repo.buyCard(id), 'کارت خریداری شد'); Future selectCard(String id) => _run(() => _repo.selectCard(id), 'کارت انتخاب شد'); Future purchase(String kind, String id) => _run( () => _repo.purchase( store: 'bazaar', kind: kind, productId: id, token: 'dev-$kind-$id-${DateTime.now().millisecondsSinceEpoch}', ), 'خرید با موفقیت انجام شد', ); Future claimAd() => _run( () => _repo.adReward('dev-ad-${DateTime.now().millisecondsSinceEpoch}'), 'سکه رایگان دریافت شد', ); }