import 'dart:async';

import 'package:zhiying_base_widget/widgets/home/home_goods/models/home_goods_model.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class HomeGoodsBloc extends BlocBase {
  List<HomeGoodsModel> _goods = List();

  String _provider = '';

  int _page = 1;

  StreamController<List<HomeGoodsModel>> _goodsController =
      StreamController<List<HomeGoodsModel>>();

  Stream<List<HomeGoodsModel>> get outData => _goodsController.stream;

  @override
  void dispose() {
    _goodsController.close();
    _goodsController = null;
  }

  void loadMore(String provider) {
    if (provider != _provider) {
      _page = 1;
    }
    _provider = provider;

    if (_page == 1) {
      _goods.clear();
    }

    NetUtil.request(
        '/api/v1/rec/${provider.toString()}?page=${_page.toString()}',
        method: NetMethod.GET,
        onCache: (data) {}, onSuccess: (data) {
      Map<String, dynamic> json = Map<String, dynamic>.from(data);
      if (json.containsKey('good')) {
        List<dynamic> list = json['good'];
        List<HomeGoodsModel> goods = list.map((item) {
          return HomeGoodsModel.fromJson(Map<String, dynamic>.from(item));
        }).toList();
        if (goods.length > 0) {
          _page++;
        }
        _goods.addAll(goods);
      }

      _goodsController.add(_goods);
    });
  }
}
