import 'package:anchor_collect_flutter/utils/dialog_utils.dart';
import 'package:dio/dio.dart';

import 'api_response.dart';

class ApiException implements Exception {
  static const unknownException = "未知错误";
  final String? message;
  final int? code;
  String? stackInfo;

  ApiException([this.code, this.message]);

  factory ApiException.fromDioError(DioException error) {
    switch (error.type) {
      case DioExceptionType.cancel:
        return BadRequestException(-1, "请求取消");
      case DioExceptionType.connectionTimeout:
        return BadRequestException(-1, "连接超时");
      case DioExceptionType.sendTimeout:
        return BadRequestException(-1, "请求超时");
      case DioExceptionType.receiveTimeout:
        return BadRequestException(-1, "响应超时");
      case DioExceptionType.connectionError:
        return BadRequestException(-1, "网络不可用");
      case DioExceptionType.unknown:
        try {
          /// http错误码带业务错误信息
          ApiResponse apiResponse = ApiResponse.fromJson(error.response?.data);
          return ApiException(apiResponse.code, apiResponse.msg);

        } on Exception {
          return ApiException(-1, unknownException);
        }
      default:
        return ApiException(-1, error.message);
    }
  }



  factory ApiException.from(dynamic exception) {
    if (exception is DioExceptionType) {
      return ApiException.fromDioError(exception as DioException);
    }
    if(exception is DioException){
      return ApiException.fromDioError(exception);
    }
    if (exception is ApiException) {
      return exception;
    } else {
      var apiException = ApiException(-1, unknownException);
      apiException.stackInfo = exception?.toString();
      return apiException;
    }
  }
}

/// 请求错误
class BadRequestException extends ApiException {
  BadRequestException([super.code, super.message]);
}

/// 未认证异常
class UnauthorisedException extends ApiException {
  UnauthorisedException([int super.code = -1, String super.message = '']);
}
