import 'dart:async';

import 'package:zhiying_base_widget/pages/orders_page/models/order_model.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class OrderSearchBloc extends BlocBase {
  List<OrderModel> _orders = List();

  StreamController<List<OrderModel>> _ordersController =
      StreamController<List<OrderModel>>();

  Stream<List<OrderModel>> get outData => _ordersController.stream;
  int _page = 1;
  String _keyword = '';

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

  void refresh(String keyword) {
    _keyword = keyword;
    _page = 1;
    _loadData(_keyword);
  }

  void _loadData(String keyword) {
    Map<String, dynamic> params = Map();
    params['keyword'] = keyword;
    params['page_no'] = _page.toString();
    NetUtil.request('/api/v1/order', method: NetMethod.POST, params: params,
        onCache: (data) {
      _parseData(data);
    }, onSuccess: (data) {
      _parseData(data);
    });
  }

  void loadMore() {
    _loadData(_keyword);
  }

  void _parseData(dynamic data) {
    List list = data ?? [];

    if (_page <= 1) {
      _orders.clear();
    }

    if (list.length > 0) {
      _page++;
    }

    _orders.addAll(list.map((item) {
      return OrderModel.fromJson(Map<String, dynamic>.from(item));
    }).toList());

    _ordersController.add(_orders);
  }
}
