import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import './bloc.dart';
import 'login_account_repository.dart';
import 'package:fluttertoast/fluttertoast.dart';

class LoginAccountBloc extends Bloc<LoginAccountEvent, LoginAccountState> {
  LoginAccountRepository repository;

  LoginAccountBloc({@required this.repository});

  @override
  LoginAccountState get initialState => LoginAccountInitial();

  @override
  Stream<LoginAccountState> mapEventToState(LoginAccountEvent event) async* {
    /// 获取数据
    if (event is LoginAccountInitEvent) {
      yield* _mapInitEventToState();
    }

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

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

    /// 密码登陆
    if(event is LoginAccountTypePasswordEvent){
      yield* _mapLoginTypePassEventToState(event);
    }
  }

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

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

  /// 验证码登陆
  Stream<LoginAccountState> _mapLoginTypeVcodeEventToState(LoginAccountTypeVcodeEvent event) async* {
    var result = await repository.loginTypeVcode(event);
    if (!EmptyUtil.isEmpty(result))
      yield LoginAccountLoginSuccessState(model: result);
    else
      yield LoginAccountLoginErrorState();
  }

  /// 密码登陆
  Stream<LoginAccountState> _mapLoginTypePassEventToState(LoginAccountTypePasswordEvent event) async* {
    var result = await repository.loginTypePass(event);
    if(!EmptyUtil.isEmpty(result))
      yield LoginAccountLoginSuccessState(model: result);
    else
      yield LoginAccountLoginErrorState();

  }
}
