import 'dart:async';

import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhiying_base_widget/pages/orders_page/models/order_filter_model.dart';
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 OrderContentBloc extends BlocBase {
  List<OrderModel> _orders = List();

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

  Stream<List<OrderModel>> get outData => _ordersController.stream;
  String _state;
  OrderFilterModel _filter;
  RefreshController refreshController =
  RefreshController(initialRefresh: false);
  @override
  void dispose() {
    _ordersController.close();
    _ordersController = null;
  }

  void refresh(String state, OrderFilterModel filter) {
    _state = state;
    _filter = filter;

    _filter.pageNo = '1';
    _loadData(state, filter);
  }

  void _loadData(String state, OrderFilterModel filter) {
    Map<String, dynamic> params = _filter.toJson();
    params.removeWhere((key, value) => value == null || value == '');
    params['state'] = _state;
    NetUtil.request('/api/v1/order', method: NetMethod.POST, params: params,
        onCache: (data) {
      //_parseData(data);
    }, onSuccess: (data) {
      _parseData(data);
    });
  }

  void loadMore() {
    _loadData(_state, _filter);
  }

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

    if (_filter.pageNo == null ||
        _filter.pageNo == '' ||
        _filter.pageNo == '1') {
      _orders.clear();
    }

    if (list.length > 0) {
      if (_filter.pageNo == null || _filter.pageNo == '') {
        _filter.pageNo = '2';
      } else {
        _filter.pageNo = ((int.tryParse(_filter.pageNo) ?? 1) + 1).toString();
      }
      refreshController.refreshCompleted();
      refreshController.resetNoData();
    }else{
      refreshController.loadNoData();
    }

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

    _ordersController?.add(_orders);
  }
}
