import 'package:ef/ef.dart';
import 'package:flutter/material.dart';
import 'package:flutter_city_picker/model/address.dart';
import 'package:flutterflow_ui/flutterflow_ui.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:lpinyin/lpinyin.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/component/tool/TopSlideNotification.dart';
import 'package:vbvs_app/controller/user_info_controller.dart';
import 'package:vbvs_app/model/user_data.dart';
// import 'package:lpinyin/lpinyin.dart';
part 'address_controller.g.dart';

@JsonSerializable()
class AddressModel {
  //版本id
  String? province; //省份
  String? city; //市
  String? county; //区
  String? street; //街道
  String? address; //详细信息
  String? name; //名字
  String? tel; //手机号
  @JsonKey(name: 'default')
  int? default_ = 0; //是否默认

  int currentType = 0;
  String? all_address;
  @JsonKey(ignore: true)
  List<AddressNode>? addressList = [];

  AddressModel();

  static AddressModel fromJson(Map<String, dynamic> json) =>
      _$AddressModelFromJson(json);
  Map<String, dynamic> toJson() => _$AddressModelToJson(this);
}

class AddressController extends GetControllerEx<AddressModel> {
  AddressController() {
    attr = GetModel(AddressModel()).obs;
  }

  Future<String> updateAddress(
      Map<String, dynamic> address, AddressModel model) async {
    if (model.addressList != null && model.addressList!.isNotEmpty) {
      if (model.addressList!.length > 0) {
        address["province"] = model.addressList![0].name; // 第一个元素为省
      }
      if (model.addressList!.length > 1) {
        address["city"] = model.addressList![1].name; // 第二个元素为市
      }
      if (model.addressList!.length > 2) {
        address["county"] = model.addressList![2].name; // 第三个元素为区
      }
      if (model.addressList!.length > 3) {
        address["street"] = model.addressList![3].name; // 第四个元素为街道
      }
    }
    address['address'] = model.address;
    address['name'] = model.name;
    address['tel'] = model.tel;
    address['default'] = model.default_;

    String serviceAddress = ServiceConstant.service_address;
    String serviceName = ServiceConstant.server_service;
    String serviceApi = ServiceConstant.add_address;
    String queryUrl = "${serviceAddress}${serviceName}${serviceApi}";
    await requestWithLog(
      logTitle: "更新地址",
      method: MyHttpMethod.put,
      queryUrl: queryUrl,
      data: {
        "id": address['_id'],
        "default": address['default'],
        "name": address['name'],
        "tel": address['tel'],
        // "area": address['all_address'],
        "address": address['address'],
        "province": address['province'],
        "city": address['city'],
        "county": address['county'],
        "street": address['street'],
      },
      onSuccess: (res) {
        if (res.code == 1) {
          print("更新地址成功");
        }
      },
    );
    return '';
  }

  Future<void> addAddress(AddressModel model, BuildContext context) async {
    try {
      final UserInfoController userInfoController =
          Get.find<UserInfoController>();
      UserModel user = userInfoController.model.user!;

      // 设置省市区街道名称
      if (model.addressList != null && model.addressList!.isNotEmpty) {
        if (model.addressList!.length > 0)
          model.province = model.addressList![0].name;
        if (model.addressList!.length > 1)
          model.city = model.addressList![1].name;
        if (model.addressList!.length > 2)
          model.county = model.addressList![2].name;
        if (model.addressList!.length > 3)
          model.street = model.addressList![3].name;
      }

      // 查询现有地址判断是否设置为默认
      String listUrl =
          "${ServiceConstant.service_address}${ServiceConstant.server_service}${ServiceConstant.address_list}";
      final listRes = await requestWithLog(
        logTitle: "查询地址列表",
        method: MyHttpMethod.get,
        queryUrl: listUrl,
      );
      if (listRes.data.length <= 0) {
        model.default_ = 1;
      }
      // 添加地址
      String addUrl =
          "${ServiceConstant.service_address}${ServiceConstant.server_service}${ServiceConstant.add_address}";
      final addRes = await requestWithLog(
        logTitle: '添加地址',
        method: MyHttpMethod.post,
        queryUrl: addUrl,
        data: model.toJson(),
      );

      if (addRes.code == 1) {
        TopSlideNotification.show(context, text: "添加成功".tr);
      }
    } catch (e) {
      print(e);
    }
  }

  List<dynamic>? _cityCache;

  Future<void> _loadCityDataOnce() async {
    if (_cityCache != null) return;

    String country = "CN";
    String queryUrl =
        "${ServiceConstant.service_address}${ServiceConstant.server_service}${ServiceConstant.city_data}?country=$country";

    await requestWithLog(
      logTitle: "查询城市数据",
      method: MyHttpMethod.get,
      queryUrl: queryUrl,
      onSuccess: (res) {
        if (res.data != null && res.data is List) {
          // 提取所有 data 并展开成一个统一列表
          _cityCache = res.data
              .where((e) => e["data"] != null && e["data"] is List)
              .expand((e) => e["data"] as List)
              .toList();
        }
      },
    );
  }

  // 构建查询
  Future<List<AddressNode>> getData({int? level, String? parentCode}) async {
    await _loadCityDataOnce(); // 确保只加载一次
    if (_cityCache == null) return [];

    // 获取省级数据
    if (parentCode == null || parentCode.isEmpty) {
      return _cityCache!.map<AddressNode>((item) {
        return AddressNode.fromJson({
          "name": item["name"],
          "code": item["code"],
          "letter": _getLetter(item["name"]),
        });
      }).toList();
    }

    // 递归查找下级
    final parent = _findNodeByCode(_cityCache!, parentCode);
    if (parent == null || parent["children"] == null) return [];

    List children = parent["children"];
    return children.map<AddressNode>((item) {
      return AddressNode.fromJson({
        "name": item["name"],
        "code": item["code"],
        "letter": _getLetter(item["name"]),
      });
    }).toList();
  }

  Map<String, dynamic>? _findNodeByCode(List<dynamic> list, String code) {
    for (var item in list) {
      if (item is Map<String, dynamic>) {
        if (item["code"] == code) return item;
        if (item["children"] != null && item["children"] is List) {
          var result = _findNodeByCode(item["children"], code);
          if (result != null) return result;
        }
      }
    }
    return null;
  }

// 工具：中文首字母转大写英文（你也可以用更专业的拼音库）
  String _getLetter(String name) {
    // return name;
    if (name.isEmpty) return "#";
    String pinyin = PinyinHelper.getPinyinE(name,
        separator: '', defPinyin: '', format: PinyinFormat.WITHOUT_TONE);
    if (pinyin.isEmpty) return "#";
    return pinyin[0].toUpperCase();
  }
}
