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

@JsonSerializable()
class DeviceShareModel {
  String? _id; // 设备类型
  String? name; // 设备类型
  int? type; // 设备类型
  String? image; // 设备类型
  DeviceShareModel();

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

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

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

class DeviceShareController extends GetControllerEx<DeviceShareModel> {
  DeviceShareController() {
    attr = GetModel(DeviceShareModel()).obs;
  }
  RxList deviceTypeList = [].obs;

  RxString account = "".obs;
  RxString msg = "".obs;
  RxInt code = 0.obs;

  Future<ApiResponse> getDeviceType() async {
    ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.device_type;
    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);
      if (res.code != HttpStatusCodes.ok) {
        if (res.msg == null || res.msg!.isEmpty) {
          res.msg = apiResponse.msg;
        }
      } else {
        deviceTypeList.value = res.data;
      }
      return res;
    } else {
      return ApiResponse(code: -1, msg: "服务器.失败".tr);
    }
  }

  Future<ApiResponse> shareDevice(String mac) async {
    ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
    EasyDartModule.logger.info("分享设备");
    DailyLogUtils.writeLog("分享设备");
    try {
      account.value = account.value.trim();
      if (account.value == null || account.value.isEmpty) {
        apiResponse.msg = "请输入手机号或者邮箱".tr;
        return apiResponse;
      }
      if (!MyUtils.isValidPhoneNumber(account.value) &&
          !MyUtils.isValidEmail(account.value)) {
        apiResponse.msg = '请输入正确的手机号或者邮箱'.tr;
        return apiResponse;
      }
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_share;
      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 = {"type": 1, "userName": account.value, "mac": mac};
      var response =
          await EasyDartModule.dio.post(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);
        if (res.code != HttpStatusCodes.ok) {
          if (res.msg == null || res.msg!.isEmpty) {
            res.msg = apiResponse.msg;
          }
        } else {
          if (res.msg == null || res.msg!.isEmpty) {
            res.msg = "操作成功".tr;
          }
        }
        if (res.code != HttpStatusCodes.ok) {
          msg.value = res.msg!;
        }
        code.value = res.code!;
        updateAll();
        return res;
      } else {
        return ApiResponse(code: -1, msg: "服务器.失败".tr);
      }
    } catch (e) {
      EasyDartModule.logger.info("分享设备失败：${e.toString()}");
      DailyLogUtils.writeLog("分享设备失败：${e.toString()}");
      return ApiResponse(code: -1, msg: "服务器.失败".tr);
    }
  }

  //确认接受设备分享
  Future<ApiResponse> confirmShare(String shareCode) async {
    EasyDartModule.logger.info("确认消息分享");
    DailyLogUtils.writeLog("确认消息分享");
    try {
      ApiResponse apiResponse = ApiResponse(code: -1, msg: "请求失败".tr);
      if (shareCode == null || shareCode.isEmpty) {
        apiResponse.msg = "请求失败".tr;
        return apiResponse;
      }
      String serviceAddress = ServiceConstant.service_address;
      String serviceName = ServiceConstant.server_service;
      String serviceApi = ServiceConstant.device_share;
      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 = {
        "code": shareCode,
      };
      var response =
          await EasyDartModule.dio.put(queryUrl, data: jsonEncode(data));
      if (response != null) {
        if (response.data['code'] != HttpStatusCodes.ok) {
          apiResponse.msg = response.data['msg'];
          apiResponse.code = response.data['code'];
          return apiResponse;
        }
        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);
    }
  }
}
