import 'package:app/global/event_bus.dart';
import 'package:app/providers/user_store.dart';
import 'package:app/router/route_paths.dart';
import 'package:app/router/routes.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

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

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

///响应拦截器
void onResponse(Response<dynamic> response,
    ResponseInterceptorHandler handler,) async {
  var apiResponse = ApiDto.fromJson(response.data);
  if (apiResponse.code == 1) {
    response.data = apiResponse.data;
    handler.next(response);
  } else if (apiResponse.code == 401) {
    // final bus = EventBus();
    // bus.fire(GlobalEvent.unauthorized);
    // final context = navigatorKey.currentState?.context;
    // print("dsd");
    // if (context != null) {
    //   // UserStore userStore = context.read<UserStore>();
    //   // userStore.logout();
    //   context.go(RoutePaths.login);
    // }
    handler.next(response);
  } else {
    handler.reject(
      DioException(
        requestOptions: response.requestOptions,
        response: response,
        error: {'code': apiResponse.code, 'message': apiResponse.message},
      ),
    );
    showError(apiResponse.message);
  }
}

///错误响应
void onError(DioException e,
    ErrorInterceptorHandler handler,) async {
  var title = "";
  if (e.type == DioExceptionType.connectionTimeout) {
    title = "请求超时";
  } else if (e.type == DioExceptionType.badResponse) {
    if (e.response?.statusCode == 401) {
      final bus = EventBus();
      bus.fire(GlobalEvent.unauthorized);
      title = "登录信息已失效，请重新登录";
    }
    else 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);
}
