import 'package:doctor_app_flutter/config/config.dart';
import 'package:doctor_app_flutter/core/service/base/base_service.dart';
import 'package:doctor_app_flutter/lookups/hospital_lookup.dart';
import 'package:doctor_app_flutter/models/doctor/doctor_profile_model.dart';
import 'package:doctor_app_flutter/models/patient/PatientArrivalEntity.dart';
import 'package:doctor_app_flutter/models/patient/get_clinic_by_project_id_request.dart';
import 'package:doctor_app_flutter/models/patient/get_doctor_by_clinic_id_request.dart';
import 'package:doctor_app_flutter/models/patient/my_referral/PendingReferral.dart';
import 'package:doctor_app_flutter/models/patient/my_referral/my_referred_patient_model.dart';
import 'package:doctor_app_flutter/models/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/models/patient/request_my_referral_patient_model.dart';

import 'base/lookup-service.dart';

class PatientReferralService extends LookupService {
  List<dynamic> projectsList = [];
  List<dynamic> clinicsList = [];
  List<dynamic> doctorsList = [];
  List<MyReferredPatientModel> listMyReferredPatientModel = [];
  List<PendingReferral> pendingReferralList = [];
  List<PendingReferral> patientReferralList = [];
  String setupID = "0";

  Future getProjectsList() async {
    hasError = false;
    const url = GET_PROJECTS;
    var info = {
      "LanguageID": 1,
      "stamp": "2020-02-26T13:51:44.111Z",
      "IPAdress": "11.11.11.11",
      "VersionID": 1.2,
      "Channel": 9,
      "TokenID": "",
      "SessionID": "i1UJwCTSqt",
      "IsLoginForDoctorApp": true,
      // "MemberID": memberID
    };
    dynamic localRes;

    await baseAppClient.post(url, onSuccess: (response, statusCode) async {
      if (response['MessageStatus'] == 1) {
        projectsList = response['ProjectInfo'];
      } else {
        // handel error
        projectsList = ListProject;
      }
    }, onFailure: (String error, int statusCode) {
      projectsList = ListProject;
    }, body: info);
  }

  Future getReferralFacilities() async {
    hasError = false;

    Map<String, dynamic> body = Map();
    body['isSameBranch'] = false;

    await baseAppClient.post(GET_REFERRAL_FACILITIES, onSuccess: (response, statusCode) async {
      projectsList = response['ProjectInfo'];
    }, onFailure: (String error, int statusCode) {
      hasError = true;
      super.error = error;
    }, body: body);
  }

