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();
    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<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);
  //     }
  //   }
  // }

}