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/util/requestWithLog.dart';

part 'address_list_controller.g.dart';

@JsonSerializable()
class AddressListModel {
  List addressList = [];
  Map address = {}; //之前控制的设备

  int? type = 1; //1添加，2编辑

  AddressListModel();

  static AddressListModel fromJson(Map<String, dynamic> json) =>
      _$AddressListModelFromJson(json);
  Map<String, dynamic> toJson() => _$AddressListModelToJson(this);
}

class AddressListController extends GetControllerEx<AddressListModel> {
  AddressListController() {
    attr = GetModel(AddressListModel()).obs;
  }

  getAddressList() async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.address_list;
    String queryUrl = "$serviceAddress$serviceName$serviceApi";

    requestWithLog(
      logTitle: '查询地址列表',
      method: MyHttpMethod.get,
      queryUrl: queryUrl,
      onSuccess: (res) {
        // 安全检查 res.data 是否为 List
        if (res.data != null && res.data is List && res.data.isNotEmpty) {
          model.addressList = res.data;
        } else {
          model.addressList = []; // 设为空数组，防止空指针问题
        }
        updateAll();
      },
      onFailure: (err) {
        model.addressList = []; // 请求失败时也清空列表以防旧数据残留
        updateAll();
      },
    );
  }

  // // 删除地址
  Future<void> deleteAddress(String id) async {
    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.add_address;
    String queryUrl = "$serviceAddress$serviceName$serviceApi?id=$id";
    requestWithLog(
      logTitle: '删除地址',
      method: MyHttpMethod.delete,
      queryUrl: queryUrl,
      onSuccess: (res) {
        getAddressList();
      },
      onFailure: (err) {
        getAddressList();
      },
    );
  }
}
