import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:zhiying_base_widget/pages/about_us_page/bloc/about_us_repository.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'about_us_state.dart';
import 'about_us_event.dart';

class AboutUsBloc extends Bloc<AboutUsEvent, AboutUsState> {
  // AboutUsBloc() : super(AboutUsInitial());

  AboutUsRepository repository;

  AboutUsBloc(this.repository);

  @override
  AboutUsState get initialState => AboutUsInitial();

  @override
  Stream<AboutUsState> mapEventToState(
    AboutUsEvent event,
  ) async* {
    if (event is AboutUsInitEvent) {
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化数据
  Stream<AboutUsState> _mapInitEventToState(AboutUsInitEvent event) async* {
    /// 1、父页面数据
    var parentData = await repository.fetchParentData(event?.data);
    if (!EmptyUtil.isEmpty(parentData)) {
      yield AboutUsLoadedState(model: parentData);
      return;
    }

    var cacheData = await repository.fetchCacheData(event?.data);
    if (!EmptyUtil.isEmpty(cacheData)) {
      yield AboutUsLoadedState(model: cacheData);
    }
    var netData = await repository.fetchNetData(event?.data);
    if (!EmptyUtil.isEmpty(netData)) {
      yield AboutUsLoadedState(model: netData);
    } else {
      yield AboutUsErrorState();
    }
  }
}
