import 'dart:async';

import 'package:zhiying_base_widget/widgets/custom/goods/category_goods/category_goods_callback.dart';
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 implements CategoryGoodsOnClickCallBack{
  List<HomeGoodsModel> _goods = List();

  String _provider = '';
  String providerss = '';
  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: _page == 1
            ? (data) {
                if (!EmptyUtil.isEmpty(data)) {

                  if (data.containsKey('good')) {
                    try {
                      List<dynamic> list = data['good'];
                      List<HomeGoodsModel> goods = list.map((item) {
                        return HomeGoodsModel.fromJson(Map<String, dynamic>.from(item));
                      }).toList();
                      Logger.warn('goods list cache data = ${data?.toString()}');
                      _goodsController.add(goods);
                    } catch (e, s) {
                      Logger.warn(e,s);
                    }
                  }
                }
              }
            : null, 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);
    });
  }

  @override
  void onTap(int index, String providerType) {
      Logger.error('index = $index, providerType = $providerType');
      _provider = providerType;
      loadMore(providerType);
  }

}
