import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:zhiying_base_widget/pages/upload_wechat_page/bloc/upload_wechat_repository.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'upload_wechat_event.dart';
import 'upload_wechat_state.dart';

class UploadWeChatBloc extends Bloc<UploadWeChatEvent, UploadWeChatState> {
  @override
  UploadWeChatState get initialState => UploadWeChatInitial();

  UploadWeChatRepository repository;

  UploadWeChatBloc(this.repository);

  @override
  Stream<UploadWeChatState> mapEventToState(
    UploadWeChatEvent event,
  ) async* {
    /// 初始化
    if (event is UploadWeChatInitEvent) {
      yield* _mapInitEventToState(event);
    }

    /// 更新微信信息
    if (event is UploadWeChatSubmitEvent) {
      yield* _mapUpdateEventToState(event);
    }
  }

  /// 初始化
  Stream<UploadWeChatState> _mapInitEventToState(UploadWeChatInitEvent event) async* {
    var result = await repository.fetchInitData();
    if (!EmptyUtil.isEmpty(result)) {
      yield UploadWeChatLoadedState(model: result);
    } else {
      yield UploadWeChatInitErrorState();
    }
  }

  /// 更新微信信息
  Stream<UploadWeChatState> _mapUpdateEventToState(UploadWeChatSubmitEvent event) async* {
    var result = await repository.fetchUpdateWeChatInfo(event?.file, event?.wxAccount);
    if (!EmptyUtil.isEmpty(result)) {
      yield UploadWeChatSubmitSuccessState();
      yield UploadWeChatLoadedState(model: result);
    } else {
      yield UploadWeChatSubmitErrorState();
    }
  }
}
