part of course;

class CourseController extends GetxController {
  // 课程数组
  List<CourseModel> courses = [];
  //  消息数组
  List<AdModel> ads = [];
  // 消息未读数
  int num = 0;
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );

  // 每页数量
  final int _limit = 10;
  // 当前页码
  int _page = 1;
  // 是否有更多
  bool _noMore = false;

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

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

  /// 获取广告数据
  void _getAds() async {
    ads = await CommonAPI.list(type: '2');
    update();
  }

  /// 消息未读数
  void getNums() async {
    num = await CommonAPI.num();
    update();
  }

  /// 获取图书详细信息
  Future<BookDetailModel> getBookDetails(String bookId) async {
    final result = await LibraryAPI.details(bookId: bookId);
    return result;
  }

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

  /// 刷新数据
  void onRefresh() async {
    try {
      await _getCourse(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 _getCourse();
      refreshController.finishLoad();
    } catch (error) {
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }

// void logout(BuildContext context) async {
//   final result = await AccountAPI.logout();
//   if (result){
//     CustomToast.success('退出成功');
//     await UserStore.to.logout();
//     if(context.mounted){
//       context.goNamed(Routes.main);
//     }
//   }
// }
}
