import 'package:vitalapp/pages/check/models/form.dart';

List<FormObject> getFormObjectData(List<Map<String, dynamic>> formData) {
  List<FormObject> formObjectData = [];

  for (var i in formData) {
    formObjectData.add(FormObject.fromJson(i));
  }
  return formObjectData;
}

List<FormObject> updateChildren(List<Map<String, dynamic>> formData) {
  List<FormObject> updatedList = [];

  List<FormObject> formObjectDataList = getFormObjectData(formData);
  for (var i = 0; i < formObjectDataList.length; i++) {
    var item = formObjectDataList[i];
    var parentKey = item.parentKey;

    if (parentKey != null) {
      var parentIndex = -1;

      // 查找父对象的索引
      for (var j = 0; j < updatedList.length; j++) {
        if (updatedList[j].key == parentKey) {
          parentIndex = j;
          break;
        }
      }

      // 如果找到了父对象，则将当前对象放在父对象的"children"下面
      if (parentIndex != -1) {
        if (updatedList[parentIndex].children?.isNotEmpty ?? false) {
          // 检查当前对象是否已经在父对象的"children"中
          var existingChildIndex = -1;
          var children = updatedList[parentIndex].children;
          for (var k = 0; k < children!.length; k++) {
            if (children[k].key == item.key) {
              existingChildIndex = k;
              break;
            }
          }

          // 如果当前对象不在父对象的"children"中，则将其添加进去
          if (existingChildIndex == -1) {
            updatedList[parentIndex].children!.add(item);
          }
        } else {
          updatedList[parentIndex].children = [item];
        }
      } else {
        updatedList.add(item);
      }
    } else {
      updatedList.add(item);
    }
  }

  return updatedList;
}
