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/controller/setting/language/language_controller.dart';
import 'package:vbvs_app/model/api_response.dart';

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

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

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

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

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

class DeviceTypeController extends GetControllerEx<DeviceTypeModel> {
  DeviceTypeController() {
    attr = GetModel(DeviceTypeModel()).obs;
  }
  RxList deviceTypeList = [].obs;
  LanguageController languageController = Get.find();

  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";
      }
    }
    try {
      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);
      }
    } catch (e) {
      return apiResponse;
    }
  }
}
