import 'dart:convert';

import 'package:flutter_clx_base/flutter_clx_base.dart';

class LoggingInterceptor extends Interceptor {
  late DateTime _startTime;
  late DateTime _endTime;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    _startTime = DateTime.now();
    loggerNoStack.i('Start:$_startTime[${options.method}]: ${options.uri}');
    super.onRequest(options, handler);
  }

  @override
  void onResponse(
      Response<dynamic> response, ResponseInterceptorHandler handler) {
    _endTime = DateTime.now();
    final int duration = _endTime.difference(_startTime).inMilliseconds;
    // 输出结果
    Map httpLogMap = {};
    httpLogMap.putIfAbsent(
        "end", () => '----------End: $duration 毫秒----------');
    httpLogMap.putIfAbsent("method", () => response.requestOptions.method);
    httpLogMap.putIfAbsent(
        "requestUrl", () => '${response.requestOptions.uri}');
    httpLogMap.putIfAbsent(
        "requestHeaders", () => response.requestOptions.headers);
    httpLogMap.putIfAbsent(
        "queryParameters", () => response.requestOptions.queryParameters);
    httpLogMap.putIfAbsent("requestBody", () => response.requestOptions.data);
    if (response.statusCode == 200) {
      httpLogMap.putIfAbsent("responseData", () => json.decode(response.data));
    } else {
      httpLogMap.putIfAbsent("responseData", () => response.data);
    }
    loggerNoStack.i(httpLogMap);

    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    loggerNoStack.e('----------Error-----------');
    super.onError(err, handler);
  }
}
