part of web;

class DiscussController extends GetxController {
  final BookDetailModel bookDetailModel;
  // 当前的章节id
  final String chapterId;
  DiscussController({required this.bookDetailModel,required this.chapterId});
  List<DiscussModel> discuss = [];
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );

  late TextEditingController searchInput = TextEditingController();
  late TextEditingController replyInput = TextEditingController();

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

  // 展示回复输入框
  bool showReply = false;
  // 当前要回复的模型
  late DiscussModel discussModel;
  // 是否展示搜索结果
  bool showSearch = false;


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

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

  void setShow() {
    showReply = !showReply;
    update();
  }

  void setDiscussModel(DiscussModel model){
      discussModel = model;
  }

  void setShowSearch(bool show){
    showSearch = show;
    update();
  }

  Future<bool> submit() async {

    Map<String,dynamic> contentMap = {
      'text':replyInput.text,
      'audio':[],
      'image':[]
    };

    final result = await LibraryAPI.addDiscuss(
        bookId: bookDetailModel.bookId.toString(),
        chapterId: chapterId,
        commentId: discussModel.id.toString(),
        quoteContent: '',
        title: '',
        content: jsonEncode(contentMap)
    );
    if(result){
      Toast.show('话题发表成功');
    }
    else{
      Toast.show('话题发表失败');
    }

    // 重置所有信息
    // reset();
    // setShowChat(false);
    return result;
  }

  /// 获取讨论详情
  Future<void> _getDiscuss([bool isRefresh = false]) async {
    if (isRefresh) _page = 1;
    // 网路请求
    final result = await LibraryAPI.discussList(
        page: _page,
        limit: _limit,
        bookId: bookDetailModel.bookId.toString(),
        chapterId: chapterId
    );
    Console.log('--------------------------------');
    // 如果是刷新 清理数据
    if (isRefresh) discuss.clear();
    discuss.addAll(result);
    _page ++;
    _noMore = result.length < _limit;
    update();

  }

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

}