part of version;

class VersionController extends GetxController {
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );
  // 每页数量
  final int _limit = 10;
  // 当前页码
  int _page = 1;
  // 是否有更多
  bool _noMore = false;
  // 版本数据
  List<VersionModel> versions = [];

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

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

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

  List<VersionModel> test() {
    return [
      VersionModel(version: '1.11', updateTime: '2024-01-03 11:14:40'),
      VersionModel(version: '1.21', updateTime: '2023-01-03 11:14:40')
    ];
  }
}
