import 'dart:convert';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:vitalapp/database/db.dart';
import 'package:vitalapp/managers/interfaces/diagnosis.dart';
import 'package:vitalapp/managers/interfaces/models/diagnosis_aggregation_record_model.dart';
import 'package:vitalapp/rpc.dart';
import 'package:vitalapp/store/store.dart';

class DiagnosisManager implements IDiagnosisManager {
  DiagnosisManager();

  @override
  Future<PageCollection<DiagnosisAggregationRecordModel>?>
      getDiagnosisAggregationPageAsync(
          String patientCode, int pageIndex, int pageSize) async {
    PageCollection<DiagnosisAggregationRecordModel> diagnosisAggregationRecord =
        PageCollection<DiagnosisAggregationRecordModel>();
    try {
      var request = DiagnosisPageRequest(
        token: Store.user.token,
        pageIndex: pageIndex,
        pageSize: pageSize,
        patientCode: patientCode,
      );
      diagnosisAggregationRecord.pageData = [];
      var result =
          await rpc.diagnosis.getDiagnosisAggregationPageAsync(request);
      diagnosisAggregationRecord.pageIndex = result.pageIndex;
      diagnosisAggregationRecord.pageSize = result.pageSize;
      diagnosisAggregationRecord.dataCount = result.dataCount;
      for (var element in result.pageData!) {
        var record = DiagnosisAggregationRecordModel.fromJson(element.toJson());
        record.isExistLocalData = false;
        diagnosisAggregationRecord.pageData!.add(record);
      }
    } catch (e) {}
    return diagnosisAggregationRecord;
  }

  @override
  Future<List<DiagnosisAggregationRecordModel>?> getListByPatientCode(
      String patientCode) async {
    try {
      List<DiagnosisAggregationRecordModel> records =
          <DiagnosisAggregationRecordModel>[];
      final localRecords = await db.repositories.diagnosis
          .getNotUploadedListByPatientCode(patientCode);
      var currentPatient = Store.user.currentSelectPatientInfo!;
      for (var element in localRecords) {
        Map<String, dynamic> data = jsonDecode(element.dataJson);
        List<DiagnosisAggregationData> list = [];
        for (var key in data.keys) {
          list.add(DiagnosisAggregationData(
              key: key, diagnosisData: jsonEncode(data[key])));
        }
        records.add(DiagnosisAggregationRecordModel(
          patientCode: element.patientCode,
          patientName: currentPatient.patientName,
          doctorName: Store.user.displayName,
          diagnosisTime: element.createTime,
          diagnosisAggregationData: list,
          isExistLocalData: true,
        ));
      }
      return records;
    } catch (e) {}
    return null;
  }

  /// 创建健康检测
  @override
  Future<bool> submitDiagnosisAsync(SubmitDiagnosisRequest request) async {
    request.token = Store.user.token;
    print(jsonEncode(request.toJson()));
    var result = await rpc.diagnosis.submitDiagnosisAsync(request);

    return result;
  }
}
