part of user_coupon;

class UserCouponController extends GetxController {

  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );

  // 优惠券
  List <CouponModel> coupons = [];

  // late int type = 0;

  final int _limit = 10;
  int _page = 1;
  bool _noMore = false;

  @override
  void onReady() {
    onRefresh();
    super.onReady();
  }

  @override
  void onClose() {
    refreshController.dispose();
    super.onClose();
  }


  //
  // void getOverCoupons() {
  //   _noMore = true;
  //   _page = 1;
  //   type = 0;
  //   _getCoupon();
  // }

  /// 获取我的优惠券
  Future<void> _getCoupon([bool isRefresh = false]) async {
    if (isRefresh) _page = 1;
    // 网路请求
    final result = await MineAPI.coupon(
        page: _page,
        limit: _limit,
        type: 0,
    );
    // 如果是刷新 清理数据
    if (isRefresh) coupons.clear();
    // for(CouponModel model in result){
    //   model.type=type;
    //   coupons.add(model);
    // }
    coupons.addAll(result);
    _page ++;
    _noMore = result.length < _limit;
    update();

  }

  void onRefresh() async {
    try {
      await _getCoupon(true);
      refreshController.finishRefresh(IndicatorResult.success);
      refreshController.resetFooter();
    } catch (error) {
      refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  void onLoading() async {
    if (_noMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    try {
      await _getCoupon();
      refreshController.finishLoad();
    } catch (error) {
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }


}