part of user_notes_des;

class UserNotesDesController extends GetxController {
  // 分类 tag
  final String tag;
  // 书籍模型
  final CourseModel model;

  UserNotesDesController(this.tag, this.model);

  List<NoteModel> notes = [];

  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );
  // 音频播放器
  just_audio.AudioPlayer audioPlayer = just_audio.AudioPlayer();
  // 每页数量
  final int _limit = 10;
  // 当前页码
  int _page = 1;
  // 是否有更多
  bool _noMore = false;

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

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

  /// 播放音频
  void playAudio(MediaModel mediaModel) {
    if (audioPlayer.playerState.playing) {
      audioPlayer.stop();
      mediaModel.currentDuration = '0:00:00';
      // if(currentPlayMediaModel.id == mediaModel.id){
      //   return;
      // }
    }
    // 本地音频
    if (mediaModel.id == 0) {
      audioPlayer.setFilePath(mediaModel.path);
    }
    // 远程音频
    else {
      audioPlayer.setUrl(mediaModel.content ?? '');
    }
    audioPlayer.play();
    StreamSubscription? positionSubscription;
    positionSubscription = audioPlayer.positionStream.listen((position) {
      String temp = Tools.formatDuration(position);
      Console.log(
          '播放时间---------------------$temp------id-------------${mediaModel.id}');
      mediaModel.currentDuration = temp;
      if (position >= audioPlayer.duration!) {
        Console.log('---------播放结束-----------');
        positionSubscription?.cancel();
      }
      update();
    });
    // currentPlayMediaModel = mediaModel;
  }

  /// 删除笔记
  void delNotes({required NoteModel noteModel, required String bookId}) async {
    final result = await MineAPI.delNotes(
        notesId: noteModel.notesId.toString(), bookId: bookId);
    if (result) {
      Toast.show('删除笔记成功');
      notes.remove(noteModel);
    }
    update();
  }

  /// 获取笔记列表
  Future<void> _getNotes([bool isRefresh = false]) async {
    if (isRefresh) _page = 1;
    // 网路请求
    final result = await MineAPI.noteList(
        page: _page,
        limit: _limit,
        bookId: model.bookId.toString(),
        types: tag);
    for (NoteModel noteModel in result) {
      if (noteModel.noteContent != null &&
          noteModel.noteContent!.audio != null) {
        if (noteModel.noteContent!.audio!.isNotEmpty) {
          await Future.forEach(noteModel.noteContent!.audio!,
              (MediaModel? mediaModel) async {
            if (mediaModel != null && mediaModel.content != null) {
              Duration? duration =
                  await audioPlayer.setUrl(mediaModel.content!);
              if (duration != null) {
                mediaModel.duration = Tools.formatDuration(duration);
              }
            }
          });
        }
      }
    }
    // 如果是刷新 清理数据
    if (isRefresh) notes.clear();
    notes.addAll(result);
    _page++;
    _noMore = result.length < _limit;
    update();
  }

  /// 刷新数据
  void onRefresh() async {
    try {
      await _getNotes(true);
      refreshController.finishRefresh(IndicatorResult.success);
      refreshController.resetFooter();
    } catch (error) {
      Console.log(
          '----error--------------------------------------$error--------------');
      refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  /// 加载数据
  void onLoading() async {
    if (_noMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    try {
      await _getNotes();
      refreshController.finishLoad();
    } catch (error) {
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }
}
