import 'dart:async';

import 'package:bloc/bloc.dart';
import 'custom_page_event.dart';
import 'custom_page_repository.dart';
import 'custom_page_state.dart';
import 'package:zhiying_comm/util/empty_util.dart';

class CustomPageBloc extends Bloc<CustomPageEvent, CustomPageState> {
  // CommonBloc() : super(CommonInitial());

  CustomPageRepository repository;

  CustomPageBloc(this.repository);

  @override
  CustomPageState get initialState => CustomPageInitialState();

  @override
  Stream<CustomPageState> mapEventToState(
    CustomPageEvent event,
  ) async* {
    /// 初始化
    if (event is CustomPageInitEvent) {
      yield* _mapInitToState(event);
    }

    /// 刷新
    if (event is CustomPageRefreshEvent) {
      yield* _mapRefreshToState(event);
    }
  }

  /// 刷新
  Stream<CustomPageState> _mapRefreshToState(CustomPageRefreshEvent event) async* {
    var result = await repository.fetchInitData();
    if (!EmptyUtil.isEmpty(result)) {
      yield CustomPageRefreshSuccessState();
      yield CustomPageLoadedState(model: result);
    } else {
      yield CustomPageRefreshErrorState();
      yield CustomPageErrorState();
    }
  }

  /// 初始化
  Stream<CustomPageState> _mapInitToState(CustomPageInitEvent event) async* {
    // 获取缓存数据
    var cache = await repository.fetchCacheData();
    if (!EmptyUtil.isEmpty(cache) && cache is List) {
      yield CustomPageLoadedState(model: cache);
    }
    // 获取网络数据
    var result = await repository.fetchInitData();
    if (!EmptyUtil.isEmpty(result) && result is List) {
      yield CustomPageLoadedState(model: result);
    } else {
      yield CustomPageInitErrorState();
    }
  }
}
