part of user_discuss_des;

class UserDiscussDesController extends GetxController {
  // 标签tag
  final String tag;
  // 课程模型
  final CourseModel model;
  UserDiscussDesController(this.tag, this.model);
  // 讨论数据
  List<DiscussModel> discuss = [];

  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
    controlFinishRefresh: true,
  );
  // 回复控制器
  late TextEditingController replyInput = TextEditingController();
  // 每页数量
  final int _limit = 10;
  // 当前页码
  int _page = 1;
  // 是否有更多
  bool _noMore = false;
  // 展示回复输入框
  bool showReply = false;
  // 当前要回复的模型
  late DiscussModel discussModel;
  // 当前要回复父级的模型
  late DiscussModel fatherDiscussModel;
  // 是否可点击
  bool canTap = true;

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

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

  /// 是否还在那时
  void setShow() {
    showReply = !showReply;
    update();
  }

  /// 设置讨论模型
  void setDiscussModel(DiscussModel model) {
    discussModel = model;
  }

  /// 设置父级模型
  void setFatherDiscussModel(DiscussModel model) {
    fatherDiscussModel = model;
  }

  /// 删除回复
  Future<void> delComment(
      {required List<DiscussModel>? list,
      required DiscussModel discussModel}) async {
    final result = await LibraryAPI.delComment(
        bookId: model.bookId!, commentId: discussModel.id!);
    if (result) {
      list?.remove(discussModel);
      Toast.show('删除成功');
    }
    update();
  }

  /// 提交
  Future<bool> submit() async {
    Map<String, dynamic> contentMap = {
      'text': replyInput.text,
      'audio': [],
      'image': []
    };

    final result = await LibraryAPI.addDiscuss(
        bookId: model.bookId.toString(),
        chapterId: discussModel.chapterId.toString(),
        commentId: discussModel.id.toString(),
        quoteContent: '',
        title: '',
        content: jsonEncode(contentMap));

    if (result.isNotEmpty) {
      Toast.show('发表成功');
      discussModel.replyNum = discussModel.replyNum! + 1;
      DiscussModel tempModel = DiscussModel.fromJson(discussModel.toJson());
      // tempModel.status = 1;
      tempModel.privacyStatus = 0;
      tempModel.commentsCheck = 0;
      tempModel.isMy = 1;
      tempModel.id = result['id'];

      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('发表失败');
    }
    replyInput.text = '';

    update();
    // 重置所有信息
    // reset();
    // setShowChat(false);
    return result.isNotEmpty ? true : false;
  }

  /// 点赞提交
  Future<void> commentLove({required DiscussModel discussModel}) async {
    num type = 0;
    if (discussModel.isPraise == 0) {
      type = 1;
    }
    final result = await LibraryAPI.commentLove(
        bookId: model.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> _getDiscuss([bool isRefresh = false]) async {
    if (isRefresh) _page = 1;
    // 网路请求
    final result = await MineAPI.discussList(
        page: _page,
        limit: _limit,
        bookId: model.bookId.toString(),
        types: tag);
    // 如果是刷新 清理数据
    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('------------onRefresh-----------------$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);
    }
  }
}
