import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:zhiying_base_widget/pages/wechat_teacher_page/bloc/wechat_teacher_repository.dart';
import 'wechat_teacher_event.dart';
import 'wechat_teacher_state.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class WechatTeacherBloc extends Bloc<WechatTeacherEvent, WechatTeacherState> {
  @override
  WechatTeacherState get initialState => WechatTeacherInitial();

  WechatTeacherRepository repository;

  WechatTeacherBloc(this.repository);

  @override
  Stream<WechatTeacherState> mapEventToState(
    WechatTeacherEvent event,
  ) async* {
    /// 初始化
    if (event is WechatTeacherInitEvent) {
      yield* _mapInitEventToState(event);
    }

    /// 绑定微信导师
    if (event is WechatTeacherBindEvent) {
      yield* _mapBindEventToState(event);
    }
  }

  /// 初始化
  Stream<WechatTeacherState> _mapInitEventToState(WechatTeacherInitEvent event) async* {
    var cacheStyle = await repository.fetchCachedStyle();
    if (!EmptyUtil.isEmpty(cacheStyle)) {
      yield WechatTeacherLoadedState(dataModel: null, styleModel: cacheStyle);
    }
    var netStyle = await repository.fetchInitStyle();
    if (!EmptyUtil.isEmpty(netStyle)) {
      yield WechatTeacherLoadedState(dataModel: null, styleModel: netStyle);
    }
    var data = await repository.fetchInitData();
    if (!EmptyUtil.isEmpty(data) && (!EmptyUtil.isEmpty(cacheStyle) || !EmptyUtil.isEmpty(netStyle))) {
      yield WechatTeacherLoadedState(styleModel: !EmptyUtil.isEmpty(netStyle) ? netStyle : cacheStyle, dataModel: data);
    } else {
      yield WechatTeacherInitErrorState();
    }
  }

  /// 绑定微信导师
  Stream<WechatTeacherState> _mapBindEventToState(WechatTeacherBindEvent event) async* {
    var style = repository.styleModel;
    var result = await repository.bindTeacher(event?.teacherWxChat);
    if (!EmptyUtil.isEmpty(result)) {
      yield WechatTeacherBindSuccessState();
      yield WechatTeacherLoadedState(styleModel: style, dataModel: result);
    } else {
      yield WechatTeacherBindErrorState();
      yield WechatTeacherLoadedState(styleModel: style, dataModel: null);
    }
  }
}
