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 'package:fluttertoast/fluttertoast.dart';

class LoginBindPhoneBloc extends Bloc<LoginBindPhoneEvent, LoginBindPhoneState> {
  LoginBindPhoneRepository repository;

  LoginBindPhoneBloc({@required this.repository});

  @override
  LoginBindPhoneState get initialState => LoginBindPhoneInitial();

  @override
  Stream<LoginBindPhoneState> mapEventToState(LoginBindPhoneEvent event) async* {
    /// 获取数据
    if (event is LoginBindPhoneInitEvent) {
      yield* _mapInitEventToState();
    }

    /// 获取验证码
    if (event is LoginBindPhoneGetVCodeEvent) {
      yield* _mapGetVcodeEventToState(event);
    }

    /// 登陆(验证码)
    if (event is LoginBindPhoneTypeVCodeEvent) {
      yield* _mapLoginTypeVcodeEventToState(event);
    }
  }

  /// 获取数据
  Stream<LoginBindPhoneState> _mapInitEventToState() async* {
    var data = await repository.fetchData();
    if (!EmptyUtil.isEmpty(data))
      yield LoginBindPhoneLoadedState(model: data);
    else
      yield LoginBindPhoneErrorState();
  }

  /// 获取验证码
  Stream<LoginBindPhoneState> _mapGetVcodeEventToState(LoginBindPhoneGetVCodeEvent event) async* {
    bool result = await repository.fetchGetVcode(event);
    if (result) {
      Fluttertoast.showToast(msg: '验证码下发成功');
      yield LoginBindPhoneGetVCodeSuccessState();
    } else {
      yield LoginBindPhoneGetVCodeErrorState();
    }
  }

  /// 验证码登陆
  Stream<LoginBindPhoneState> _mapLoginTypeVcodeEventToState(LoginBindPhoneTypeVCodeEvent event) async* {
    var result = await repository.loginTypeVCode(event);
    if (!EmptyUtil.isEmpty(result))
      yield LoginBindPhoneLoginSuccessState(model: result);
    else
      yield LoginBindPhoneLoginErrorState();
  }
}
