
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/platform_export.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:router/componentRouter/component_service_manager.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:router/componentRouter/community_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) {
      //弹框就清除了数据
      //使用 UserConfigService 对象中的方法处理
      UserConfigService.getInstance().handleLogoutParams();

      //拦截 token 过期，弹出弹窗提示用户重新登录
      DialogEngine.show(
        keepSingle: true,
        onDismiss: () {
          isDialogShowing = false;
        },
        widget: AppDefaultDialog(
          title: "Notice",
          message: "The login credential have expired, please log in again.",
          confirmAction: () {
            //移除全部的页面并且跳转到登录页面
            ComponentServiceManager().authService.startAndPopAllLoginPage();
          },
        ),
      );
      //设置已经展示
      isDialogShowing = true;
    }
  }

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