import 'dart:convert';

import 'package:archive/archive.dart';
import 'package:dio/dio.dart';

import '../../../utils/crypto.dart';
import '../../../utils/developer/ix_developer_tools.dart';
import '../../../utils/log/logger.dart';
import '../../constants/keys.dart';
import '../../data/models/api_exception.dart';
import '../../data/models/api_result.dart';
import '../../data/models/disconnect_domain.dart';
import '../../data/sp/ix_sp.dart';
import '../base/base_api.dart';

import '../core/api_core_paths.dart';

/// 核心API
class ApiLog extends BaseApi {
  static final _instance = ApiLog._internal();

  factory ApiLog() => _instance;

  ApiLog._internal() {
    _initDio();
  }

  /// 初始化Dio
  void _initDio() {
    // 此处可以设置默认的DIO参数
    final options = BaseOptions();
    options.connectTimeout = const Duration(seconds: 90);
    options.receiveTimeout = const Duration(seconds: 90);
    options.responseType = ResponseType.bytes;
    options.headers['content-type'] = 'application/json';

    dio = Dio(options);

    dio.interceptors.add(SimpleApiMonitorInterceptor());

    // 添加拦截器
    _setupInterceptors();
  }

  // bool _isRefreshing = false;

  void _setupInterceptors() {
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          // 在请求发送前添加token
          final user = IXSP.getUser();
          if (user != null) {
            options.headers['Authorization'] = user.accessToken;
          }
          return handler.next(options);
        },
        onError: (DioException error, handler) async {
          IXSP.addDisconnectDomain(
            DisconnectDomain(
              domain: error.requestOptions.baseUrl,
              status: error.response?.statusCode ?? -1,
              msg: error.message ?? '',
              startTime: DateTime.now().millisecondsSinceEpoch,
              endTime: DateTime.now().millisecondsSinceEpoch,
              count: 1,
            ),
          );
          return handler.next(error);
        },
      ),
    );
  }

  @override
  Map<String, dynamic>? getDefaultHeader() {
    // 可以设置自定义Header
    final headers = {
      'X-NL-Product-Code': 'nomo',
      'X-NL-Content-Encoding': 'gzip',
    };
    return headers;
  }

  @override
  Map<String, dynamic>? getDefaultQuery() {
    // 可以设置自定义Query
    return null;
  }

  @override
  dynamic encrypt(dynamic input) {
    try {
      final data = jsonEncode(input);
      final bytes = utf8.encode(data);
      final gzipEncoder = GZipEncoder();
      final compressedBytes = gzipEncoder.encode(bytes);
      log('ApiLog', '>>: $data');
      return Crypto.encryptBytesUint8(compressedBytes, Keys.aesKey, Keys.aesIv);
    } catch (error) {
      throw ApiException("-2", "encrypt error: $error");
    }
  }

  @override
  dynamic decrypt(dynamic input) {
    try {
      final decryptedBytes = Crypto.decryptBytes(
        base64Encode(input),
        Keys.aesKey,
        Keys.aesIv,
      );
      // 使用GZip解压
      final gzipDecoder = GZipDecoder();
      final decodeBytes = gzipDecoder.decodeBytes(decryptedBytes);
      final data = utf8.decode(decodeBytes);
      log('ApiLog', '<<:$data');
      return jsonDecode(data);
    } catch (error) {
      throw ApiException("-2", "decrypt error: $error");
    }
  }

  /// 上传日志
  Future<ApiResult> uploadLogs(dynamic data) async {
    return post(ApiCorePaths.uploadLog, data: data, domainType: DomainType.log);
  }
}
