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/util/MyUtils.dart';
import 'package:vbvs_app/common/util/requestWithLog.dart';
import 'package:vbvs_app/controller/main_bottom/global_controller.dart';

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

@JsonSerializable()
class PeopleInfoModel {
  String? name;
  String sex = "男";
  String? height;
  String? weight;
  DateTime? birthday;
  String? phone;
  String? contact;
  List peopleList = [];
  PeopleInfoModel();

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

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

class PeopleInfoController extends GetControllerEx<PeopleInfoModel> {
  PeopleInfoController() {
    attr = GetModel(PeopleInfoModel()).obs;
  }

  @override
  Future<void> onInit() async {
    super.onInit();
    await getPeoples(Get.arguments['mac']); // 控制器创建时立即执行
  }

  getPeoples(String mac) async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.person_info;
    String queryUrl = "$serviceAddress$serviceName$serviceApi?mac=$mac";

    requestWithLog(
      logTitle: "获取设备的人员信息列表",
      method: MyHttpMethod.get,
      queryUrl: queryUrl,
      onSuccess: (res) {
        if (res.data != null && res.data is List) {
          model.peopleList = res.data;
          updateAll();
          print("peopleList: ${model.peopleList}");
        }
      },
      onFailure: (err) {
        print("获取人员信息失败: $err");
      },
    );
  }

  savePeoples(Map<String, dynamic> data) async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.person_info;
    String queryUrl = "$serviceAddress$serviceName$serviceApi";
    requestWithLog(
      logTitle: "更新人员信息",
      method: MyHttpMethod.put,
      queryUrl: queryUrl,
      data: data,
      onSuccess: (res) {
        print("更新人员信息成功: $res");
      },
      onFailure: (err) {
        print("更新人员信息失败: $err");
      },
    );
  }
}
