import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:zhiying_base_widget/pages/feedback_page/bloc/feedback_record_repository.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'feedback_record_event.dart';
import 'feedback_record_state.dart';

class FeedbackRecordBloc extends Bloc<FeedbackRecordEvent, FeedbackRecordState> {
  // FeedbackRecordBloc() : super(FeedbackRecordInitial());
  @override
  FeedbackRecordState get initialState => FeedbackRecordInitial();

  FeedbackRecordRepository repository;

  FeedbackRecordBloc(this.repository);

  @override
  Stream<FeedbackRecordState> mapEventToState(
    FeedbackRecordEvent event,
  ) async* {
    /// 初始化
    if (event is FeedbackRecordInitEvent) {
      yield* _mapInitEventToState(event);
    }

    /// 刷新
    if (event is FeedbackRecordRefreshEvent) {
      yield* _mapRefreshEventToState(event);
    }

    /// 加载更多
    if (event is FeedbackRecordLoadEvent) {
      yield* _mapLoadEventToState(event);
    }
  }

  /// 初始化
  Stream<FeedbackRecordState> _mapInitEventToState(FeedbackRecordInitEvent event) async* {
    var styleCache = await repository.fetchCacheStyle();
    var styleNet = await repository.fetchInitStyle();
    var data = await repository.fetchInitData();
    if (!EmptyUtil.isEmpty(data) && (!EmptyUtil.isEmpty(styleCache) || !EmptyUtil.isEmpty(styleNet))) {
      yield FeedbackRecordLoadedState(dataModel: data, styleModel: !EmptyUtil.isEmpty(styleNet) ? styleNet : styleCache);
    } else {
      yield FeedbackRecordInitErrorState();
    }
  }

  /// 刷新
  Stream<FeedbackRecordState> _mapRefreshEventToState(FeedbackRecordRefreshEvent event) async* {
    var style = repository.styleModel;
    var result = await repository.fetchRefreshData();
    if (!EmptyUtil.isEmpty(result) && !EmptyUtil.isEmpty(style)) {
      yield FeedbackRecordRefreshSuccessState();
      yield FeedbackRecordLoadedState(dataModel: result, styleModel: style);
    } else {
      yield FeedbackRecordRefreshErrorState();
    }
  }

  /// 加载更多
  Stream<FeedbackRecordState> _mapLoadEventToState(FeedbackRecordLoadEvent event) async* {
    var style = repository.styleModel;
    var result = await repository.fetchLoadData();
    if (!EmptyUtil.isEmpty(result) && !EmptyUtil.isEmpty(style)) {
      yield FeedbackRecordLoadSuccessState();
      yield FeedbackRecordLoadedState(dataModel: result, styleModel: style);
    } else {
      yield FeedbackRecordLoadErrorState();
    }
  }
}
