import 'dart:async';

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

class HomeGoodsHeaderBloc extends BlocBase {
  List<HomeGoodsHeaderModel> _tabs = List();

  StreamController<List<HomeGoodsHeaderModel>> _tabController =
      StreamController<List<HomeGoodsHeaderModel>>();

  Stream<List<HomeGoodsHeaderModel>> get outData => _tabController.stream;

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

  void loadData(int id) {
    NetUtil.request('/api/v1/mod',
        method: NetMethod.POST,
        params: Map<String, dynamic>.from({
          'ids': [id]
        }), onCache: (data) {
      if (data != null) {
        _loadData(id, data);
      }
    }, onSuccess: (data) {
      _loadData(id, data);
    });
  }

  void _loadData(int id, dynamic data) {
    String key = id.toString();
    Map<String, dynamic> json = Map<String, dynamic>.from(data);
    if (json.containsKey(key)) {
      List<dynamic> list = json[key];
      _tabs = list.map((item) {
        return HomeGoodsHeaderModel.fromJson(Map<String, dynamic>.from(item));
      }).toList();
    }

    _tabController.add(_tabs);
  }
}
