import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/pages/team_details_page/bloc/team_details_repository.dart';
import 'package:zhiying_base_widget/pages/team_details_page/model/team_details_data_model.dart';
import 'package:zhiying_base_widget/pages/team_details_page/model/team_details_style_model.dart';
import 'package:zhiying_comm/util/empty_util.dart';

part 'team_details_event.dart';

part 'team_details_state.dart';

class TeamDetailsBloc extends Bloc<TeamDetailsEvent, TeamDetailsState> {
  // TeamDetailsBloc() : super(TeamDetailsInitial());
  @override
  TeamDetailsState get initialState => TeamDetailsInitial();

  TeamDetailsRepository repository;

  TeamDetailsBloc({@required this.repository});

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

  /// 初始化数据
  Stream<TeamDetailsState> _mapInitEventToState(TeamDetailsInitEvent event) async* {
    var cacheStyle = await repository.fetchCacheData();
    if (!EmptyUtil.isEmpty(cacheStyle)) {
      yield TeamDetailsLoadedState(styleModel: cacheStyle);
    }
    var resultStyle = await repository.fetchNetStyleModelData();
    if (!EmptyUtil.isEmpty(resultStyle)) {
      yield TeamDetailsLoadedState(styleModel: resultStyle);
    }
    var resultData = await repository.fetchNetData(event?.model);
    if (!EmptyUtil.isEmpty(resultData) && (!EmptyUtil.isEmpty(resultStyle) || !EmptyUtil.isEmpty(cacheStyle))) {
      yield TeamDetailsLoadedState(dataModel: resultData, styleModel: !EmptyUtil.isEmpty(resultStyle) ? resultStyle : cacheStyle);
    } else {
      yield TeamDetailsErrorState();
    }
  }
}
