import 'package:dio/dio.dart';
import 'package:plugin_basic/provider/app_config/app_config_service.dart';
import 'package:shared/utils/device_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import '../provider/user_config/user_config_service.dart';

/*
 * 用户授权加密等相关处理的拦截器
 */
class AuthDioInterceptors extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    //拿到现有的Headers
    Map<String, dynamic> headers = options.headers;

    if (Utils.isEmpty(headers['accept'])) {
      headers['accept'] = 'application/json';
    }

    if (Utils.isEmpty(headers['Content-Type'])) {
      headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }

    // 设置需要添加平台信息，App版本信息等
    if (DeviceUtils.isIOS) {  
      final systemVersion = AppConfigService.getState().iosDeviceInfo?.systemVersion;
      final appVersion = AppConfigService.getState().version;
      const platform = 'ios';

      final agent = 'platform:$platform systemVersion:$systemVersion appVersion:$appVersion}';
      headers['User-Agent'] = agent;
    } else if (DeviceUtils.isAndroid) {
      final device = '${AppConfigService.getState().androidDeviceInfo?.brand}-${AppConfigService.getState().androidDeviceInfo?.device}';
      final systemVersion = AppConfigService.getState().androidDeviceInfo?.version.release;
      final appVersion = AppConfigService.getState().version;
      const platform = 'android';

      final agent = 'platform:$platform device:$device systemVersion:$systemVersion appVersion:$appVersion';
      headers['User-Agent'] = agent;
    } else {
      headers['User-Agent'] = 'Mozilla/5.0';
    }

    //每个接口添加自定义的设备UUID标识
    // final uuid = SPUtil.getString(AppConstant.storageDeviceUUID);
    // if (Utils.isNotEmpty(uuid)) {
    //   headers['device-uuid'] = uuid!;
    // }

    //如果有通行令牌，都带上通行令牌
    String? token = UserConfigService.getState().token;
    Log.d("请求拦截加上Token:$token");
    if (!Utils.isEmpty(token)) {
      headers['Authorization'] = 'Bearer $token';
    }
    // 参数加密

    // 通讯加密

    //设置给Option对象
    options.headers = headers;

    super.onRequest(options, handler);
  }
}
