import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:flutter/cupertino.dart';

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

class CustomSlideBannerBloc extends Bloc<CustomSlideBannerEvent, CustomSlideBannerState> {
  CustomSlideBannerRepository repository;

  CustomSlideBannerBloc({@required this.repository});

  @override
  CustomSlideBannerState get initialState => InitialCustomSlideBannerState();

  @override
  Stream<CustomSlideBannerState> mapEventToState(CustomSlideBannerEvent event) async* {
    final currentState = state;

    /// 初始化
    if (event is CustomBannerInitEvent) {
      print('---------HomeBannerInitEvent---------');
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化
  Stream<CustomSlideBannerState> _mapInitEventToState(CustomBannerInitEvent event) async* {
    var parent = await repository.fetchPreantData(event.model);
    if (!EmptyUtil.isEmpty(parent)) {
      yield HomeSlideBannerLoadedState(datas: parent);
      return;
    }
    var cached = await repository.fetchCachedDate(id: event.model['mod_id']);
    if (!EmptyUtil.isEmpty(cached)) yield CustomSlideBannerCachedState(datas: cached);
    var param = await repository.fetchData(id: event.model['mod_id']);
    if (!EmptyUtil.isEmpty(param))
      yield HomeSlideBannerLoadedState(datas: param);
    else
      yield HomeSlideBannerLoadError();
  }
}
