part of user_msg;

class MsgController extends GetxController {


  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );
  List<MsgModel> msgs = [];

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


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

  /// 消息未读变已读
  Future<bool> read(String id) async {
    bool result = await CommonAPI.read(id: id);
    return result;
  }

  /// 获取订单详细
  Future<OrderInfoModel> getOrderInfo(String orderNum) async {
    return await MineAPI.getOrderInfo(orderNum: orderNum);
  }

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

  }

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