import 'package:chat/models/moment/moment_model.dart';
import 'package:chat/models/upload_model.dart';
import 'package:chat/utils/network/http.dart';
import 'package:chat/utils/ui_tools.dart';

class MomentProvider {
  /// 获取[发现]列表数据
  /// [createAt] 最后一列的create_at
  static Future<MomentModel?> fetchMomentList([String? createAt]) async {
    try {
      final result = await Http.get(
        'dynamics',
        params: {
          'created_at': createAt,
        },
      );
      return MomentModel.fromJson(result);
    } catch (e) {
      UiTools.toast(e.toString());
    }
    return null;
  }

  /// 点赞
  /// [dynamicId]
  static Future<bool?> likeMoment(int dynamicId) async {
    try {
      final result = await Http.post('dynamics/$dynamicId/like');
      return result['is_like'];
    } catch (e) {
      UiTools.toast(e.toString());
    }
    return null;
  }

  /// 删除
  /// [dynamicId]
  static Future<bool?> delMoment(int dynamicId) async {
    try {
      final result = await Http.delete('dynamics/$dynamicId');
      return result;
    } catch (e) {
      UiTools.toast(e.toString());
    }
    return null;
  }

  /// 回复或评论
  /// [dynamicId]
  /// [content] 评论内容
  /// [parentId] 回复的评论id
  static Future<Comment?> replyComment(
    int dynamicId,
    String content, [
    int? parentId,
  ]) async {
    try {
      final result = await Http.post(
        'dynamics/$dynamicId/comment',
        data: {
          'content': content,
          'parent_id': parentId,
        },
      );
      return Comment.fromJson(result);
    } catch (e) {
      UiTools.toast('评论失败');
    }
    return null;
  }

  /// 删除评论
  /// [dynamicId]
  /// [comment] 评论id
  static Future<bool?> delComment(
    int dynamicId, [
    int? commentId,
  ]) async {
    try {
      final result = await Http.delete(
        'dynamics/$dynamicId/comment/$commentId',
      );
      return result;
    } catch (e) {
      UiTools.toast('删除评论失败');
    }
    return null;
  }

  /// 上传文件
  static Future<UploadModel?> uploadFile(String filePath) async {
    try {
      final result = await Http.upload('storage/upload', filePath: filePath);
      return UploadModel.fromJson(result);
    } catch (e) {
      UiTools.toast('上传失败');
    }
    return null;
  }

  /// 发布“发现”内容
  ///
  /// [description] 文本内容
  /// [pictures] 媒体内容
  static Future<dynamic> publishMoment({
    required String description,
    required List<String> pictures,
  }) async {
    try {
      final result = await Http.post('dynamics', data: {
        'description': description,
        'pictures': pictures,
      });
      return result;
    } catch (e) {
      UiTools.toast(e.toString());
    }
    return null;
  }
}
