import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/model/Prescription_model.dart';
import 'package:doctor_app_flutter/core/model/calculate_box_request_model.dart';
import 'package:doctor_app_flutter/core/model/get_medication_response_model.dart';
import 'package:doctor_app_flutter/core/model/item_by_medicine_request_model.dart';
import 'package:doctor_app_flutter/core/model/medical_file_model.dart';
import 'package:doctor_app_flutter/core/model/prescription_req_model.dart';
import 'package:doctor_app_flutter/core/model/post_prescrition_req_model.dart';
import 'package:doctor_app_flutter/core/model/search_drug_model.dart';
import 'package:doctor_app_flutter/core/model/search_drug_request_model.dart';
import 'package:doctor_app_flutter/core/service/base/base_service.dart';
import 'package:doctor_app_flutter/core/service/base/lookup-service.dart';
import 'package:doctor_app_flutter/models/SOAP/GetAllergiesResModel.dart';
import 'package:doctor_app_flutter/models/SOAP/GetAssessmentReqModel.dart';
import 'package:doctor_app_flutter/models/SOAP/GetAssessmentResModel.dart';
import 'package:doctor_app_flutter/models/SOAP/master_key_model.dart';
import 'package:doctor_app_flutter/models/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/models/patient/vital_sign/patient-vital-sign-data.dart';
import 'package:doctor_app_flutter/util/date-utils.dart';

class PrescriptionService extends LookupService {
  List<PrescriptionModel> _prescriptionList = List();
  List<PrescriptionModel> get prescriptionList => _prescriptionList;
  List<SearchDrugModel> _drugsList = List();
  List<SearchDrugModel> get drugsList => _drugsList;
  List<dynamic> doctorsList = [];
  List<GetMedicationResponseModel> allMedicationList = [];
  List<dynamic> specialityList = [];
  List<dynamic> drugToDrug = [];
  List<dynamic> get drugToDrugList => drugToDrug;
  List<dynamic> itemMedicineList = [];
  List<dynamic> itemMedicineListRoute = [];
  List<dynamic> itemMedicineListUnit = [];
  dynamic boxQuantity;

  PrescriptionReqModel _prescriptionReqModel = PrescriptionReqModel();
  ItemByMedicineRequestModel _itemByMedicineRequestModel =
      ItemByMedicineRequestModel();
  SearchDrugRequestModel _drugRequestModel = SearchDrugRequestModel(
    //search: ["Acetaminophen"],
    search: ["Amoxicillin"],
  );

  CalculateBoxQuantityRequestModel _boxQuantityRequestModel =
      CalculateBoxQuantityRequestModel();

  PostPrescriptionReqModel _postPrescriptionReqModel =
      PostPrescriptionReqModel();

