import 'dart:async';

import 'package:zhiying_base_widget/pages/goods_share_page/models/goods_share_temp_add_model.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class GoodsShareData {
  List<Map<String, dynamic>> tabs;
  List<GoodsShareTempDataModel> datas;
}

class GoodsShareBloc extends BlocBase {
  GoodsShareData _data = GoodsShareData();

  StreamController<GoodsShareData> _tabController =
      StreamController<GoodsShareData>();

  Stream<GoodsShareData> get outData => _tabController.stream;

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

  void loadData(String shopType, Map<String, dynamic> params) async {
    var json = await NetUtil.post('/api/v1/share/${shopType}', params: params);
    Map<String, dynamic> data = json['data'];
    List shareTemp = data['data_list'];
    _data.datas = shareTemp.map((item) {
      return GoodsShareTempDataModel.fromJson(Map<String, dynamic>.from(item));
    }).toList();

    NetUtil.request(
      '/api/v1/mod/pub.flutter.share?share_type=${shopType.toString()}',
      method: NetMethod.GET,
      onCache: (data) {
        _loadData(data);
      },
      onSuccess: (data) {
        _loadData(data);
      },
    );
  }

  void _loadData(dynamic data) {
    try {
      List list = Map<String, dynamic>.from(data)['mod_list'];
      _data.tabs = list.map((item) {
        return Map<String, dynamic>.from(item);
      }).toList();
      _tabController.add(_data);
    } catch (err) {
      Logger.error(err);
    }
  }
}
