import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:flutter/cupertino.dart';
import './bloc.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'login_invite_repository.dart';

class LoginInviteBloc extends Bloc<LoginInviteEvent, LoginInviteState> {
  LoginInviteRepository repostitory;

  LoginInviteBloc({@required this.repostitory});

  @override
  LoginInviteState get initialState => LoginInviteInitial();

  @override
  Stream<LoginInviteState> mapEventToState(
    LoginInviteEvent event,
  ) async* {
    /// 初始化
    if (event is LoginInviteInitEvent) {
      yield* _mapInitEventToState(event);
    }

    /// 查询邀请人
    if (event is LoginInviteQueryEvent) {
      yield* _mapQueryEventToState(event);
    }

    /// 提交
    if (event is LoginInviteSubmitEvent) {
      yield* _mapSubmitEventToState(event);
    }
  }

  /// 获取页面数据
  Stream<LoginInviteState> _mapInitEventToState(LoginInviteInitEvent event) async* {
    var data = await repostitory.fetchData();
    if (!EmptyUtil.isEmpty(data)) {
      yield LoginInviteLoadedState(model: data);
    }
  }

  /// 查询邀请人
  Stream<LoginInviteState> _mapQueryEventToState(LoginInviteQueryEvent event) async* {
    var data = await repostitory.fetchInviteUserInfo(event);
    if (!EmptyUtil.isEmpty(data))
      yield LoginInviteQuerySuccessState(model: data, pageMdel: repostitory?.pageModel);
    else
      yield LoginInviteQueryErrorState();
  }

  /// 提交
  Stream<LoginInviteState> _mapSubmitEventToState(LoginInviteSubmitEvent event) async* {
    var data = await repostitory.submitInvite(event);
    if (!EmptyUtil.isEmpty(data)) {
      yield LoginInviteSubmitSuccess(model: data);
    } else {
      yield LoginInviteSubmitErrorState();
      yield LoginInviteQuerySuccessState(model: repostitory?.lastInviteUser, pageMdel: repostitory?.pageModel);
    }
  }
}
