import 'dart:convert';

import 'package:fis_jsonrpc/services/diagnosis.m.dart';
import 'package:get/get.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/managers/interfaces/diagnosis.dart';
import 'package:vitalapp/managers/interfaces/dictionary.dart';
import 'package:vitalapp/pages/medical/records/state.dart';

class MedicalRecordsController extends FControllerBase {
  final state = MedicalRecordsState();
  final _diagnosisManager = Get.find<IDiagnosisManager>();
  final _dictionaryManager = Get.find<IDictionaryManager>();

  late String patientCode;
  @override
  void onReady() {
    super.onReady();
    final p = Get.parameters;
    patientCode = p['patientCode'] ?? "";
    _loadData();
  }

  _loadData() async {
    try {
      var result =
          await _diagnosisManager.getDiagnosisAggregationPageAsync(patientCode);
      if (result != null) {
        state.updateDto(result);
      }
    } catch (e) {}
  }

  Future<List<List<String>>> getTableData(
      DiagnosisAggregationRecord dto) async {
    var currentDiagnosis = <List<String>>[];
    var index = 1;
    // this.diagnosisTime = DateFormat("yyyy-MM-dd HH:mm:ss").format(row.diagnosisTime);
    for (var element in dto.diagnosisAggregationData!) {
      if (element.diagnosisData != "null") {
        var jsonData = json.decode(element.diagnosisData!);
        List<String> keys = jsonData.keys.toList();
        var dtos =
            await _dictionaryManager.getDictionaryNameAndUnitByKeysAsync(keys);
        for (var key in keys) {
          var dto = dtos?.firstWhere((item) => item.key == key);
          currentDiagnosis.add([
            (index++).toString(),
            dto?.name ?? '',
            jsonData[key],
            dto?.unit ?? '',
          ]);
        }
      }
    }
    return currentDiagnosis;
  }
}
