part of book_score;

class BookScoreController extends GetxController {
  final String bookId ;
  BookScoreController(this.bookId);

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

  // 评价列表
  List <ScoreModel> scores = [];



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


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


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

  }

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