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

import 'package:zhiying_base_widget/pages/invited_friends/models/invite_friend_data_model.dart';
import 'package:zhiying_base_widget/pages/invited_friends/models/invited_friends_model.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class InvitedFriendshBloc extends BlocBase {
  InvitedFriendsModel _model;

  StreamController<InvitedFriendsModel> _dataController =
      StreamController<InvitedFriendsModel>();

  Stream<InvitedFriendsModel> get outData => _dataController.stream;

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

  void loadData(String skipIdentifier) async {
    Map<String, dynamic> data =
        await NetUtil.post('/api/v1/user/invitefriend', method: NetMethod.GET);
    InvitedFriendsDataModel dataModel = InvitedFriendsDataModel.fromJson(
        Map<String, dynamic>.from(data['data']));
    NetUtil.request('/api/v1/mod/${skipIdentifier.toString()}',
        method: NetMethod.GET, onCache: (data) {}, onSuccess: (data) {
      _model = _loadData(data);
      _model?.dataModel = dataModel;
      _dataController.add(_model);
    });
  }

  InvitedFriendsModel _loadData(dynamic data) {
    try {
      Map<String, dynamic> json = Map<String, dynamic>.from(data);
      if (json == null || json.length == 0) {
        return null;
      }
      List mods = json['mod_list'];
      if (mods.first != null) {
        json = Map<String, dynamic>.from(mods.first);
        String d = json['data'];
        Map<String, dynamic> da =
            Map<String, dynamic>.from(convert.jsonDecode(d));
        return InvitedFriendsModel.fromJson(da);
      }
    } catch (err) {
      Logger.error(err);
    }
    return null;
  }
}
