53 lines
1.9 KiB
Dart
53 lines
1.9 KiB
Dart
import '../../../../core/network/api_client.dart';
|
|
import '../models/patient_search_item_model.dart';
|
|
|
|
class PatientSearchService {
|
|
final ApiClient apiClient;
|
|
|
|
PatientSearchService({ApiClient? client}) : apiClient = client ?? ApiClient();
|
|
|
|
Future<List<PatientSearchItemModel>> searchPatients(String rawQuery, {int limit = 25}) async {
|
|
final cleanQuery = rawQuery.trim();
|
|
if (cleanQuery.isEmpty) return [];
|
|
|
|
try {
|
|
final words = cleanQuery.split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
|
|
final queryParams = <String>[
|
|
'limit=$limit',
|
|
'sort=-id',
|
|
'fields=id,nombre,apellido,cedula,telefono,edad,sexo,fec_ultcon,seguro,mot_cons',
|
|
];
|
|
|
|
if (words.length == 1) {
|
|
final w = Uri.encodeQueryComponent(words.first);
|
|
queryParams.add('filter[_or][0][nombre][_icontains]=$w');
|
|
queryParams.add('filter[_or][1][apellido][_icontains]=$w');
|
|
queryParams.add('filter[_or][2][cedula][_icontains]=$w');
|
|
queryParams.add('filter[_or][3][telefono][_icontains]=$w');
|
|
if (int.tryParse(words.first) != null) {
|
|
queryParams.add('filter[_or][4][id][_eq]=${words.first}');
|
|
}
|
|
} else {
|
|
for (var i = 0; i < words.length; i++) {
|
|
final w = Uri.encodeQueryComponent(words[i]);
|
|
queryParams.add('filter[_and][$i][_or][0][nombre][_icontains]=$w');
|
|
queryParams.add('filter[_and][$i][_or][1][apellido][_icontains]=$w');
|
|
}
|
|
}
|
|
|
|
final url = '/items/pacientes?${queryParams.join('&')}';
|
|
final response = await apiClient.dio.get(url);
|
|
|
|
if (response.statusCode == 200 && response.data != null) {
|
|
final data = response.data['data'] as List<dynamic>? ?? [];
|
|
return data
|
|
.map((item) => PatientSearchItemModel.fromJson(item as Map<String, dynamic>))
|
|
.toList();
|
|
}
|
|
return [];
|
|
} catch (e) {
|
|
throw Exception('Error al consultar pacientes en Directus: $e');
|
|
}
|
|
}
|
|
}
|