import 'dart:async';
import 'dart:math';

import 'package:bloc/bloc.dart';
import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/bloc/home_quick_entry_repository.dart';
import 'package:zhiying_comm/util/empty_util.dart';

import './bloc.dart';

class HomeQuickEntryBloc extends Bloc<HomeQuickEntryEvent, HomeQuickEntryState> {
  HomeQuickEntryRepository repository;

  HomeQuickEntryBloc({@required this.repository});

  @override
  HomeQuickEntryState get initialState => InitialHomeQuickEntryState();

  @override
  Stream<HomeQuickEntryState> mapEventToState(HomeQuickEntryEvent event) async* {
    final currentState = state;
    if (event is HomeQuickEntryInitEvent) {
      yield* _mapHomeQuickEntryInitToState(event);
    }
  }

  /// 初始化
  Stream<HomeQuickEntryState> _mapHomeQuickEntryInitToState(HomeQuickEntryInitEvent event) async* {

    /// 获取父页面传进来的数据
    var parentData = await repository.fetchPreantData(event: event);
    if(!EmptyUtil.isEmpty(parentData)){
      yield HomeQuickEntryLoadedState(model: parentData);
      return;
    }
    /// 获取本地缓存数据
    var cached = await repository.fetchCachedData(event: event);
    if (!EmptyUtil.isEmpty(cached)) {
      yield HomeQuickEntryCachedState(model: cached);
    }
    /// 获取网络的数据
    var result = await repository.fetchData(event: event);
    if (!EmptyUtil.isEmpty(result)) {
      yield HomeQuickEntryLoadedState(model: result);
    } else {
      yield HomeQuickEntryErrorState();
    }
  }
}
