import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/ComprehensiveMedicalCheckup/GetCMCAllOrdersResponseModel.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/Prescriptions.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/perscription_pharmacy.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/prescription_info_rc_model.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/prescription_report.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/prescription_report_enh.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/prescription_report_inp.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/prescriptions_order.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/request_get_list_pharmacy_for_prescriptions.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/request_prescription_report.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/request_prescription_report_enh.dart';
import 'package:diplomaticquarterapp/core/model/prescriptions/request_send_prescription_email.dart';
import 'package:diplomaticquarterapp/core/service/base_service.dart';
import 'package:flutter/cupertino.dart';

class PrescriptionsService extends BaseService {
  List<Prescriptions> prescriptionsList = List();
  List<PrescriptionReportINP> prescriptionReportListINP = List();
  List<GetCMCAllOrdersResponseModel> prescriptionsOrderList = List();
  List<PrescriptionInfoRCModel> prescriptionsOrderListRC = List();
  var isMedDeliveryAllowed;

  Future getPrescriptions() async {
    hasError = false;
    Map<String, dynamic> body = Map();
    body['isDentalAllowedBackend'] = false;
    await baseAppClient.post(PRESCRIPTIONS, onSuccess: (dynamic response, int statusCode) {
      prescriptionsList.clear();
      response['PatientPrescriptionList'].forEach((prescriptions) {
        prescriptionsList.add(Prescriptions.fromJson(prescriptions));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);
  }

  Future getPrescriptionsOrders() async {
    prescriptionsOrderList.clear();
    Map<String, dynamic> body = Map();
    // body['isDentalAllowedBackend'] = false;
    await baseAppClient.post(GET_PRESCRIPTIONS_ALL_ORDERS, onSuccess: (dynamic response, int statusCode) {
      response['PatientER_GetPatientAllPresOrdersList'].forEach((prescriptionsOrder) {
        // prescriptionsOrderList.add(PrescriptionsOrder.fromJson(prescriptionsOrder));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);
  }

  Future getPrescriptionsInfoRC(int orderID, dynamic patientID) async {
    prescriptionsOrderListRC.clear();
    Map<String, dynamic> body = Map();
    body['ID'] = orderID;
    await baseAppClient.post(GET_ALL_PRESCRIPTION_INFO_RC + "?PatientId=" + patientID.toString(), isRCService: true, onSuccess: (dynamic response, int statusCode) {
      response['response']['report'].forEach((prescriptionsOrder) {
        prescriptionsOrderListRC.add(PrescriptionInfoRCModel.fromJson(prescriptionsOrder));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);
  }

  Future getPrescriptionsOrdersRC() async {
    prescriptionsOrderList.clear();
    Map<String, dynamic> body = Map();
    // body['isDentalAllowedBackend'] = false;
    await baseAppClient.post(GET_ALL_PRESCRIPTION_ORDERS_RC, isRCService: true, onSuccess: (dynamic response, int statusCode) {
      response['response'].forEach((prescriptionsOrder) {
        prescriptionsOrderList.add(GetCMCAllOrdersResponseModel.fromJson(prescriptionsOrder));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);
  }

  RequestPrescriptionReport _requestPrescriptionReport = RequestPrescriptionReport(appointmentNo: 0, isDentalAllowedBackend: false);
  List<PrescriptionReport> prescriptionReportList = List();

  Future getPrescriptionReport({Prescriptions prescriptions}) async {
    hasError = false;
    if (prescriptions.isInOutPatient == false) {
      _requestPrescriptionReport.dischargeNo = prescriptions.dischargeNo;
    } else {
      _requestPrescriptionReport.dischargeNo = 0;
    }
    _requestPrescriptionReport.projectID = prescriptions.projectID;
    _requestPrescriptionReport.clinicID = prescriptions.clinicID;
    _requestPrescriptionReport.setupID = prescriptions.setupID;
    _requestPrescriptionReport.episodeID = prescriptions.episodeID;
    _requestPrescriptionReport.appointmentNo = prescriptions.appointmentNo;

    await baseAppClient.post(prescriptions.isInOutPatient ? GET_PRESCRIPTION_REPORT_ENH : GET_PRESCRIPTION_REPORT, onSuccess: (dynamic response, int statusCode) {
      prescriptionReportList.clear();
      prescriptionReportEnhList.clear();
      isMedDeliveryAllowed = response['IsHomeMedicineDeliverySupported'];
      if (prescriptions.isInOutPatient) {
        response['ListPRM'].forEach((prescriptions) {
          prescriptionReportList.add(PrescriptionReport.fromJson(prescriptions));
          prescriptionReportEnhList.add(PrescriptionReportEnh.fromJson(prescriptions));
        });
      } else {
        prescriptionReportListINP.clear();
        response['INP_GetPrescriptionReport_List'].forEach((prescriptions) {
          prescriptionReportListINP.add(PrescriptionReportINP.fromJson(prescriptions));
        });
      }
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: _requestPrescriptionReport.toJson());
  }

  RequestSendPrescriptionEmail _requestSendPrescriptionEmail = RequestSendPrescriptionEmail(
    isDentalAllowedBackend: false,
  );

  Future sendPrescriptionEmail(String appointmentDate, int patientID, String clinicName, String doctorName, int doctorID, int projectID) async {
    _requestSendPrescriptionEmail.listPrescriptions = prescriptionReportList;
    _requestSendPrescriptionEmail.appointmentDate = appointmentDate;
    _requestSendPrescriptionEmail.patientID = patientID;
    _requestSendPrescriptionEmail.clinicName = clinicName;
    _requestSendPrescriptionEmail.doctorName = doctorName;
    _requestSendPrescriptionEmail.projectID = projectID;
    _requestSendPrescriptionEmail.to = user.emailAddress;
    _requestSendPrescriptionEmail.dateofBirth = user.dateofBirth;
    _requestSendPrescriptionEmail.patientIditificationNum = user.patientIdentificationNo;
    _requestSendPrescriptionEmail.patientMobileNumber = user.mobileNumber;
    _requestSendPrescriptionEmail.doctorID = doctorID;
    _requestSendPrescriptionEmail.patientName = user.firstName + " " + user.lastName;
    _requestSendPrescriptionEmail.setupID = user.setupID;
    _requestSendPrescriptionEmail.to = user.emailAddress;
    hasError = false;
    await baseAppClient.post(SEND_PRESCRIPTION_EMAIL, onSuccess: (response, statusCode) {}, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: _requestSendPrescriptionEmail.toJson());
  }

  RequestGetListPharmacyForPrescriptions requestGetListPharmacyForPrescriptions = RequestGetListPharmacyForPrescriptions(
    latitude: 0,
    longitude: 0,
    isDentalAllowedBackend: false,
  );
  List<PharmacyPrescriptions> pharmacyPrescriptionsList = List();

  Future getListPharmacyForPrescriptions({int itemId}) async {
    hasError = false;
    requestGetListPharmacyForPrescriptions.itemID = itemId;

    requestGetListPharmacyForPrescriptions.latitude = await sharedPref.getDouble(USER_LAT);
    requestGetListPharmacyForPrescriptions.longitude = await sharedPref.getDouble(USER_LONG);

    // requestGetListPharmacyForPrescriptions.latitude = 24.709863;
    // requestGetListPharmacyForPrescriptions.longitude = 46.668348;

    pharmacyPrescriptionsList.clear();
    await baseAppClient.post(GET_PHARMACY_LIST, onSuccess: (dynamic response, int statusCode) {
      pharmacyPrescriptionsList.clear();
      response['PharmList'].forEach((prescriptions) {
        pharmacyPrescriptionsList.add(PharmacyPrescriptions.fromJson(prescriptions));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: requestGetListPharmacyForPrescriptions.toJson());
  }

  RequestPrescriptionReportEnh _requestPrescriptionReportEnh = RequestPrescriptionReportEnh(
    isDentalAllowedBackend: false,
  );

  List<PrescriptionReportEnh> prescriptionReportEnhList = List();

  Future getPrescriptionReportEnh({PrescriptionsOrder prescriptionsOrder}) async {
    bool isInPatient = false;
    prescriptionsList.forEach((element) {
      if (prescriptionsOrder.appointmentNo == "0") {
        if (element.dischargeNo == int.parse(prescriptionsOrder.dischargeID)) {
          _requestPrescriptionReportEnh.appointmentNo = element.appointmentNo;
          _requestPrescriptionReportEnh.clinicID = element.clinicID;
          _requestPrescriptionReportEnh.projectID = element.projectID;
          _requestPrescriptionReportEnh.episodeID = element.episodeID;
          _requestPrescriptionReportEnh.setupID = element.setupID;
          _requestPrescriptionReportEnh.dischargeNo = element.dischargeNo;
          isInPatient = element.isInOutPatient;
        }
      } else {
        if (int.parse(prescriptionsOrder.appointmentNo) == element.appointmentNo) {
          _requestPrescriptionReportEnh.appointmentNo = element.appointmentNo;
          _requestPrescriptionReportEnh.clinicID = element.clinicID;
          _requestPrescriptionReportEnh.projectID = element.projectID;
          _requestPrescriptionReportEnh.episodeID = element.episodeID;
          _requestPrescriptionReportEnh.setupID = element.setupID;
          _requestPrescriptionReportEnh.dischargeNo = element.dischargeNo;
          isInPatient = element.isInOutPatient;
        }
      }
    });

    hasError = false;

    await baseAppClient.post(isInPatient ? GET_PRESCRIPTION_REPORT_ENH : GET_PRESCRIPTION_REPORT, onSuccess: (dynamic response, int statusCode) {
      prescriptionReportEnhList.clear();

      if (isInPatient) {
        response['ListPRM'].forEach((prescriptions) {
          prescriptionReportEnhList.add(PrescriptionReportEnh.fromJson(prescriptions));
        });
      } else {
        response['INP_GetPrescriptionReport_List'].forEach((prescriptions) {
          PrescriptionReportEnh reportEnh = PrescriptionReportEnh.fromJson(prescriptions);
          reportEnh.itemDescription = prescriptions['ItemDescriptionN'];
          prescriptionReportEnhList.add(reportEnh);
        });
      }
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: _requestPrescriptionReportEnh.toJson());
  }

  Future updatePressOrderRC({@required int presOrderID}) async {
    hasError = false;
    Map<String, dynamic> body = Map();
    body['Id'] = presOrderID;
    body['StatusId'] = 6;
    body['ClickButton'] = 14;
    await baseAppClient.post(UPDATE_PRESCRIPTION_ORDER_RC, onSuccess: (dynamic response, int statusCode) {}, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);
  }

  Future updatePressOrder({@required int presOrderID}) async {
    hasError = false;
    Map<String, dynamic> body = Map();
    body['PresOrderID'] = presOrderID;
    body['EditedBy'] = user.patientID;
    body['RejectionReason'] = '';
    body['PresOrderStatus'] = 4;
    body['isDentalAllowedBackend'] = false;
    await baseAppClient.post(UPDATE_PRESS_ORDER, onSuccess: (dynamic response, int statusCode) {}, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);
  }
}
