import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:zhiying_base_widget/pages/team_page/model/team_data_model.dart';
import 'package:zhiying_base_widget/widgets/team/recommend/bloc/team_recommend_repository.dart';
import 'package:zhiying_comm/util/empty_util.dart';

part 'team_recommend_event.dart';

part 'team_recommend_state.dart';

class TeamRecommendBloc extends Bloc<TeamRecommendEvent, TeamRecommendState> {
  // TeamRecommendBloc() : super(TeamRecommendInitial());

  TeamRecommendRepository repository;

  TeamRecommendBloc(this.repository);

  @override
  TeamRecommendState get initialState => TeamRecommendInitial();

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

    /// 关联推荐人
    if (event is TeamRecommendRelateEvent) {
      yield* _mapRelateEventToState(event);
    }
  }

  /// 初始化数据
  Stream<TeamRecommendState> _mapInitEventToState(TeamRecommendInitEvent event) async* {
    var dataModel = await repository.fetchNetData();
    if (!EmptyUtil.isEmpty(dataModel) && !EmptyUtil.isEmpty(dataModel.referrer_username) && !EmptyUtil.isEmpty(dataModel.referrer_invite_code)) {
      yield TeamRecommendLoadedState(dataModel);
    } else {
      yield TeamRecommendErrorState();
    }
  }

  /// 关联推荐人
  Stream<TeamRecommendState> _mapRelateEventToState(TeamRecommendRelateEvent event) async* {
    TeamDataModel dataModel = await repository.fetchRelate(event.inviteCode);
    if (!EmptyUtil.isEmpty(dataModel) && !EmptyUtil.isEmpty(dataModel.referrer_username) && !EmptyUtil.isEmpty(dataModel.referrer_invite_code)) {
      yield TeamRecommendLoadedState(dataModel);
    } else {
      yield TeamRecommendErrorState();
    }
  }
}
