part of user_love;

class UserLoveController extends GetxController {

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

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

  // 收藏数据
  List<CourseModel> loves = [];

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

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

  /// 取消收藏
  void unLoved({
    required String bookId
  }) async {
    bool result = await CommonAPI.love(bookId: bookId, love: '0');
    if (result) {
      onRefresh();
    }
  }

  /// 获取课程内图书列表
  Future<void> _getLoves([bool isRefresh = false]) async {
    if (isRefresh) _page = 1;
    // 网路请求
    final result = await MineAPI.love(
        page: _page,
        limit: _limit
    );
    // 如果是刷新 清理数据
    if (isRefresh) loves.clear();
    loves.addAll(result);
    _page ++;
    _noMore = result.length < _limit;
    update();

  }

  void onRefresh() async {
    try {
      await _getLoves(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 _getLoves();
      refreshController.finishLoad();
    } catch (error) {
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }

}