part of library_content;

class LibraryContentController extends GetxController {
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );

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


  // 图书列表数据
  List<CourseModel> books = [];


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


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



  /// 收藏 与 取消收藏
  void love({
    required String bookId,
    required num isCollection
  }) async {
    if (isCollection == 0){
      isCollection = 1;
    }
    else{
      isCollection = 0;
    }
    bool result = await CommonAPI.love(bookId: bookId, love: isCollection.toString());
    if (result) {
      onRefresh();
    }
  }

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

  }

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

}