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

@JsonSerializable()
class DeviceShareListModel {
  String? key; //关键字搜索
  int? all = 0; //是否全选 0：不全选 1：全选
  String? accountKey = 'uid';//账户key

  DeviceShareListModel();

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

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

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

class DeviceShareListController extends GetControllerEx<DeviceShareListModel> {
  DeviceShareListController() {
    attr = GetModel(DeviceShareListModel()).obs;
  }
  RxList shareInfoList = [].obs;
  RxList selectedShareInfo = [].obs;

  //查询分享信息
  Future<ApiResponse> getDeviceShareList(String mac, {String? key}) async {
    try {
      EasyDartModule.logger.info("设备设备分享列表");
      DailyLogUtils.writeLog("设备设备分享列表");
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_share;
      String queryUrl = "${serviceAddress}${serviceName}${serviceApi}"
          "${key != null ? '?key=$key&' : '?'}mac=$mac";
      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) {
          shareInfoList.value = res.data!;
          updateAll();
          return res;
        }
      } else {
        return ApiResponse(code: -1, msg: "服务器.失败".tr);
      }
      return apiResponse;
    } catch (e) {
      EasyDartModule.logger.error("设备请求列表: $e");
      DailyLogUtils.writeError("设备请求列表: $e");
    }
    return ApiResponse(code: -1, msg: "未知错误".tr);
  }

  //删除分享
  Future<ApiResponse> deleteShareDevice() async {
    try {
      EasyDartModule.logger.info("删除分享设备");
      DailyLogUtils.writeLog("删除分享设备");
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.share_deleted;
      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": "",
      };
      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.error("删除分享设备: $e");
      DailyLogUtils.writeError("删除分享设备: $e");
    } finally {
      EasyDartModule.logger.info("用户操作：删除分享设备");
      DailyLogUtils.writeLog("用户操作：删除分享设备");
    }
    return ApiResponse(code: -1, msg: "未知错误".tr); // Default return statement
  }
}
