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 'body_device_controller.g.dart'; // 由json_serializable自动生成的部分

@JsonSerializable()
class BodyDeviceModel {
  int? type = 1; //设备类型 1:我的e护 2.云关爱

  BodyDeviceModel();

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

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

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

class BodyDeviceController extends GetControllerEx<BodyDeviceModel> {
  BodyDeviceController() {
    attr = GetModel(BodyDeviceModel()).obs;
  }

  RxInt bindDeviceNum = 0.obs;
  RxList deviceList = [].obs;
  RxMap<String, List<dynamic>> sleepReportData = <String, List<dynamic>>{}.obs;

  RxString keyWord = "".obs;

  String wifiMac = "";

  

  Future<ApiResponse> getDeviceNum() async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "设备.设备列表请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_list;
      String queryUrl =
          "${serviceAddress}${serviceName}${serviceApi}?bindNum=1";
      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!;
          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> getDeviceList({String? key}) async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "设备.设备列表请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_list;
      String queryUrl =
          "${serviceAddress}${serviceName}${serviceApi}?bindType=${model.type}${key != null ? '&key=$key' : ''}";
      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!;
          deviceList.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
  }

  Future<ApiResponse> deleteDevice(Map<String, dynamic> device) async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_bind;
      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";
        }
      }
      final data = {
        "mac": device['mac'],
      };
      var response =
          await EasyDartModule.dio.delete(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");
    } finally {
      EasyDartModule.logger.info("用户操作：解绑设备");
      DailyLogUtils.writeLog("用户操作：解绑设备");
    }
    return ApiResponse(code: -1, msg: "未知错误".tr); // Default return statement
  }

  Future<ApiResponse> getSleepReport() async {
    try {
      sleepReportData.value = {};
      ApiResponse<Map<String, List<dynamic>>> apiResponse = ApiResponse(
        code: -1,
        msg: "请求失败".tr,
      );

      if (deviceList.value.isEmpty) {
        return ApiResponse(
          code: HttpStatusCodes.ok,
          msg: "请求成功".tr,
        );
      }

      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.sleep_report;

      for (var device in deviceList.value) {
        String mac = device['mac'] ?? "";
        if (mac.isEmpty) continue;

        sleepReportData[mac] = []; // 初始化当前设备的数据列表

        String queryUrl =
            "$serviceAddress$serviceName$serviceApi?mac=$mac&time=${DateTime.now().millisecondsSinceEpoch}";

        try {
          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);

            if (res.code == HttpStatusCodes.ok && res.data != null) {
              // 确保数据是一个列表
              if (res.data is List) {
                sleepReportData[mac] = List.from(res.data);
              } else {
                sleepReportData[mac] = [res.data];
              }
            }
          }
        } catch (e) {
          EasyDartModule.logger.warning("请求设备 $mac 的睡眠数据失败: $e");
        }
      }
      if (sleepReportData.value.isNotEmpty) {
        // 遍历 Map 中的每一个键值对
        sleepReportData.value.forEach((key, report) {
          // 确保 report 列表不为空
          if (report.isNotEmpty) {
            // 获取该列表的最后一个元素
            var lastElement = report.last;

            // 给最后一个元素添加 selected 属性
            lastElement['selected'] = true; // 假设每个元素是一个 Map 类型
          }
        });
      }

      updateAll();

      return ApiResponse(
        code: HttpStatusCodes.ok,
        msg: "请求成功".tr,
        data: sleepReportData,
      );
    } catch (e) {
      EasyDartModule.logger.info("设备请求列表异常: $e");
      DailyLogUtils.writeLog("设备请求列表异常: $e");
      return ApiResponse(code: -1, msg: "未知错误".tr, data: {});
    }
  }

  updateDeviceShow(device) async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "操作失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_show;
      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 data = {
        "id": device['_id'],
        "show": !device['show'],
      };
      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
  }
}
