import 'package:chat/models/im/search_user_model.dart';
import 'package:chat/models/upload_model.dart';
import 'package:chat/utils/network/http.dart';
import 'package:chat/utils/ui_tools.dart';

class UserProvider {
  /// 上传头像
  static Future<UploadModel?> uploadAvatar(String filePath) async {
    try {
      var res = await Http.upload('storage/upload', filePath: filePath);

      var model = UploadModel.fromJson(res);
      await Http.put('user/setting/avatar', data: {
        'value': model.url,
      });

      return model;
    } catch (e) {
      UiTools.toast(e.toString());
      return null;
    }
  }

  static Future<bool> updateNickname(String nickname) async {
    try {
      await Http.put('user/setting/nickname', data: {
        'value': nickname,
      });

      return true;
    } catch (e) {
      UiTools.toast(e.toString());
      return false;
    }
  }

  /// 从服务器查找用户
  static Future<List<SearchUserModel>?> searchUser(String keyword) async {
    try {
      var json = await Http.get(
        'user/search',
        params: {
          'keyword': keyword,
        },
      );

      return List<SearchUserModel>.from(
        json.map(
          (x) => SearchUserModel.fromJson(x),
        ),
      );
    } catch (err) {
      UiTools.toast(err.toString());
    }
    return null;
  }
}
