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;


  final int _searchLimit = 10;
  int _searchPage = 1;
  bool _searchNoMore = false;

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

  // 搜全文
  List<SearchAllModel> searchALlResults = [];


  @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 setFatherDiscussModel(DiscussModel model){
    fatherDiscussModel = model;
  }

  void setShowSearch(bool show){
    if(show == false){
      searchInput.text = '';
    }
    showSearch = show;
    update();
  }

  // 点赞 取消点赞
  Future<void> commentLove({required DiscussModel discussModel}) async {
     num type = 0;
     if (discussModel.isPraise ==0){
       type = 1;
     }
     final result = await LibraryAPI.commentLove(bookId:bookDetailModel.bookId! , type: type, commentId: discussModel.id!);
     if(result){
       num goodNum = discussModel.goodNum??0;
       if(type ==0){
         goodNum --;
       }
       else{
         goodNum ++;
       }
       discussModel.isPraise = type;
       discussModel.goodNum = goodNum;
     }
     update();
  }

  // 删除回复
  Future<void> delComment({required DiscussModel discussModel}) async {
    final result = await LibraryAPI.delComment(bookId:bookDetailModel.bookId!, commentId: discussModel.id!);
    if(result){
      discuss.remove(discussModel);
      Toast.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('发表成功');
      Toast.show('发表成功');
      discussModel.replyNum = discussModel.replyNum! +1;
      DiscussModel tempModel = DiscussModel.fromJson(discussModel.toJson());
      tempModel.status = 1;
      tempModel.commentsCheck = 0;
      tempModel.isMy = 1;

      NoteContentModel contentModel = NoteContentModel(
          text: MediaModel(content:replyInput.text,privacyStatus: 1)
      );
      tempModel.content= contentModel;
      tempModel.content?.text?.privacyStatus = 1;
      tempModel.replacePersonName = discussModel.personName;

      Map<String,dynamic> map = jsonDecode(StorageService.to.getString(kLocalUserInfo));
      if (map.keys.contains('head_img')){
        tempModel.personPic = map['head_img'];
      }
      if (map.keys.contains('name')){
        tempModel.personName = map['name'];
      }
      tempModel.replyNum = 0;
      fatherDiscussModel.commentAll?.add(tempModel);
      // fatherDiscussModel.replyNum = fatherDiscussModel.commentAll?.length;
    }
    else{
      Toast.show('发表失败');
    }

    // 重置所有信息
    // reset();
    // setShowChat(false);
    replyInput.text = '';
    update();
    return result;
  }

  /// 搜全文
  Future<void> searchAll([bool isRefresh = false]) async {
    if (isRefresh) _searchPage = 1;
    // 网路请求
    final result = await LibraryAPI.searchAll(
        page: _searchPage,
        limit: _searchLimit,
        bookId: bookDetailModel.bookId.toString(),
        key: searchInput.text
    );
    // testData();
    Console.log('--------------------------------');
    // 如果是刷新 清理数据
    if (isRefresh) searchALlResults.clear();
    searchALlResults.addAll(result);
    _searchPage ++;
    _searchNoMore = result.length < _searchLimit;
    update();

  }

  void onRefreshSearch() async {
    try {
      await searchAll(true);
      refreshController.finishRefresh(IndicatorResult.success);
      refreshController.resetFooter();
    } catch (error) {
      Console.log('--error-----------------------------$error-');
      refreshController.finishRefresh(IndicatorResult.fail);
    }
  }

  void onLoadingSearch() async {
    if (_searchNoMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    try {
      await searchAll();
      refreshController.finishLoad();
    } catch (error) {
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }


  /// 获取讨论详情
  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);
    }
  }

  void testData(){

    // String? bookId,   num? chapterId,   String? chapterName,   String? key,   String? combinedContent,

    searchALlResults.addAll([
      SearchAllModel(bookId: '123',chapterId: 333,chapterName: '你好',key: '我是',combinedContent: '我是谁啊'),
      SearchAllModel(bookId: '13',chapterId: 22,chapterName: '哈哈哈',key: '你是',combinedContent: '你是谁啊')
    ]);
  }

}