import 'package:chat/services/auth_service.dart';
import 'package:chat/utils/ui_tools.dart';
import 'package:dio/dio.dart';

class HttpInterceptor extends Interceptor {
  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) {
    // 头部添加token
    options.headers['Authorization'] = AuthService.to.userToken;
    options.headers['Accept'] = 'application/json';

    super.onRequest(
      options,
      handler,
    );
  }

  @override
  void onResponse(
    Response response,
    ResponseInterceptorHandler handler,
  ) {
    final apiStatusCode = response.data['status_code'];

    if (apiStatusCode == 200) {
      response.data = response.data['data'];
    } else if (apiStatusCode == 401) {
      throw DioError(
        response: response,
        error: "登录超时",
        requestOptions: response.requestOptions,
      );
    } else if (apiStatusCode == 404) {
      throw DioError(
        response: response,
        error: "请求的接口不存在",
        requestOptions: response.requestOptions,
      );
    } else if (apiStatusCode == 0) {
      throw DioError(
        response: response,
        error: response.data['message'],
        requestOptions: response.requestOptions,
      );
    } else {
      throw DioError(
        response: response,
        error: response.data['message'],
        requestOptions: response.requestOptions,
      );
    }
    super.onResponse(
      response,
      handler,
    );
  }

  @override
  void onError(
    DioError err,
    ErrorInterceptorHandler handler,
  ) {
    switch (err.type) {
      // 连接服务器超时
      case DioErrorType.connectTimeout:
        UiTools.toast('网络传输超时');
        break;
      // 响应超时
      case DioErrorType.receiveTimeout:
        UiTools.toast('网络传输超时');
        break;
      // 发送超时
      case DioErrorType.sendTimeout:
        UiTools.toast('网络传输超时');
        break;
      // 请求取消
      case DioErrorType.cancel:
        break;
      // 404/503错误
      case DioErrorType.response:
        break;
      // other 其他错误类型
      case DioErrorType.other:
        if (err.response?.data['status_code'] == 401) {
          AuthService.to.logout();
        }
        break;
    }
    super.onError(
      err,
      handler,
    );
  }
}
