insert method

Future<int> insert(
  1. Map<String, dynamic> data
)

Cria um registro com auto-incremento de ID

Implementation

Future<int> insert(Map<String, dynamic> data) async {
  final rows = await getRawRows(forceRefresh: true);
  if (rows.isEmpty) throw Exception("Cabeçalhos não encontrados.");

  final headers = List<String>.from(rows[0]);
  int idColIndex = headers.indexOf("id");

  int maxId = 0;
  int lastPopulatedRow = 1; // 1 is header
  int firstEmptyRow = -1;

  for (var i = 1; i < rows.length; i++) {
    bool isEmptyId = true;
    if (rows[i].length > idColIndex) {
      var val = rows[i][idColIndex];
      var idStr = val == null ? "" : val.toString().trim();
      if (idStr.isNotEmpty && idStr != "null") {
        isEmptyId = false;
        lastPopulatedRow = i + 1;

        var id = double.tryParse(idStr)?.toInt() ?? int.tryParse(idStr);
        if (id != null && id > maxId) {
          maxId = id;
        }
      }
    }
    if (isEmptyId && firstEmptyRow == -1) {
      firstEmptyRow = i + 1;
    }
  }

  int newId = maxId + 1;
  int nextRow = firstEmptyRow != -1 ? firstEmptyRow : lastPopulatedRow + 1;

  final newRow = headers.map((h) => h == "id" ? newId : data[h]).toList();
  List<sheets.ValueRange> updateData = [];

  for (int i = 0; i < headers.length; i++) {
    var val = newRow[i];
    if (val != null && val.toString().isNotEmpty) {
      String colLetter = listAlfabetic(i);
      updateData.add(
        sheets.ValueRange(
          range: '$sheetName!$colLetter$nextRow',
          values: [
            [val],
          ],
        ),
      );
    }
  }

  if (updateData.isNotEmpty) {
    final batchRequest = sheets.BatchUpdateValuesRequest(
      valueInputOption: "USER_ENTERED",
      data: updateData,
    );

    await api.spreadsheets.values.batchUpdate(batchRequest, spreadsheetId);
  }

  _cachedRawRows = null; // Invalida o cache
  return newId;
}