import 'dart:async';

import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class MainPageBloc extends BlocBase {
  List<Map<String, dynamic>> _pageData = List();

  StreamController<List<Map<String, dynamic>>> _mainController =
      StreamController<List<Map<String, dynamic>>>();

  Stream<List<Map<String, dynamic>>> get outData => _mainController.stream;

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

  void loadData(int id) {
    NetUtil.request('/api/v1/mod',
        method: NetMethod.POST,
        params: Map<String, dynamic>.from({
          'ids': [id]
        }), onCache: (data) {
      _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];
      _pageData = list.map((item) {
        return Map<String, dynamic>.from(item);
      }).toList();
    }

    _mainController.add(_pageData);
  }
}
