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/detail_img/bloc/goods_details_img_repository.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_base_widget/widgets/goods_details/detail_img/model/goods_details_img_model.dart';
import 'package:zhiying_comm/util/global_config.dart';

part 'goods_details_img_event.dart';

part 'goods_details_img_state.dart';

class GoodsDetailsImgBloc extends Bloc<GoodsDetailsImgEvent, GoodsDetailsImgState> {
  GoodsDetailsImgBloc({this.repository});

  GoodsDetailsImgRepository repository;

  @override
  GoodsDetailsImgState get initialState => GoodsDetailsImgInitial();

  @override
  Stream<GoodsDetailsImgState> mapEventToState(
    GoodsDetailsImgEvent event,
  ) async* {
    /// 初始化事件
    if (event is GoodsDetailsImgInitEvent) {
      yield* _mapInitEventToState(event);
    }
  }

  /// 初始化方法
  Stream<GoodsDetailsImgState> _mapInitEventToState(GoodsDetailsImgInitEvent event) async* {
    var parentData = await repository.fetchParentData(event.model);
    if (!EmptyUtil.isEmpty(parentData)) {
      yield GoodsDetailsImgLoadedState(model: parentData);
      /// 如果等于淘宝类型，就前端去抓去商品详情图片
      if (parentData.provider == GlobalConfig.PROVIDER_TB || parentData.provider == GlobalConfig.PROVIDER_TM) {
        /// 进行网络访问
        var netData = await repository.fetchNetData(event.model);
        if (!EmptyUtil.isEmpty(netData)) {
          // yield Good;
          yield GoodsDetailsImgLoadedState(model: netData);
        } else {
          yield GoodsDetailsImgErrorState();
        }
      }

    } else {
      yield GoodsDetailsImgErrorState();
    }
  }
}