  Future getItem({int itemID}) async {
    _itemByMedicineRequestModel =
        ItemByMedicineRequestModel(medicineCode: itemID);

    hasError = false;

    await baseAppClient.post(GET_ITEM_BY_MEDICINE,
        onSuccess: (dynamic response, int statusCode) {
      itemMedicineList = [];
      itemMedicineList = response['listItemByMedicineCode']['frequencies'];
      itemMedicineListRoute = response['listItemByMedicineCode']['routes'];
      itemMedicineListUnit = response['listItemByMedicineCode']['strengths'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: _itemByMedicineRequestModel.toJson());
  }

  Future getPatientAssessment(
      GetAssessmentReqModel getAssessmentReqModel) async {
    hasError = false;
    await baseAppClient.post(GET_ASSESSMENT,
        onSuccess: (dynamic response, int statusCode) {
      print("Success");
      patientAssessmentList.clear();
      response['AssessmentList']['entityList'].forEach((v) {
        patientAssessmentList.add(GetAssessmentResModel.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: getAssessmentReqModel.toJson());
  }

  Future getPrescription({int mrn}) async {
    _prescriptionReqModel = PrescriptionReqModel(
      patientMRN: mrn,
    );
    hasError = false;
    _prescriptionList.clear();
    await baseAppClient.post(GET_PRESCRIPTION_LIST,
        onSuccess: (dynamic response, int statusCode) {
      _prescriptionList
          .add(PrescriptionModel.fromJson(response['PrescriptionList']));
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: _prescriptionReqModel.toJson());
  }

  Future getDrugs({String drugName}) async {
    _drugRequestModel = SearchDrugRequestModel(search: [drugName]);

    hasError = false;

    await baseAppClient.post(SEARCH_DRUG,
        onSuccess: (dynamic response, int statusCode) {
      doctorsList = [];
      doctorsList = response['MedicationList']['entityList'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: _drugRequestModel.toJson());
  }

  Future getMedicationList() async {
    hasError = false;
    _drugRequestModel.search = [""];
    await baseAppClient.post(SEARCH_DRUG,
        onSuccess: (dynamic response, int statusCode) {
      allMedicationList = [];
      response['MedicationList']['entityList'].forEach((v) {
        allMedicationList.add(GetMedicationResponseModel.fromJson(v));
      });
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: _drugRequestModel.toJson());
  }

  Future postPrescription(
      PostPrescriptionReqModel postProcedureReqModel) async {
    hasError = false;
    //_prescriptionList.clear();
    await baseAppClient.post(
      POST_PRESCRIPTION_LIST,
      onSuccess: (dynamic response, int statusCode) {
        print("Success");
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: postProcedureReqModel.toJson(),
    );
  }

  Future updatePrescription(
      PostPrescriptionReqModel updatePrescriptionReqModel) async {
    hasError = false;
    //_prescriptionList.clear();
    await baseAppClient.post(
      UPDATE_PRESCRIPTION,
      onSuccess: (dynamic response, int statusCode) {
        print("Accepted");
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: updatePrescriptionReqModel.toJson(),
    );
  }

  Future getDrugToDrug(
      VitalSignData vital,
      List<GetAssessmentResModel> lstAssessments,
      List<GetAllergiesResModel> allergy,
      PatiantInformtion patient,
      List<dynamic> prescription) async {
    // Map<String, dynamic> request = {
    //   "Prescription": {
    //     "objPatientInfo": {"Gender": "Male", "Age": "21/06/1967"},
    //     "objVitalSign": {"Height": "180", "Weight": "37"},
    //     "objPrescriptionItems": [
    //       {
    //         "DrugId": "83-20-00-30-20-03-03",
    //         "DrugName": "WARFARIN 1 MG TAB 28'S (N)",
    //         "Dose": "1",
    //         "DoseType": "04",
    //         "Unit": "actuation(s)",
    //         "FrequencyType": "1/3/Day",
    //         "Duration": "3/Day",
    //         "IsScreen": "true"
    //       },
    //       {
    //         "DrugId": "64-20-00-10-00-03-15",
    //         "DrugName": "PANADOL 500 MG TAB 24'S(DIS)",
    //         "Dose": "1",
    //         "DoseType": "04",
    //         "Unit": "MG",
    //         "FrequencyType": "3/1/Day",
    //         "Duration": "4/Day",
    //         "RouteID": "24",
    //         "IsScreen": "true"
    //       }
    //     ],
    //     "objAllergies": {
    //       "Allergy": {
    //         "objProperties": {"Id": "26", "Name": "phenoxymethylpenicillin"}
    //       }
    //     },
    //     "objDiagnosis": {
    //       "Diagnosis": {
    //         "objProperties": {"Id": "A01.1", "Name": "Paratyphoid fever A"}
    //       }
    //     },
    //     "IsDoctor": "false",
    //     "IsPharmacist": "false"
    //   },
    //   "IPAdress": "10.10.10.10",
    //   "Channel": 9,
    //   "LanguageID": 2,
    //   "VersionID": 5.3,
    //   "SessionID": "BlUSkYymTt",
    //   "IsLoginForDoctorApp": true,
    //   "PatientOutSA": 0,
    //   "TokenID": "@dm!n",
    //   "OutSA": true
    // };
    Map<String, dynamic> request = {
      "Prescription": {
        "objPatientInfo": {
          "Gender": patient.gender == 1 ? 'Male' : 'Female',
          "Age": DateUtils.convertDateFromServerFormat(
              patient.dateofBirth, 'dd/MM/yyyy')
        },
        "objVitalSign": {"Height": vital?.heightCm, "Weight": vital?.weightKg},
        "objPrescriptionItems": prescription,
        "objAllergies": getAllergiesObj(allergy),
        "objDiagnosis": getDiagnosisObj(lstAssessments),
        "IsDoctor": "false",
        "IsPharmacist": "false"
      }
    };

    hasError = false;
    await baseAppClient.post(DRUG_TO_DRUG,
        onSuccess: (dynamic response, int statusCode) {
      drugToDrug = [];
      drugToDrug =
          response['DrugToDrugResponse']['objPrescriptionCheckerResult'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: request);
  }

  Future calculateBoxQuantity(
      {int freq, int duration, int itemCode, double strength}) async {
    _boxQuantityRequestModel = CalculateBoxQuantityRequestModel(
        frequency: freq,
        duration: duration,
        itemCode: itemCode,
        strength: strength);

    hasError = false;

    await baseAppClient.post(GET_BOX_QUANTITY,
        onSuccess: (dynamic response, int statusCode) {
      boxQuantity = response['BoxQuantity'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: _boxQuantityRequestModel.toJson());
  }

  getAllergiesObj(List<GetAllergiesResModel> allergies) {
    var allergiesObj = [];
    allergies.forEach((element) {
      allergiesObj.add({
        "objProperties": {
          'Id': element.allergyDiseaseId,
          'Name': element.allergyDiseaseName
        }
      });
    });
    return allergiesObj;
  }

  getDiagnosisObj(List<GetAssessmentResModel> lstAssessments) {
    var lstAssessmentsObj = [];
    lstAssessments.forEach((element) {
      lstAssessmentsObj.add({
        "objProperties": {'Id': element.icdCode10ID, 'Name': element.asciiDesc}
      });
    });
    return lstAssessmentsObj;
  }
}
