csvDataManager.dart 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import 'dart:convert';
  2. import 'package:fis_common/logger/logger.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:get/get.dart';
  5. import 'interfaces/csvData.dart';
  6. import 'interfaces/models/csv_data.dart';
  7. import 'interfaces/template.dart';
  8. class CsvDataManager implements ICsvDataManager {
  9. ///将csv中的数据解析成结构化数据
  10. @override
  11. Future<List<CsvRevord>> CsvDataConvert(List<List<dynamic>> datas) async {
  12. var json = await Get.find<ITemplateManager>()
  13. .getTemplateByKey("BiochemicalValues");
  14. List<CsvRevord> csvRevords = [];
  15. List<dynamic> items = jsonDecode(json);
  16. List<List<List<dynamic>>> result = _splitIntoChunks(datas);
  17. for (List<List<dynamic>> chunkDatas in result) {
  18. List<CsvData> csvDatas = [];
  19. for (var item in items) {
  20. try {
  21. if (item is Map) {
  22. int row = item["row"];
  23. int column = item["column"];
  24. String key = item["key"];
  25. String des = item["des"];
  26. String identifier = item["identifier"];
  27. String referenceRange = item["referenceRange"];
  28. String unit = item["unit"];
  29. String value = "";
  30. if (chunkDatas.length >= row + 1) {
  31. var rowValue = chunkDatas[row];
  32. if (rowValue.length >= column + 1) {
  33. value = chunkDatas[row][column].toString().trim();
  34. } else {
  35. continue;
  36. }
  37. } else {
  38. continue;
  39. }
  40. csvDatas.add(CsvData(
  41. key: key,
  42. value: value,
  43. des: des,
  44. unit: unit,
  45. identifier: identifier,
  46. referenceRange: referenceRange,
  47. ));
  48. }
  49. } catch (e) {
  50. logger.e("CsvDataManager csvDataConvert ex:", e);
  51. }
  52. }
  53. csvRevords.add(CsvRevord(csvDatas));
  54. }
  55. return csvRevords;
  56. }
  57. List<List<List<dynamic>>> _splitIntoChunks(List<List<dynamic>> datas) {
  58. List<List<List<dynamic>>> records = [];
  59. List<List<dynamic>> currentRecord = [];
  60. for (int i = 0; i < datas.length; i++) {
  61. // Check if the current element and the next one are empty lists
  62. if ((datas[i].length == 1 && datas[i][0].isEmpty) &&
  63. i + 1 < datas.length &&
  64. (datas[i + 1].length == 1 && datas[i + 1][0].isEmpty)) {
  65. // Skip the next empty list as it is part of the separator
  66. i++;
  67. // Add the current record to records if it is not empty
  68. if (currentRecord.isNotEmpty) {
  69. records.add(List.from(currentRecord));
  70. currentRecord.clear();
  71. }
  72. } else {
  73. // Add the current data to the current record
  74. currentRecord.add(datas[i]);
  75. }
  76. }
  77. // Add the last record if it's not empty (case when no trailing empty lists)
  78. if (currentRecord.isNotEmpty) {
  79. records.add(currentRecord);
  80. }
  81. return records;
  82. }
  83. }