import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:zhiying_base_widget/widgets/goods_details/footer/bloc/goods_details_footer_repository.dart';
import 'package:zhiying_base_widget/widgets/goods_details/footer/model/goods_details_footer_model.dart';
import 'package:zhiying_comm/util/empty_util.dart';

part 'goods_details_footer_event.dart';

part 'goods_details_footer_state.dart';

class GoodsDetailsFooterBloc extends Bloc<GoodsDetailsFooterEvent, GoodsDetailsFooterState> {
  GoodsDetailsFooterBloc({this.repository});

  GoodsDetailsFooterRepository repository;

  @override
  GoodsDetailsFooterState get initialState => GoodsDetailsFooterInitial();

  @override
  Stream<GoodsDetailsFooterState> mapEventToState(
    GoodsDetailsFooterEvent event,
  ) async* {
    /// 初始化
    if (event is GoodsDetailsFooterInitEvent) {
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化
  Stream<GoodsDetailsFooterState> _mapInitEventToState(GoodsDetailsFooterInitEvent event) async* {
    var result = await repository.fetchParentData(event.model);
    if (!EmptyUtil.isEmpty(result)) {
      print('result  = ${result.toString()}');
      yield GoodsDetailsFooterLoadedState(model: result);
    } else {
      yield GoodsDetailsFooterErrorState();
    }
  }

  /// 点击收藏
  Stream<GoodsDetailsFooterState> _mapCollectEventToState(GoodsDetailsFooterCollectEvent event) async* {
    var result = await repository.fetchCollect();
    if (!EmptyUtil.isEmpty(result))
      yield GoodsDetailsFooterLoadedState(model: result);
    else
      yield GoodsDetailsFooterErrorState();
  }
}