  Future getProjectInfo(int projectId) async {
    Map<String, dynamic> body = Map();
    body['ProjectID'] = projectId;

    await baseAppClient.post(
      PROJECT_GET_INFO,
      onSuccess: (dynamic response, int statusCode) {
        setupID = response['ProjectInfo'][0]['facilityGroupId'];
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: body,
    );
  }

  Future getClinicsList(int projectId) async {
    hasError = false;
    ClinicByProjectIdRequest _clinicByProjectIdRequest =
        ClinicByProjectIdRequest();
    _clinicByProjectIdRequest.projectID = projectId;

    await baseAppClient.post(
      PATIENT_GET_CLINIC_BY_PROJECT_URL,
      onSuccess: (dynamic response, int statusCode) {
        clinicsList = [];
        clinicsList = response['List_Clinic_All'];
        print(response['List_Clinic_All']);
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: _clinicByProjectIdRequest.toJson(),
    );
  }

  Future getDoctorsList(String clinicId) async {
    hasError = false;
    DoctorsByClinicIdRequest _doctorsByClinicIdRequest =
        DoctorsByClinicIdRequest();

    _doctorsByClinicIdRequest.clinicID = clinicId;
    await baseAppClient.post(
      PATIENT_GET_DOCTOR_BY_CLINIC_URL,
      onSuccess: (dynamic response, int statusCode) {
        doctorsList = [];
        doctorsList = response['List_Doctors_All'];
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: _doctorsByClinicIdRequest.toJson(),
    );
  }

  Future getMyReferredPatient() async {
    hasError = false;
    RequestMyReferralPatientModel _requestMyReferralPatient =
        RequestMyReferralPatientModel();
    DoctorProfileModel doctorProfile = await getDoctorProfile();

    await baseAppClient.post(
      GET_MY_REFERRED_PATIENT,
      onSuccess: (dynamic response, int statusCode) {
        listMyReferredPatientModel.clear();

        response['List_MyReferredPatient'].forEach((v) {
          MyReferredPatientModel item = MyReferredPatientModel.fromJson(v);
          if (doctorProfile != null) {
            item.isReferralDoctorSameBranch =
                doctorProfile.projectID == item.projectId;
          } else {
            item.isReferralDoctorSameBranch = false;
          }
          listMyReferredPatientModel.add(item);
        });
        // print(response['List_MyReferredPatient']);
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: _requestMyReferralPatient.toJson(),
    );
  }

  Future getPendingReferralList() async {
    hasError = false;
    DoctorProfileModel doctorProfile = await getDoctorProfile();
    Map<String, dynamic> body = Map();
    body['ClinicID'] = 0;
    body['DoctorID'] = doctorProfile.doctorID;

    await baseAppClient.post(
      GET_PENDING_REFERRAL_PATIENT,
      onSuccess: (dynamic response, int statusCode) {
        pendingReferralList.clear();

        response['PendingReferralList'].forEach((v) {
          PendingReferral item = PendingReferral.fromJson(v);
          item.isReferralDoctorSameBranch =
              item.targetProjectId == item.sourceProjectId;
          pendingReferralList.add(item);
        });
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: body,
    );
  }

  Future getPatientReferral(PatiantInformtion patient) async {
    hasError = false;
    Map<String, dynamic> body = Map();
    body['PatientMRN'] = patient.patientMRN;
    body['AppointmentNo'] = patient.appointmentNo;

    await baseAppClient.post(
      GET_PATIENT_REFERRAL,
      onSuccess: (dynamic response, int statusCode) {
        patientReferralList.clear();

        response['ReferralList']['entityList'].forEach((v) {
          PendingReferral item = PendingReferral.fromJson(v);
          item.isReferralDoctorSameBranch =
              item.targetProjectId == item.sourceProjectId;
          patientReferralList.add(item);
        });
      },
      onFailure: (String error, int statusCode) {
        patientReferralList.clear();
        hasError = true;
        super.error = error;
      },
      body: body,
    );
  }

  Future responseReferral(PendingReferral pendingReferral, bool isAccepted) async {
    hasError = false;
    DoctorProfileModel doctorProfile = await getDoctorProfile();

    Map<String, dynamic> body = Map();
    body['PatientMRN'] = pendingReferral.patientID;
    body['AppointmentNo'] = pendingReferral.targetAppointmentNo;
    body['SetupID'] = pendingReferral.targetSetupID;
    body['ProjectID'] = pendingReferral.targetProjectId;
    body['IsAccepted'] = isAccepted;
    body['PatientName'] = pendingReferral.patientName;
    body['ReferralResponse'] = pendingReferral.remarksFromSource;
    body['DoctorName'] = doctorProfile.doctorName;

    await baseAppClient.post(
      RESPONSE_PENDING_REFERRAL_PATIENT,
      onSuccess: (dynamic response, int statusCode) {
        print(response);
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: body,
    );
  }

  Future makeReferral(
      PatiantInformtion patient,
      String isoStringDate,
      int projectID,
      int clinicID,
      int doctorID,
      String remarks) async {
    hasError = false;
    Map<String, dynamic> body = Map();

    List<dynamic> physiotheraphyGoalsList = [];
    listOfPhysiotherapyGoals.forEach((element) {
      physiotheraphyGoalsList
          .add({"goalId": element.id, "remarks": element.remarks});
    });

    body['PatientMRN'] = patient.patientMRN;
    body['AppointmentNo'] = patient.appointmentNo;
    body['SetupID'] = setupID;
    body['appointmentDate'] = isoStringDate;
    body['SlotStart'] = isoStringDate;
    body['SlotEnd'] = isoStringDate;
    body['Remarks'] = remarks;
    body['ProjectID'] = projectID;
    body['ClinicID'] = clinicID;
    body['DoctorID'] = doctorID;
    body['noOfSessions'] = 1;
    body['physiotheraphyGoalsList'] = physiotheraphyGoalsList;

    await baseAppClient.post(
      CREATE_REFERRAL_PATIENT,
      onSuccess: (dynamic response, int statusCode) {
        print(response.toString());
        print("create referral status code = ${statusCode}");
      },
      onFailure: (String error, int statusCode) {
        hasError = true;
        super.error = error;
      },
      body: body,
    );
  }
}
