import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:zhiying_base_widget/pages/custom_page/bloc/custom_item_page_repository.dart';
import 'custom_item_page_state.dart';
import 'custom_item_page_event.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class CustomItemPageBloc extends Bloc<CustomItemPageEvent, CustomItemPageState> {
  // CustomItemPageBloc() : super(CustomItemPageInitial());

  CustomItemPageRepository repository;

  CustomItemPageBloc(this.repository);

  @override
  CustomItemPageState get initialState => CustomItemPageInitial();

  @override
  Stream<CustomItemPageState> mapEventToState(
    CustomItemPageEvent event,
  ) async* {
    /// 初始化
    if (event is CustomItemPageInitEvent) {
      yield* _mapInitEventToState(event);
    }

    /// 下拉刷新
    if (event is CustomItemPageRefreshEvent) {
      yield* _mapRefreshEventToState(event);
    }

    /// 上拉更多
    if (event is CustomItemPageLoadEvent) {
      yield* _mapLoadEventToState(event);
    }
  }

  /// 初始化
  Stream<CustomItemPageState> _mapInitEventToState(CustomItemPageInitEvent event) async* {
    var cacheStyle = await repository.fetchCacheStyle();
    if (!EmptyUtil.isEmpty(cacheStyle)) {
      yield CustomItemPageLoadedState(model: cacheStyle);
    }
    var netStyle = await repository.fetchNetStyle();
    if (!EmptyUtil.isEmpty(netStyle) && netStyle is List) {
      yield CustomItemPageLoadedState(model: netStyle);
    } else {
      yield CustomItemPageInitErrorState();
    }
  }

  /// 下拉刷新
  Stream<CustomItemPageState> _mapRefreshEventToState(CustomItemPageRefreshEvent event) async* {
    var netStyle = await repository.fetchNetStyle();
    if (!EmptyUtil.isEmpty(netStyle)) {
      yield CustomItemPageRefreshSuccessState();
      yield CustomItemPageLoadedState(model: netStyle);
    } else {
      yield CustomItemPageRefreshErrorState();
      yield CustomItemPageErrorState();
    }
  }

  /// 上拉更多
  Stream<CustomItemPageState> _mapLoadEventToState(CustomItemPageLoadEvent event) async* {}
}
