import 'dart:async';

import 'package:zhiying_base_widget/pages/goods_share_page/models/goods_share_poster_model.dart';
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;
  GoodsSharePosterModel poster;
}

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 {
    await loadPoster(params);
    await loadMod(shopType);
    await loadInfo(shopType, params);
    _tabController.add(_data);
  }

  Future loadPoster(Map<String, dynamic> params) async {
    _data.poster = await _loadPoster(params);
  }

  Future loadMod(String shopType) async {
    var data = await NetUtil.post(
        '/api/v1/tmp/mod/pub.flutter.share?type=${shopType.toString()}',
        method: NetMethod.GET);
    _loadMod(data['data']);
  }

  void _loadMod(dynamic data) {
    try {
      List list = Map<String, dynamic>.from(data)['mod_list'];
      for (dynamic model in list) {
        Map d = Map<String, dynamic>.from(model);
        if (d.containsKey('tab_view')) {
          List tabs = d['tab_view'];
          _data.tabs = tabs.map((item) {
            return Map<String, dynamic>.from(item);
          }).toList();
        }
      }
    } catch (err) {
      Logger.error(err);
    }
  }

  Future loadInfo(String shopType, Map<String, dynamic> params) async {
    _data.datas = List();
    for (Map<String, dynamic> item in _data.tabs) {
      String url = item['url'];
      Logger.debug(url);
      var json = await NetUtil.post('/api/v1/share?type=${url.toString()}',
          params: params);
      Map<String, dynamic> data = json['data'];
      _data.datas.add(
          GoodsShareTempDataModel.fromJson(Map<String, dynamic>.from(data)));
    }
  }

  // 请求分享海报
  Future<GoodsSharePosterModel> _loadPoster(Map<String, dynamic> params) async {
    var json = await NetUtil.post('/api/v1/share?type=poster', params: params);
    Map<String, dynamic> data = Map<String, dynamic>.from(json['data']);

    return GoodsSharePosterModel.fromJson(data);
  }
}
