import 'dart:async';
import 'dart:convert';

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();

  dynamic _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(dynamic provider) {
    ///避免多次下拉刷新出现跳页加载的情况
    if (provider != _provider) {
      page = 1;
    }
    _provider = provider;

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

    NetUtil.request('/api/v1/rec?page=${page.toString()}',
        queryParameters: _provider,
        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) {
      if (_provider != provider) {
        return;
      }
      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;
    page=1;
    loadMore(providerType);
  }
}
