import 'package:dio/dio.dart';
import 'package:loopin/IM/push_service.dart';

import 'http_config.dart';

class Http {
  static Dio get _dio => HttpConfig.dio;

  static Future<dynamic> get(String url, {Map<String, dynamic>? params, Map<String, dynamic>? headers}) async {
    final res = await _dio.get(
      url,
      queryParameters: params,
      options: Options(extra: headers ?? {}),
    );
    return res.data;
  }

  static Future<dynamic> post(String url, {dynamic data, Map<String, dynamic>? headers}) async {
    try {
      final res = await _dio.post(
        url,
        data: data,
        options: Options(extra: headers ?? {}),
      );
      return res.data;
    } catch (e) {
      logger.e('$e--------$url');
    }
  }

  static Future<dynamic> put(String url, {dynamic data, Map<String, dynamic>? headers}) async {
    final res = await _dio.put(
      url,
      data: data,
      options: Options(extra: headers ?? {}),
    );
    return res.data;
  }

  static Future<dynamic> delete(String url, {dynamic data, Map<String, dynamic>? headers}) async {
    final res = await _dio.delete(
      url,
      data: data,
      options: Options(extra: headers ?? {}),
    );
    return res.data;
  }

  static Future<dynamic> upload(String url,
      {required String filePath,
      String fileKey = 'file',
      Map<String, dynamic>? data,
      Map<String, dynamic>? headers,
      Function(int sent, int total)? onSendProgress}) async {
    FormData formData = FormData.fromMap({
      fileKey: await MultipartFile.fromFile(filePath),
      if (data != null) ...data,
    });

    final res = await _dio.post(
      url,
      data: formData,
      onSendProgress: onSendProgress,
      options: Options(
        contentType: 'multipart/form-data',
        extra: headers ?? {},
      ),
    );

    return res.data;
  }
}
