import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
import 'package:zhiying_base_widget/pages/vip_center_page/bloc/vip_center_repository.dart';
import 'package:zhiying_base_widget/pages/vip_center_page/model/vip_center_data_model.dart';
import 'package:zhiying_base_widget/pages/vip_center_page/model/vip_center_style_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

part 'vip_center_event.dart';

part 'vip_center_state.dart';

class VipCenterBloc extends Bloc<VipCenterEvent, VipCenterState> {
  // VipCenterBloc() : super(VipCenterInitial());
  @override
  VipCenterState get initialState => VipCenterInitial();

  VipCenterRepository repository;

  VipCenterBloc(this.repository);

  @override
  Stream<VipCenterState> mapEventToState(
    VipCenterEvent event,
  ) async* {
    /// 初始化数据
    if (event is VipCenterInitEvent) {
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化数据
  Stream<VipCenterState> _mapInitEventToState(VipCenterInitEvent event) async* {
    var cacheStyle = await repository.fetchCachedStyle();
    if (!EmptyUtil.isEmpty(cacheStyle)) {
      yield VipCenterLoadedState(dataModel: null, styleMode: cacheStyle);
    }
    var netStyle = await repository.fetchNetStyle();
    if (!EmptyUtil.isEmpty(netStyle)) {
      yield VipCenterLoadedState(dataModel: null, styleMode: netStyle);
    }
    var result = await repository.fetchNetData();
    if (!EmptyUtil.isEmpty(result) && (!EmptyUtil.isEmpty(cacheStyle) || !EmptyUtil.isEmpty(netStyle))) {
      yield VipCenterLoadedState(dataModel: result, styleMode: !EmptyUtil.isEmpty(netStyle) ? netStyle : cacheStyle);
    }else{
      yield VipCenterErrorState();
    }
  }
}
