import 'dart:convert';

import 'package:EasyDartModule/EasyDartModule.dart';
import 'package:ef/ef.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:vbvs_app/common/color/ServiceConstant.dart';
import 'package:vbvs_app/common/color/app_uri_status.dart';
import 'package:vbvs_app/common/util/DailyLogUtils.dart';
import 'package:vbvs_app/common/util/MyUtils.dart';
import 'package:vbvs_app/model/api_response.dart';

part 'message_controller.g.dart'; // 由json_serializable自动生成的部分

@JsonSerializable()
class MhMessageModel {
  int? type = 1; //设备类型 1:体征消息 2.系统消息
  int? body_message_read = 0; //体征消息 0：已读 1：未读
  int? system_message_read = 0; //系统消息  0：已读 1：未读

  MhMessageModel();

  // 从JSON反序列化时的异常处理

  factory MhMessageModel.fromJson(Map<String, dynamic> json) {
    try {
      return _$MhMessageModelFromJson(json);
    } catch (e) {
      // 在实际应用中，应该有更细致的异常处理策略和错误日志
      return MhMessageModel(); // 或者返回一个带有错误信息的特定DeviceInfoModel实例
    }
  }

  // 序列化为JSON时的异常处理
  Map<String, dynamic> toJson() => _$MhMessageModelToJson(this);
}

class MhMessageController extends GetControllerEx<MhMessageModel> {
  MhMessageController() {
    attr = GetModel(MhMessageModel()).obs;
  }

  RxList messageList = [].obs;

  Future<ApiResponse> getMessageList({String? key}) async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.message_list;
      String messageType = "app_system";
      if (model.type == 1) {
        messageType = "app_vsm";
      } else {
        messageType = "app_system";
      }
      String queryUrl =
          "${serviceAddress}${serviceName}${serviceApi}?type=${messageType}";
      String? language = "";
      if (languageController.selectLanguage != null) {
        language = languageController.selectLanguage.value!.language_code;
      }
      if (language != null && language.isNotEmpty) {
        if (queryUrl.contains("?")) {
          queryUrl += "&lang=$language";
        } else {
          queryUrl += "?lang=$language";
        }
      }
      var response = await EasyDartModule.dio.get(queryUrl);
      if (response != null) {
        var responseData =
            response.data is String ? jsonDecode(response.data) : response.data;
        ApiResponse res =
            ApiResponse.fromJson(responseData, (object) => object);
        MyUtils.formatResponse(res, "请求成功".tr, "请求失败".tr);
        if (res.code == HttpStatusCodes.ok) {
          updateAll();
          messageList.value = res.data;
          return res;
        }
      } else {
        return ApiResponse(code: -1, msg: "服务器.失败".tr);
      }
      return apiResponse;
    } catch (e) {
      EasyDartModule.logger.info("设备请求列表: $e");
      DailyLogUtils.writeLog("设备请求列表: $e");
    }
    return ApiResponse(code: -1, msg: "未知错误".tr); // Default return statement
  }

  //获取消息已读未读
  Future<ApiResponse> getMessageStatus() async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
      // return apiResponse;
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.message_read;

      String queryUrl = "${serviceAddress}${serviceName}${serviceApi}";
      String? language = "";
      if (languageController.selectLanguage != null) {
        language = languageController.selectLanguage.value!.language_code;
      }
      if (language != null && language.isNotEmpty) {
        if (queryUrl.contains("?")) {
          queryUrl += "&lang=$language";
        } else {
          queryUrl += "?lang=$language";
        }
      }
      var response = await EasyDartModule.dio.get(queryUrl);
      if (response != null) {
        var responseData =
            response.data is String ? jsonDecode(response.data) : response.data;
        ApiResponse res =
            ApiResponse.fromJson(responseData, (object) => object);
        MyUtils.formatResponse(res, "请求成功".tr, "请求失败".tr);
        if (res.code == HttpStatusCodes.ok) {
          updateAll();
          List dataList = res.data;

          // 查找 type 为 app_vsm 的项
          var vsmItem = dataList.firstWhere(
            (e) => e['type'] == 'app_vsm',
            orElse: () => null,
          );
          model.body_message_read = vsmItem?['count'] ?? 0;

          // 查找 type 为 app_system 的项
          var systemItem = dataList.firstWhere(
            (e) => e['type'] == 'app_system',
            orElse: () => null,
          );
          model.system_message_read = systemItem?['count'] ?? 0;

          updateAll();
          return res;
        }
      } else {
        return ApiResponse(code: -1, msg: "服务器.失败".tr);
      }
      return apiResponse;
    } catch (e) {
      EasyDartModule.logger.info("获取消息已读未读: $e");
      DailyLogUtils.writeLog("获取消息已读未读: $e");
    }
    return ApiResponse(code: -1, msg: "未知错误".tr); // Default return statement
  }

  //更新消息已读
  Future<ApiResponse> updateMessageStatus({String? type}) async {
    EasyDartModule.logger.info("更新消息已读状态");
    DailyLogUtils.writeLog("更新消息已读状态");
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "操作失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.message_read;

      // 拼接 URL，添加 type 参数
      String queryUrl = "$serviceAddress$serviceName$serviceApi";
      if (type != null && type.isNotEmpty) {
        queryUrl += "?type=$type";
      }

      String? language = "";
      if (languageController.selectLanguage != null) {
        language = languageController.selectLanguage.value!.language_code;
      }
      if (language != null && language.isNotEmpty) {
        if (queryUrl.contains("?")) {
          queryUrl += "&lang=$language";
        } else {
          queryUrl += "?lang=$language";
        }
      }
      var response = await EasyDartModule.dio.post(queryUrl);

      if (response != null) {
        var responseData =
            response.data is String ? jsonDecode(response.data) : response.data;
        ApiResponse res =
            ApiResponse.fromJson(responseData, (object) => object);
        MyUtils.formatResponse(res, "操作成功".tr, "操作成功".tr);
        return res;
      } else {
        return ApiResponse(code: -1, msg: "服务器.失败".tr);
      }
    } catch (e) {
      EasyDartModule.logger.info("更新消息已读状态->$e");
      DailyLogUtils.writeLog("更新消息已读状态->$e");
      return ApiResponse(code: -1, msg: "服务器.失败".tr);
    }
  }
}
