import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_i18n/modules/index.dart';
import 'package:fis_jsonrpc/exception.dart';
import 'package:fis_jsonrpc/interceptor.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';

class JsonRpcExInterceptor extends JsonRpcInterceptor {
  @override
  Future<JsonRpcServerError> onResponseError(JsonRpcServerError error) async {
    var errorCode = error.code;
    try {
      EasyLoading.dismiss(animation: false);
      if (error.code != null && error.code != 1 && error.code != 2) {
        String? text;
        if (errorCode != null && errorCode < -1) {
          // 小于-1 是Server内部的报错，无需展示错误码
          text = i18nBook.errorCodes.errorCodeUN.t;
        } else if (error.code == -1) {
          text =
              i18nBook.getTrItem(ErrorCodesModule.ModuleName, 'errorCodeUN')?.t;
        } else {
          text = i18nBook
              .getTrItem(ErrorCodesModule.ModuleName, 'errorCode${error.code}')
              ?.t;
        }
        PromptBox.toast(text ?? "Unkonwn RPC Exception");
        logger.w("Fetch RPC error, code: ${error.code}, msg: ${error.message}");
      }
    } catch (e) {
      if (errorCode != null && errorCode < -1) {
        // 小于-1 是Server内部的报错，无需展示错误码
        PromptBox.toast(i18nBook.errorCodes.errorCodeUN.t);
      } else {
        PromptBox.toast("${i18nBook.errorCodes.errorCodeUN.t}[$errorCode]");
      }
    }
    return error;
  }
}
