import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/common/app_config.dart';
import 'package:kaer_with_panels/app/mixins/kr_app_bar_opacity_mixin.dart';
import 'package:kaer_with_panels/app/model/entity_from_json_util.dart';
import 'package:kaer_with_panels/app/services/kr_site_config_service.dart';

import '../utils/kr_aes_util.dart';
import '../utils/kr_log_util.dart';

/// 接口返回基础类
class BaseResponse<T> {
  late int retCode; //状态码
  late String retMsg; //返回的信息
  late Map<String, dynamic> body; // 返回的数据
  late T model;
  List<T> list = []; // 初始化为空列表
  bool isSuccess = true; // 是否返回正确数据

  BaseResponse.fromJson(Map<String, dynamic> json) {
    retCode = json['code'];
    final dataMap = json['data'] ?? Map<String, dynamic>();
    final cipherText = dataMap['data'] ?? "";
    final nonce = dataMap['time'] ?? "";
    // 判断是否需要解密：根据站点配置的 enable_security 字段
    if (cipherText.isNotEmpty && nonce.isNotEmpty) {
      try {
        if (kDebugMode) {
          // print('═══════════════════════════════════════');
          // print('🔐 检测到加密响应，开始解密...');
          // print('📥 加密数据长度: ${cipherText.length} 字符');
          // print('⏰ 时间戳: $nonce');
        }

        final decrypted = KRAesUtil.decryptData(cipherText, nonce, AppConfig.kr_encryptionKey);
        body = jsonDecode(decrypted);

        if (kDebugMode) {
          // print('✅ 解密成功');
          // print('');
          // print('📦 解密后的完整数据:');
          // // 格式化打印 JSON，方便调试
          // final bodyStr = JsonEncoder.withIndent('  ').convert(body);
          // print(bodyStr);
          // print('═══════════════════════════════════════');
        }

        KRLogUtil.kr_i('🔓 解密成功', tag: 'BaseResponse');
      } catch (e) {
        if (kDebugMode) {
          print('❌ 解密失败: $e');
          print('⚠️ 将使用原始数据');
          print('═══════════════════════════════════════');
        }
        KRLogUtil.kr_e('❌ 解密失败: $e', tag: 'BaseResponse');
        body = dataMap;
      }
    }
    else
    {
      body = dataMap;
    }
    if (retCode == 40004 || retCode == 40005 || retCode == 40002 || retCode == 40003) {
      KRAppRunData().kr_loginOut();
      return;
    }

    if (retCode != 200) {
      isSuccess = false;
    }
    retMsg = json['msg'];

    // 获取错误信息
    final msg = "error.${retCode.toString()}".tr;

    if (msg.isNotEmpty && msg != "error.${retCode.toString()}") {
      retMsg = msg;
    }

   

    if (body.isNotEmpty) {
      if (body is List) {
        list = (json['data'] as List<dynamic>)
            .map((e) => EntityFromJsonUtil.parseJsonToEntity<T>(e))
            .toList();
      } else {
        if (T == dynamic) {
          model = body as T;
        } else {
          model = EntityFromJsonUtil.parseJsonToEntity<T>(body);
        }
      }
    } else {
      // 当body为空时，设置默认model值
    }
  }

  // 获取泛型T的默认值
  T _getDefaultValue<T>() {
    if (T == String) return '' as T;
    if (T == int) return 0 as T;
    if (T == double) return 0.0 as T;
    if (T == bool) return false as T;
    if (T == Map) return {} as T;
    if (T == List) return [] as T;
    return null as T;
  }
}
