import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../providers/app_store.dart';
import '../dto/base_dto.dart';

///请求拦截器
void onRequest(
  RequestOptions options,
  RequestInterceptorHandler handler,
) async {
  String token = await AppStore.getToken();
  options.headers['Authorization'] = 'Bearer $token';
  return handler.next(options);
}

///响应拦截器
void onResponse(
  Response<dynamic> response,
  ResponseInterceptorHandler handler,
) {
  var apiResponse = ApiDto.fromJson(response.data);
  if (apiResponse.code == 1) {
    response.data = apiResponse.data;
    return handler.next(response);
  } else {
    showError(apiResponse.message);
    handler.reject(
      DioException(
        requestOptions: response.requestOptions,
        response: response,
        error: {'code': 0, 'message': apiResponse.message},
      ),
    );
  }
}

///错误响应
void onError(
  DioException e,
  ErrorInterceptorHandler handler,
) {
  var title = "";
  if (e.type == DioExceptionType.connectionTimeout) {
    title = "请求超时";
  } else if (e.type == DioExceptionType.badResponse) {
    if (e.response?.statusCode == 404) {
      title = "接口404不存在";
    } else {
      title = "500";
    }
  } else if (e.type == DioExceptionType.connectionError) {
    title = "网络连接失败";
  } else {
    title = "异常其他错误";
  }
  showError(title);
  handler.next(e);
}

///显示错误信息
void showError(String message) {
  EasyLoading.showError(message);
}
