
import 'dart:io';
import 'dart:math';

import 'package:anchor_collect_flutter/utils/sp_helper.dart';
import 'package:device_info/device_info.dart';
import 'package:dio/dio.dart' as dio;
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

import '../congifs.dart';

class TokenInterceptor extends Interceptor{

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {

    String uuidStr = SpHelper.getStorage(Config.SP_UUID)??getUUid();
    ///todo get token from cache
    // options.headers["Authorization"] = "Basic ZHhtaF93ZWI6ZHhtaF93ZWJfc2VjcmV0";
    // options.headers["token"] = "YToyOntzOjY6InVzZXJpZCI7czo5OiI3eVVnamVnc2UiO3M6OToidGltZXN0YW1wIjtpOjE2OTk0MDc0MTQ7fQ\$\$#M2YxODdhZWNiZDdjMGE2NWRiNzI3NjJhNmNkNWEyZDA\$ ";
    options.headers["token"] = SpHelper.getStorage(Config.SP_STR_TOKEN);
    options.headers["deptid"] = SpHelper.getStorage(Config.SP_DEPT_ID);
    options.headers["imei"] = uuidStr;
    // options.headers["imei"] = '8743174844301820';
    // options.headers["type"] = 'app';
    // options.headers["response-status"] = 401;
    print('token:${options.headers["token"]},imei:${options.headers["imei"]}');
    super.onRequest(options, handler);
  }

  @override
  void onResponse(dio.Response response, ResponseInterceptorHandler handler) {
    super.onResponse(response, handler);
  }

  static Future<String?> getDeviceId() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      if (kDebugMode) {
        print('设备 ID: ${androidInfo.androidId}');
      }
      return androidInfo.androidId;
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      if (kDebugMode) {
        print('设备 ID: ${iosInfo.identifierForVendor}');
      } // 在 iOS 中，我们使用 identifierForVendor 作为设备 ID
      return iosInfo.identifierForVendor;
    }
  }

  //获取随机4位+时间戳
  String getUUid() {
    String randomStr = Random().nextInt(10).toString();
    for (var i = 0; i < 1; i++) {
      var str = Random().nextInt(10);
      randomStr = "$randomStr$str";
    }
    var timeNumber = DateTime.now().millisecondsSinceEpoch;//时间
    var uuid = "$randomStr$timeNumber";
    if (kDebugMode) {
      print(uuid);
    }
    SpHelper.putStorage(Config.SP_UUID, uuid);
    return uuid;
  }
}