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/common/util/requestWithLog.dart';
import 'package:vbvs_app/model/api_response.dart';

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

@JsonSerializable()
class MHTHomeModel {
  MHTHomeModel();

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

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

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

class MHTHomeController extends GetControllerEx<MHTHomeModel> {
  MHTHomeController() {
    attr = GetModel(MHTHomeModel()).obs;
  }

  RxInt bindDeviceNum = 0.obs; //设备数量
  RxMap deviceList = {}.obs; //设备列表
  RxList deviceListForWeb = [].obs; //h5设备列表
  RxMap<String, List<dynamic>> sleepReportData =
      <String, List<dynamic>>{}.obs; //睡眠报告
  RxList personnelList = [].obs; //人员信息列表

  RxString keyWord = "".obs;

  String wifiMac = "";
  var sleepDays = [].obs;
  var homeSleepDays = [].obs;

  var selectedDayIndex = (6).obs;

  var selectDevcie = ''.obs;
  var selectPerson = {}.obs;

  bool initDeviceFlag = false;

  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, String? group, int? bindType}) async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "设备.设备列表请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_list;

      // 初始URL
      String queryUrl = "$serviceAddress$serviceName$serviceApi";

      // 用Map统一管理query参数
      Map<String, String> queryParams = {};

      if (key != null && key.isNotEmpty) {
        queryParams['key'] = key;
      }

      if (group != null && group.isNotEmpty) {
        queryParams['group'] = group;
      }

      if (bindType != null) {
        queryParams['bindType'] = bindType.toString();
      }

      String? language = "";
      if (languageController.selectLanguage != null) {
        language = languageController.selectLanguage.value!.language_code;
      }
      if (language != null && language.isNotEmpty) {
        queryParams['lang'] = language;
      }

      // 拼接完整URL
      if (queryParams.isNotEmpty) {
        queryUrl += '?' + Uri(queryParameters: queryParams).query;
      }

      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) {
          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> getDeviceListForWeb(
      {String? key, String? group, int? bindType}) async {
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "设备.设备列表请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_list;

      // 初始URL
      String queryUrl = "$serviceAddress$serviceName$serviceApi";

      // 用Map统一管理query参数
      Map<String, String> queryParams = {};

      if (key != null && key.isNotEmpty) {
        queryParams['key'] = key;
      }

      if (group != null && group.isNotEmpty) {
        queryParams['group'] = group;
      }

      if (bindType != null) {
        queryParams['bindType'] = bindType.toString();
      }

      String? language = "";
      if (languageController.selectLanguage != null) {
        language = languageController.selectLanguage.value!.language_code;
      }
      if (language != null && language.isNotEmpty) {
        queryParams['lang'] = language;
      }

      // 拼接完整URL
      if (queryParams.isNotEmpty) {
        queryUrl += '?' + Uri(queryParameters: queryParams).query;
      }

      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) {
          deviceListForWeb.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
  }

  //查询人员信息列表
  Future<void> getPersonList() async {
    ApiResponse apiResponse = ApiResponse(code: -1, msg: "设备.设备列表请求失败".tr);
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.personnel_info;

    // 初始URL
    String queryUrl = "$serviceAddress$serviceName$serviceApi";
    await requestWithLog(
      logTitle: "请求人员信息列表",
      method: MyHttpMethod.get,
      queryUrl: queryUrl,
      onSuccess: (res) {
        personnelList.value = res.data ?? [];
      },
      onFailure: (res) {
        EasyDartModule.logger.warning("请求人员信息列表失败: ${res.msg}");
      },
    );
  }

  Future<void> getSleeps(String? mac) async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.sleep_report;
    String queryUrl = "$serviceAddress$serviceName$serviceApi";

    // 当前时间的毫秒时间戳
    int timestamp = DateTime.now().millisecondsSinceEpoch;

    // 拼接参数
    List<String> queryParams = [];

    if (mac != null && mac.isNotEmpty) {
      queryParams.add("mac=$mac");
    }
    queryParams.add("time=$timestamp");

    if (queryParams.isNotEmpty) {
      queryUrl += "?${queryParams.join("&")}";
    }

    await requestWithLog(
      logTitle: "请求睡眠信息列表",
      method: MyHttpMethod.get,
      queryUrl: queryUrl,
      onSuccess: (res) {
        if (res.data != null && res.data is List) {
          List<dynamic> rawList = res.data;
          List<Map<String, dynamic>> processedList =
              rawList.map<Map<String, dynamic>>((item) {
            Map<String, dynamic> map = Map<String, dynamic>.from(item);

            // 取出 time
            String? timeStr = map['time'];
            int? timeMillis = timeStr != null ? int.tryParse(timeStr) : null;

            if (timeMillis != null) {
              DateTime dateTime =
                  DateTime.fromMillisecondsSinceEpoch(timeMillis);

              // 格式化 week 和 date
              String week = MyUtils.formatDateTimeWeek(dateTime);
              String date = MyUtils.formatDateTimeDay(dateTime);

              // 添加到 map 中
              map['week'] = week;
              map['date'] = date;
            }

            return map;
          }).toList();

          // 赋值给 sleepDays
          sleepDays.value = processedList;
        } else {
          // 为空时直接赋空数组
          sleepDays.value = [];
        }

        // 更新UI
        updateAll();
      },
      onFailure: (res) {
        EasyDartModule.logger.warning("请求睡眠信息列表失败: ${res.msg}");
      },
    );
  }

  Future<void> getHomeSleeps(String? mac) async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.sleep_report;
    String queryUrl = "$serviceAddress$serviceName$serviceApi";

    // 当前时间的毫秒时间戳
    int timestamp = DateTime.now().millisecondsSinceEpoch;

    // 拼接参数
    List<String> queryParams = [];

    if (mac != null && mac.isNotEmpty) {
      queryParams.add("mac=$mac");
    }
    queryParams.add("time=$timestamp");

    if (queryParams.isNotEmpty) {
      queryUrl += "?${queryParams.join("&")}";
    }

    await requestWithLog(
      logTitle: "请求睡眠信息列表",
      method: MyHttpMethod.get,
      queryUrl: queryUrl,
      onSuccess: (res) {
        if (res.data != null && res.data is List) {
          List<dynamic> rawList = res.data;
          List<Map<String, dynamic>> processedList =
              rawList.map<Map<String, dynamic>>((item) {
            Map<String, dynamic> map = Map<String, dynamic>.from(item);

            // 取出 time
            String? timeStr = map['time'];
            int? timeMillis = timeStr != null ? int.tryParse(timeStr) : null;

            if (timeMillis != null) {
              DateTime dateTime =
                  DateTime.fromMillisecondsSinceEpoch(timeMillis);

              // 格式化 week 和 date
              String week = MyUtils.formatDateTimeWeek(dateTime);
              String date = MyUtils.formatDateTimeDay(dateTime);

              // 添加到 map 中
              map['week'] = week;
              map['date'] = date;
            }

            return map;
          }).toList();

          // 赋值给 sleepDays
          homeSleepDays.value = processedList;
        } else {
          // 为空时直接赋空数组
          homeSleepDays.value = [];
        }

        // 更新UI
        updateAll();
      },
      onFailure: (res) {
        EasyDartModule.logger.warning("请求睡眠信息列表失败: ${res.msg}");
      },
    );
  }

  //开启定时器
  void startTimer(args) {
    var tmp = args[0];
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.user_setting;
    String type = "control_${tmp['mac']}";
    String queryUrl = "${serviceAddress}${serviceName}${serviceApi}";
    var data = {
      "type": type,
      "duration": tmp['duration'],
      "mac": tmp['mac'],
      "time": tmp['startTime'],
    };
    requestWithLog(
        logTitle: "更新控制倒计时",
        method: MyHttpMethod.put,
        queryUrl: queryUrl,
        data: data,
        onSuccess: (res) {});
  }

  //关闭定时器
  void cancelTimer(args) {
    var tmp = args[0];
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.user_setting;
    String type = "control_${tmp['mac']}";
    String queryUrl = "${serviceAddress}${serviceName}${serviceApi}";
    var data = {
      "type": type,
      "duration": 0,
      "mac": tmp['mac'],
      "time": tmp['startTime'],
    };
    requestWithLog(
        logTitle: "查询控制倒计时",
        method: MyHttpMethod.put,
        queryUrl: queryUrl,
        data: data,
        onSuccess: (res) {});
  }

  //恢复
  restoreTimer(args) async {
    var data = {};
    try {
      var tmp = args[0];
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.user_setting;
      String type = "control_${tmp}";
      String queryUrl =
          "${serviceAddress}${serviceName}${serviceApi}?type=$type";
      await requestWithLog(
        logTitle: "查询控制倒计时",
        method: MyHttpMethod.get,
        queryUrl: queryUrl,
        onSuccess: (res) {
          if (res.data != null) {
            data = res.data;
          }
        },
        onFailure: (res) {
          data = {};
        },
      );
    } catch (e) {
      ef.log("$e");
    }

    return data;
  }
}
