hi-client/lib/app/network/base_response.dart
2025-10-17 15:28:40 +08:00

92 lines
2.8 KiB
Dart
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'dart:convert';
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 字段
final shouldDecrypt = KRSiteConfigService().isDeviceSecurityEnabled();
if (shouldDecrypt && cipherText.isNotEmpty && nonce.isNotEmpty) {
try {
KRLogUtil.kr_i('🔓 开始解密响应数据', tag: 'BaseResponse');
final decrypted = KRAesUtil.decryptData(cipherText, nonce, AppConfig.kr_encryptionKey);
body = jsonDecode(decrypted);
KRLogUtil.kr_i('✅ 解密成功', tag: 'BaseResponse');
} catch (e) {
KRLogUtil.kr_e('❌ 解密失败: $e,使用原始数据', tag: 'BaseResponse');
body = dataMap;
}
}
else
{
body = dataMap;
}
if (retCode == 40004 || retCode == 40005 || retCode == 40002 || retCode == 40003) {
KRAppRunData().kr_loginOut();
}
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;
}
}