import 'package:get/utils.dart';
import 'package:plugin_platform/platform_export.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:router/componentRouter/component_router_service.dart';
import 'package:widgets/dialog/app_default_dialog.dart';

import '../service/user_service.dart';

/*
 * 特殊状态code处理的拦截器，
 * 401 弹出弹窗提示用户重新登录
 */
class StatusCodeDioInterceptors extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response.statusCode == 200) {
      Map<String, dynamic> jsonMap = response.data;
      if (jsonMap.containsKey('code')) {
        int code = jsonMap['code'];
        if (code == 401) {
          _showExpiredDialog();
        }
      }
    } else if (response.statusCode == 401) {
      _showExpiredDialog();
    }

    super.onResponse(response, handler);
  }

  void _showExpiredDialog() {
    bool isDialogShowing = false; // 控制弹窗是否正在显示
    // 避免重复展示弹窗
    if (!isDialogShowing) {
      //弹框就清除了数据
      UserService.to.handleLogoutParams();

      //拦截 token 过期，弹出弹窗提示用户重新登录
      DialogEngine.show(
        keepSingle: true,
        onDismiss: () {
          isDialogShowing = false;
        },
        widget: AppDefaultDialog(
          title: "Notice".tr,
          message: "The login credential have expired, please log in again.".tr,
          confirmAction: () {
            ComponentRouterServices.authService.startPopAllLoginPage();
          },
        ),
      );
      //设置已经展示
      isDialogShowing = true;
    }
  }

  @override
  Future onError(DioException err, ErrorInterceptorHandler handler) async {
    super.onError(err, handler);
  }
}
