import 'dart:convert';

import 'package:EasyDartModule/EasyDartModule.dart';
import 'package:ef/ef.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 'person_controller.g.dart'; // 由json_serializable自动生成的部分

@JsonSerializable()
class PersonModel {
  int? read = 1;
  // String? name;

  PersonModel();

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

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

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

class PersonController extends GetControllerEx<PersonModel> {
  PersonController() {
    attr = GetModel(PersonModel()).obs;
  }
  RxList selectedDiseaseIds = [].obs;

  RxString currentPersonId = "".obs;
  RxString name = "".obs;
  RxInt gender = 1.obs;
  RxString birthday = "".obs;
  RxString weight = "".obs;
  RxString height = "".obs;
  DateTime? dateTime = DateTime.now(); //选择时间
  RxList diseaseList = [].obs;
  RxString update_person_mac = "".obs;
  var after_deveice;

  Future<ApiResponse> savePersonData() async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "蓝牙绑定.绑定失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.person_info;
      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";
        }
      }
      if (name.value.isEmpty) {
        apiResponse.msg = "请输入姓名".tr;
        return apiResponse;
      }
      if (birthday.value.isEmpty) {
        apiResponse.msg = "请选择生日".tr;
        return apiResponse;
      }
      if (weight == null || weight.value.isEmpty) {
        apiResponse.msg = "请输入体重".tr;
        return apiResponse;
      }
      if (height == null || height.value.isEmpty) {
        apiResponse.msg = "请输入身高".tr;
        return apiResponse;
      }

      var data = {
        "id": currentPersonId.value,
        "name": name.value,
        "gender": gender.value,
        "birthday": (birthday.value == null || birthday.value!.isEmpty)
            ? MyUtils.formatBindTime(dateTime!)
            : birthday.value,
        "weight": weight!.value,
        "height": height.value,
        "disease": selectedDiseaseIds.value,
      };
      var response =
          await EasyDartModule.dio.put(queryUrl, data: jsonEncode(data));
      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) {
          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> updatePersonName(person, deviceId) async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.person_info;
      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";
        }
      }
      if (name.value.isEmpty) {
        apiResponse.msg = "请输入姓名".tr;
        return apiResponse;
      }
      if (person == null) {
        person = {};
      }
      person['name'] = name.value;
      person['id'] = deviceId;
      var response =
          await EasyDartModule.dio.put(queryUrl, data: jsonEncode(person));
      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) {
          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> getDiseaseData() async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.disease_list;
      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) {
          // bindDeviceNum.value = res.total!;
          diseaseList.value = res.data!;
          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
  }
}
