namespace Hims.Infrastructure.Services
{
    using System;
    using System.Threading.Tasks;
    using Dapper;
    using Domain.Configurations;
    using Domain.Entities;
    using Domain.Repositories.UnitOfWork;
    using Domain.Services;
    using Shared.EntityModels;
    using Shared.Library;
    using Shared.Library.Enums;
    using Shared.UserModels;
    using Hims.Shared.Library.Helpers;
    using System.Collections.Generic;
    using System.Collections;
    using Newtonsoft.Json;

    /// <inheritdoc />
    public class GynEncounterServices : IGynEncounterService
    {
        /// <summary>
        /// The unit of work.
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <summary>
        /// The amazon s3 configuration.
        /// </summary>
        private readonly IAmazonS3Configuration amazonS3Configuration;

        /// <summary>
        /// The timeline service.
        /// </summary>
        private readonly ITimelineService timelineService;
        private readonly IEncounterService encounterServices;
        private readonly IAppointmentService appointmentsServices;
        /// <inheritdoc cref="IGynEncounterService"/>
        public GynEncounterServices(ITimelineService timelineService, IUnitOfWork unitOfWork, IAmazonS3Configuration amazonS3Configuration, IEncounterService encounterServices,  IAppointmentService appointmentsServices)
        {
            this.unitOfWork = unitOfWork;
            this.amazonS3Configuration = amazonS3Configuration;
            this.timelineService = timelineService;
            this.encounterServices = encounterServices;
            this.appointmentsServices= appointmentsServices;

        }

        /// <inheritdoc />
        public async Task<GynEncounterModel> FindAsync(int appointmentId, bool isAdmission)
        {
            var result = new GynEncounterModel();
            if (appointmentId != 0)
            {
                var query = "";
                int cnt = 0;
                var addRecords = new Admission();
                var appRecord = new Appointment();
                if (isAdmission)
                {
                    addRecords = this.unitOfWork.Admission.Find(s => s.AdmissionId == appointmentId);
                    cnt = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(*) FROM ""GynEncounter"" WHERE ""AdmissionId"" = {addRecords.AdmissionId}");
                }
                else
                {
                    appRecord = this.unitOfWork.Appointments.Find(s => s.AppointmentId == appointmentId);
                    if (appRecord != null)
                    {
                        cnt = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(*) FROM ""GynEncounter"" WHERE ""AppointmentId"" = {appRecord.AppointmentId}");
                    }
                }
                if (cnt == 0)
                {
                    var ancRecords = new GYNCardGeneration();
                    var AptCnt = 0;
                    var ancCardQuerry = isAdmission ? $@"select * from ""GYNCardGeneration"" where ""PatientId""={addRecords.PatientId} and ""Active""=true order by 1 desc " :
                        $@"select * from ""GYNCardGeneration"" where ""PatientId""={appRecord.PatientId} and ""Active""=true order by 1 desc ";
                    ancRecords = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<GYNCardGeneration>(ancCardQuerry);
                    if (isAdmission)
                    {
                        query = $@"select * from ""GynEncounter"" where ""PatientId""={addRecords.PatientId} order by 1 desc ";
                        AptCnt = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(*) FROM ""GynEncounter"" WHERE ""PatientId"" = {addRecords.PatientId}");
                    }
                    else
                    {
                        if (appRecord != null && appRecord.PatientId != 0)
                        {
                            // query = $@"select * from ""GynEncounter"" where ""PatientId""={appRecord.PatientId} order by 1 desc ";

                            query =
                               $@"select gyn.""GynEncounterId"",gyn.""BirthControl"", 
                            gyn. ""GynHistory"", gyn.""GynLabs"", gyn.""GynUltraSound"", gyn.""MeasureCommonData"",
							gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""GynaecOrders"",gyn.""GyneacCard"",gyn.""GyneacCard"",gyn.""GynaecOrders"",gyn.""GyneacSurgery"",
            gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""Procedure"",gyn.""GyneacPartner"",gyn.""GyneacAdmissionSheet, gyn.""Reminder"",
                gyn.""ProformaForOasi"",gyn.""Colposcopic"" ,gyn.""Ectopic"",gyn.""Measure"",gyn.""RefferalOrder"",gyn.""Surgeries"",gyn.""Allergies"",gyn.""Surgeries"",
gyn.""Procedure"",gyn.""GyneacPartner"",	gyn.""GyneacDiscargeSummary"",	gyn. ""ReferralForm"",gyn.""SpeacialFeature"",gyn.""MeasureCommonData"",gyn."",""OutSideTests"",
   
  ""OrderPrescription"", CE.""BirthHistory"", CE.""FamilyHistory"", CE.""ProblemList"",CE.""Surgeries"" ,""CE.""GPLA"" from ""GynEncounter"" gyn
left join ""CommonEncounter"" CE on CE.""PatientId""=gyn.""PatientId""
 where gyn.""PatientId"" ={ appRecord.PatientId}
                            order by 1 desc ";


                            AptCnt = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(*) FROM ""GynEncounter"" WHERE ""PatientId"" = {appRecord.PatientId}");

                        }
                    }
                    if (AptCnt > 0 && ancRecords != null)
                    {
                        await AddExistedAsync(appointmentId, isAdmission ? addRecords.PatientId : appRecord.PatientId, isAdmission);
                        query = isAdmission ? $@"select gyn.""GynEncounterId"",gyn.""BirthControl"", gyn.""AppointmentId"",gyn.""PatientId"",gyn.""AdmissionId"",gyn.""CreatedDate"",gyn.""CreatedBy"",
                            gyn. ""GynHistory"", gyn.""GynLabs"", gyn.""GynUltraSound"",  gyn.""MeasureCommonData"",
							gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""GynaecOrders"",gyn.""GyneacCard"",gyn.""GyneacCard"",gyn.""GynaecOrders"",
gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""Procedure"",gyn.""GyneacPartner"",gyn.""GyneacSurgery"",gyn.""GyneacAdmissionSheet"", gyn.""Reminder"",
gyn.""ProformaForOasi"",gyn.""Colposcopic"" ,gyn.""Ectopic"",gyn.""Measure"",gyn.""RefferalOrder"",gyn.""Surgeries"",gyn.""Allergies"",gyn.""Surgeries"",gyn.""Procedure"",gyn.""GyneacPartner"",
""OrderPrescription"",	gyn.""GyneacDiscargeSummary"",gyn. ""ReferralForm"",gyn.""SpeacialFeature"",gyn.""MeasureCommonData"",  gyn.""OutSideTests"",
   CE.""BirthHistory"", CE.""FamilyHistory"", CE.""ProblemList"",CE.""Surgeries"" from ""GynEncounter"" gyn
left join ""CommonEncounter"" CE on CE.""PatientId""=gyn.""PatientId""
where gyn.""PatientId""={addRecords.PatientId}  and  gyn.""AdmissionId""={addRecords.AdmissionId} order by 1 desc" :
$@"select gyn.""GynEncounterId"",gyn.""BirthControl"",  gyn.""AppointmentId"",gyn.""PatientId"",gyn.""AdmissionId"",gyn.""CreatedDate"",gyn.""CreatedBy"",
                            gyn. ""GynHistory"", gyn.""GynLabs"", gyn.""GynUltraSound"", gyn.""GyneacSurgery"",gyn.""GyneacAdmissionSheet"",
							gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""GynaecOrders"",gyn.""GyneacCard"",gyn.""GyneacCard"",gyn.""GynaecOrders"",
gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""Procedure"",gyn.""GyneacPartner"",gyn.""GyneacDiscargeSummary"",gyn. ""ReferralForm"",gyn.""SpeacialFeature"",
gyn.""ProformaForOasi"",gyn.""Colposcopic"" ,gyn.""Ectopic"",gyn.""Measure"",gyn.""RefferalOrder"",gyn.""Surgeries"",gyn.""Allergies"",gyn.""Surgeries"",gyn.""Procedure"",gyn.""GyneacPartner"",
""OrderPrescription"",	gyn.""MeasureCommonData"",   gyn.""OutSideTests"", gyn.""Reminder"",
   CE.""BirthHistory"", CE.""FamilyHistory"", CE.""ProblemList"",CE.""Surgeries""  ,CE.""GPLA"" from ""GynEncounter"" gyn
left join ""CommonEncounter"" CE on CE.""PatientId""=gyn.""PatientId""
where gyn.""PatientId""={appRecord.PatientId}  and  gyn.""AppointmentId""={appRecord.AppointmentId} order by  CE.""CreatedDate"" desc";
                        result = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<GynEncounterModel>(query);
                    }
                    // result.AppointmentId = isAdmission ? addRecords.AdmissionId : appRecord.AppointmentId;
                }
                else
                {

                    query = isAdmission ? $@"select gyn.""GynEncounterId"",gyn.""BirthControl"", gyn.""AppointmentId"",gyn.""PatientId"",gyn.""AdmissionId"",gyn.""CreatedDate"",gyn.""CreatedBy"",
                            gyn. ""GynHistory"", gyn.""GynLabs"", gyn.""GynUltraSound"",  gyn.""MeasureCommonData"",
							gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""GynaecOrders"",gyn.""GyneacCard"",gyn.""GyneacCard"",gyn.""GynaecOrders"",
gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""Procedure"",gyn.""GyneacPartner"",gyn.""GyneacSurgery"",gyn.""GyneacAdmissionSheet"",
gyn.""ProformaForOasi"",gyn.""Colposcopic"" ,gyn.""Ectopic"",gyn.""Measure"",gyn.""RefferalOrder"",gyn.""Surgeries"",gyn.""Allergies"",gyn.""Surgeries"",gyn.""Procedure"",gyn.""GyneacPartner"",
""OrderPrescription"",	gyn.""GyneacDiscargeSummary"",gyn. ""ReferralForm"",gyn.""SpeacialFeature"",gyn.""MeasureCommonData"",  gyn.""OutSideTests"", gyn.""Reminder""
   CE.""BirthHistory"", CE.""FamilyHistory"", CE.""ProblemList"",CE.""Surgeries"" from ""GynEncounter"" gyn
left join ""CommonEncounter"" CE on CE.""PatientId""=gyn.""PatientId""
where gyn.""PatientId""={addRecords.PatientId}  and  gyn.""AdmissionId""={addRecords.AdmissionId} order by 1 desc" :
$@"select gyn.""GynEncounterId"",gyn.""BirthControl"",  gyn.""AppointmentId"",gyn.""PatientId"",gyn.""AdmissionId"",gyn.""CreatedDate"",gyn.""CreatedBy"",
                            gyn. ""GynHistory"", gyn.""GynLabs"", gyn.""GynUltraSound"", gyn.""GyneacSurgery"",gyn.""GyneacAdmissionSheet"",
							gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""GynaecOrders"",gyn.""GyneacCard"",gyn.""GyneacCard"",gyn.""GynaecOrders"",
gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""Procedure"",gyn.""GyneacPartner"",gyn.""GyneacDiscargeSummary"",gyn. ""ReferralForm"",gyn.""SpeacialFeature"",
gyn.""ProformaForOasi"",gyn.""Colposcopic"" ,gyn.""Ectopic"",gyn.""Measure"",gyn.""RefferalOrder"",gyn.""Surgeries"",gyn.""Allergies"",gyn.""Surgeries"",gyn.""Procedure"",gyn.""GyneacPartner"",
""OrderPrescription"",	gyn.""MeasureCommonData"",   gyn.""OutSideTests"", gyn.""Reminder"",
   CE.""BirthHistory"", CE.""FamilyHistory"", CE.""ProblemList"",CE.""Surgeries"" ,CE.""GPLA"" from ""GynEncounter"" gyn
left join ""CommonEncounter"" CE on CE.""PatientId""=gyn.""PatientId""
where gyn.""PatientId""={appRecord.PatientId}  and  gyn.""AppointmentId""={appRecord.AppointmentId}  order by  CE.""CreatedDate"" desc";

                    result = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<GynEncounterModel>(query);
                }
                // result = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<GynEncounterModel>(query);

            }
            return result;
        }
        public async Task<CommonResponse> AddExistedAsync(int appointmentId, int patientId, bool isAdmission)
        {
            var commonResponse = new CommonResponse { Status = 1 };
            var res = new GynEncounterModel();
            var admissionRecords = new Admission();
            var appointmentRecords = new Appointment();
            var query = $@"select * from ""GynEncounter"" where ""PatientId""={patientId} order by 1 desc ";
            res = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<GynEncounterModel>(query);
            var values = this.unitOfWork.Appointments.Find(s => s.AppointmentId == appointmentId);
            var commonQry = $@"select * from ""CommonEncounter"" where  ""PatientId"" = {patientId} and ""Active"" = true order by ""CreatedDate"" desc limit 1";
            var commonValues= await this.unitOfWork.Current.QueryFirstOrDefaultAsync<CommonEncounterModel>(commonQry);
            if (isAdmission)
            {
                admissionRecords = this.unitOfWork.Admission.Find(s => s.AdmissionId == appointmentId);

            }
            else
            {
                appointmentRecords = this.unitOfWork.Appointments.Find(s => s.AppointmentId == appointmentId);
            }
            var encounter = new GynEncounter
            {
                Active = true,
                AdmissionId = admissionRecords.AdmissionId,
                AppointmentId = appointmentRecords.AppointmentId,
                EncounterDate = DateTime.UtcNow,
                PatientId = isAdmission ? admissionRecords.PatientId : appointmentRecords.PatientId,
            };
            if (res != null)
            {
                encounter.Abdomen = res.Abdomen;
                encounter.AdditionalLabs = res.AdditionalLabs;
                encounter.BirthControl = res.BirthControl;
                encounter.Breast = res.Breast;
                encounter.BreastScreening = res.BreastScreening;
                encounter.CancerHistory = res.CancerHistory;
                encounter.Cardiovascular = res.Cardiovascular;                
                encounter.GynHistory = res.GynHistory;               
                encounter.GynLabs = res.GynLabs;
                encounter.GynUltraSound = res.GynUltraSound;
                encounter.Heent = res.Heent;
                encounter.LastBreastUltraSound = res.LastBreastUltraSound;
                encounter.LastDexaScan = res.LastDexaScan;
                encounter.LastMammogram = res.LastMammogram;
                encounter.LastPelvicUltraSound = res.LastPelvicUltraSound;
                encounter.Lymphatic = res.Lymphatic;
                encounter.MenopausalHistory = res.MenopausalHistory;
                encounter.MensutralHistory = res.MensutralHistory;
                encounter.MusculoSkeletal = res.MusculoSkeletal;
                encounter.PatientDeferred = res.PatientDeferred;
                encounter.Pelvic = res.Pelvic;
                encounter.PhysicalExam = res.PhysicalExam;
                encounter.Respiratory = res.Respiratory;
                encounter.Skin = res.Skin;
                encounter.Vitals = res.Vitals;
                encounter.GyneacCard = res.GyneacCard;
                encounter.GynIUI = res.GynIUI;
                encounter.ProformaForOasi = res.ProformaForOasi;
                encounter.Procedure = res.Procedure;
                encounter.GyneacPartner = res.GyneacPartner;
                // case OBEncounterType.ProblemList:
                //    commonEncounter.ProblemList = model.JsonString;
                //    break;
                //case OBEncounterType.FamilyHistory:
                //    commonEncounter.FamilyHistory = model.JsonString;
                //    break;
                //case OBEncounterType.BirthHistory:
                //    commonEncounter.BirthHistory = model.JsonString;
                //    break;
                //case OBEncounterType.Surgeries:
                //    commonEncounter.Surgeries = model.JsonString;
                    if (commonValues!=null && commonValues.FamilyHistory!=null)
                {
                    encounter.FamilyHistory = commonValues.FamilyHistory;
                }
                if (commonValues != null && commonValues.Surgeries != null)
                {
                    encounter.Surgeries = commonValues.Surgeries;
                }
                if (commonValues != null && commonValues.BirthHistory != null)
                {
                    encounter.BirthHistory = commonValues.BirthHistory;
                }
                if (commonValues != null && commonValues.ProblemList != null)
                {
                    encounter.ProblemList = commonValues.ProblemList;
                }
                //encounter.ProblemList = res.ProblemList;
                //encounter.Surgeries = res.Surgeries;
                //encounter.BirthHistory = res.BirthHistory;
                encounter.Allergies = res.Allergies;
                encounter.GyneacSurgery = res.GyneacSurgery;
                encounter.GyneacDiscargeSummary = res.GyneacDiscargeSummary;
                encounter.GyneacAdmissionSheet = res.GyneacAdmissionSheet;
                encounter.Colposcopic = res.Colposcopic;
                encounter.Ectopic = res.Ectopic;
                encounter.ReferralForm = res.ReferralForm;
                encounter.SpeacialFeature = res.SpeacialFeature;
                //encounter.RefferalOrder = res.RefferalOrder;
                encounter.MeasureCommonData = res.MeasureCommonData;
            }
            try
            {
                var response = await this.unitOfWork.GynEncounters.InsertAsync(encounter);
                commonResponse.Response = response;
                var basicDetails = await this.encounterServices.GetBasicAppointmentDetails(appointmentRecords.AppointmentId, isAdmission);
                await this.appointmentsServices.UpdateEncounterTypeAsync(appointmentRecords.AppointmentId,
                    (int)EncounterTypes.GynEncounter, isAdmission);
                 ;
                return commonResponse;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task<int> getApppointmentId(int appointmentId, bool isAdmission)
        {
            var id = 0;
            id = isAdmission ? await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(*) FROM ""GynEncounter"" WHERE ""AdmissionId"" = {appointmentId}") :
            await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(*) FROM ""GynEncounter"" WHERE ""AppointmentId"" = {appointmentId}");
            return id;
        }

        public async Task<int> getAptId(int patientId)
        {

            var checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>($@"select count(*) from ""CommonEncounter"" where  ""AppointmentId""= '{patientId}'");
            return checkIf;
        }
        /// <inheritdoc />
        public async Task<GynEncounterResource> FindDashboardAsync(int appointmentId, GynEncounterType type, bool isAdmission)
        {
            try
            {
                var gynEncounter = new GynEncounterModel();
                var admRecord = new Admission();
                var appRecord = new Appointment();
                var findAppointmentId = 0;
                if (appointmentId != 0)
                {
                    var query = "";
                    if (isAdmission)
                    {
                        admRecord = this.unitOfWork.Admission.Find(s => s.AdmissionId == appointmentId);
                        findAppointmentId = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(*) FROM ""GynEncounter"" WHERE ""AdmissionId"" = {appointmentId}");
                    }
                    else
                    {
                        appRecord = this.unitOfWork.Appointments.Find(s => s.AppointmentId == appointmentId);
                        findAppointmentId = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(*) FROM ""GynEncounter"" WHERE ""AppointmentId"" = {appointmentId}");
                    }

                    if (findAppointmentId == 0)
                    {
                        query = isAdmission ? $@"select * from ""GynEncounter"" where ""PatientId""={admRecord.PatientId} order by 1 desc " :
                            $@"select * from ""GynEncounter"" where ""PatientId""={appRecord.PatientId} order by 1 desc ";

                    }
                    else
                    {
                        query = isAdmission ? $@"select * from ""GynEncounter"" where ""PatientId""={admRecord.PatientId}  and  ""AdmissionId""={appointmentId} order by 1 desc " :
                             $@"select * from ""GynEncounter"" where ""PatientId""={appRecord.PatientId}  and  ""AppointmentId""={appointmentId} order by 1 desc ";
                    }
                    gynEncounter = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<GynEncounterModel>(query);

                }
                var gynEncounterResource = new GynEncounterResource
                {
                    AppointmentId = appointmentId,
                    GynEncounterId = null,
                    JsonString = null
                };

                if (gynEncounter != null)
                {
                    gynEncounterResource.GynEncounterId = gynEncounter.GynEncounterId;
                    switch (type)
                    {
                        case GynEncounterType.Abdomen:
                            gynEncounterResource.JsonString = gynEncounter.Abdomen;
                            break;
                        case GynEncounterType.AdditionalLabs:
                            gynEncounterResource.JsonString = gynEncounter.AdditionalLabs;
                            break;
                        case GynEncounterType.BirthControl:
                            gynEncounterResource.JsonString = gynEncounter.BirthControl;
                            break;
                        case GynEncounterType.Breast:
                            gynEncounterResource.JsonString = gynEncounter.Breast;
                            break;
                        case GynEncounterType.BreastScreening:
                            gynEncounterResource.JsonString = gynEncounter.BreastScreening;
                            break;
                        case GynEncounterType.CancerHistory:
                            gynEncounterResource.JsonString = gynEncounter.CancerHistory;
                            break;
                        case GynEncounterType.Cardiovascular:
                            gynEncounterResource.JsonString = gynEncounter.Cardiovascular;
                            break;
                        case GynEncounterType.GynHistory:
                            gynEncounterResource.JsonString = gynEncounter.GynHistory;
                            break;
                        case GynEncounterType.GynLabs:
                            gynEncounterResource.JsonString = gynEncounter.GynLabs;
                            break;
                        case GynEncounterType.GynUltraSound:
                            gynEncounterResource.JsonString = gynEncounter.GynUltraSound;
                            break;
                        case GynEncounterType.Heent:
                            gynEncounterResource.JsonString = gynEncounter.Heent;
                            break;
                        case GynEncounterType.LastBreastUltraSound:
                            gynEncounterResource.JsonString = gynEncounter.LastBreastUltraSound;
                            break;
                        case GynEncounterType.LastDexaScan:
                            gynEncounterResource.JsonString = gynEncounter.LastDexaScan;
                            break;
                        case GynEncounterType.LastMammogram:
                            gynEncounterResource.JsonString = gynEncounter.LastMammogram;
                            break;
                        case GynEncounterType.LastPelvicUltraSound:
                            gynEncounterResource.JsonString = gynEncounter.LastPelvicUltraSound;
                            break;
                        case GynEncounterType.Lymphatic:
                            gynEncounterResource.JsonString = gynEncounter.Lymphatic;
                            break;

                        case GynEncounterType.MenopausalHistory:
                            gynEncounterResource.JsonString = gynEncounter.MenopausalHistory;
                            break;
                        case GynEncounterType.MensutralHistory:
                            gynEncounterResource.JsonString = gynEncounter.MensutralHistory;
                            break;
                        case GynEncounterType.MusculoSkeletal:
                            gynEncounterResource.JsonString = gynEncounter.MusculoSkeletal;
                            break;
                        case GynEncounterType.PatientDeferred:
                            gynEncounterResource.JsonString = gynEncounter.PatientDeferred;
                            break;
                        case GynEncounterType.Pelvic:
                            gynEncounterResource.JsonString = gynEncounter.Pelvic;
                            break;
                        case GynEncounterType.PhysicalExam:
                            gynEncounterResource.JsonString = gynEncounter.PhysicalExam;
                            break;
                        case GynEncounterType.Respiratory:
                            gynEncounterResource.JsonString = gynEncounter.Respiratory;
                            break;
                        case GynEncounterType.Skin:
                            gynEncounterResource.JsonString = gynEncounter.Skin;
                            break;
                        case GynEncounterType.Vitals:
                            gynEncounterResource.JsonString = gynEncounter.Vitals;
                            break;
                        case GynEncounterType.GyneacCard:
                            gynEncounterResource.JsonString = gynEncounter.GyneacCard;
                            break;
                        case GynEncounterType.GynaecOrders:
                            gynEncounterResource.JsonString = gynEncounter.GynaecOrders;
                            break;
                        case GynEncounterType.GynIUI:
                            gynEncounterResource.JsonString = gynEncounter.GynIUI;
                            break;
                        case GynEncounterType.ProformaForOasi:
                            gynEncounterResource.JsonString = gynEncounter.ProformaForOasi;
                            break;
                        case GynEncounterType.Procedure:
                            gynEncounterResource.JsonString = gynEncounter.Procedure;
                            break;
                        case GynEncounterType.GyneacPartner:
                            gynEncounterResource.JsonString = gynEncounter.GyneacPartner;
                            break;
                        case GynEncounterType.FamilyHistory:
                            gynEncounterResource.JsonString = gynEncounter.FamilyHistory;
                            break;
                        case GynEncounterType.ProblemList:
                            gynEncounterResource.JsonString = gynEncounter.ProblemList;
                            break;
                        case GynEncounterType.Surgeries:
                            gynEncounterResource.JsonString = gynEncounter.Surgeries;
                            break;
                        case GynEncounterType.BirthHistory:
                            gynEncounterResource.JsonString = gynEncounter.BirthHistory;
                            break;
                        case GynEncounterType.Allergies:
                            gynEncounterResource.JsonString = gynEncounter.Allergies;
                            break;
                        case GynEncounterType.GyneacSurgery:
                            gynEncounterResource.JsonString = gynEncounter.GyneacSurgery;
                            break;
                        case GynEncounterType.GyneacAdmissionSheet:
                            gynEncounterResource.JsonString = gynEncounter.GyneacAdmissionSheet;
                            break;
                        case GynEncounterType.GyneacDiscargeSummary:
                            gynEncounterResource.JsonString = gynEncounter.GyneacDiscargeSummary;
                            break;
                        //case GynEncounterType.GynaecVisit:
                        //    gynEncounterResource.JsonString = gynEncounter.GynaecVisit;
                        //    break;
                        //case GynEncounterType.OrderPrescription:
                        //    gynEncounterResource.JsonString = gynEncounter.OrderPrescription;
                        //    break;
                        case GynEncounterType.Colposcopic:
                            gynEncounterResource.JsonString = gynEncounter.Colposcopic;
                            break;
                        case GynEncounterType.Ectopic:
                            gynEncounterResource.JsonString = gynEncounter.Ectopic;
                            break;
                        case GynEncounterType.ReferralForm:
                            gynEncounterResource.JsonString = gynEncounter.ReferralForm;
                            break;
                        case GynEncounterType.SpeacialFeature:
                            gynEncounterResource.JsonString = gynEncounter.SpeacialFeature;
                            break;
                        case GynEncounterType.Measure:
                            gynEncounterResource.JsonString = gynEncounter.Measure;
                            break;
                        case GynEncounterType.RefferalOrder:
                            gynEncounterResource.JsonString = gynEncounter.RefferalOrder;
                            break;
                        case GynEncounterType.ScanAppointmentDetails:
                            gynEncounterResource.JsonString = gynEncounter.ScanAppointmentDetails;
                            break;
                        case GynEncounterType.OutSideTests:
                            gynEncounterResource.JsonString = gynEncounter.OutSideTests;
                            break;
                        case GynEncounterType.Reminder:
                            gynEncounterResource.JsonString = gynEncounter.Reminder;
                            break;
                    }
                }

                return gynEncounterResource;
            }
            catch (Exception e)
            {
                throw;
            }
        }
        /// <inheritdoc />
        public async Task<CommonResponse> AddAltAsync(GynEncounterModifyModel model)
        {
            var commonResponse = new CommonResponse { Status = 1 };
            var checkIf = model.IsAdmission
                ? await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""GynEncounterId"") FROM ""GynEncounter"" WHERE ""AdmissionId"" = {model.AppointmentId}")
                : await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""GynEncounterId"") FROM ""GynEncounter"" WHERE ""AppointmentId"" = {model.AppointmentId}");
            if (checkIf > 0)
            {
                commonResponse.Response = -1;
                return commonResponse;
            }
            var admission = new Admission();
            var appointment = new Appointment();
            if (model.IsAdmission)
            {
                admission = this.unitOfWork.Admission.Find(s => s.AdmissionId == model.AppointmentId);
            }
            else
            {
                appointment = this.unitOfWork.Appointments.Find(s => s.AppointmentId == model.AppointmentId);
            }
            var values = this.unitOfWork.Appointments.Find(s => s.AppointmentId == model.AppointmentId);
            var encounter = new GynEncounter
            {
                Active = true,
                AppointmentId = model.IsAdmission ? null : (int?)model.AppointmentId,
                AdmissionId = model.IsAdmission ? (int?)model.AppointmentId : null,
                EncounterDate = DateTime.Now,
                CreatedBy = model.ModifiedBy,
                CreatedDate = DateTime.Now,
                PatientId = model.IsAdmission ? admission.PatientId : appointment.PatientId
            };

            switch (model.Type)
            {
                case GynEncounterType.Abdomen:
                    encounter.Abdomen = model.JsonString;
                    break;
                case GynEncounterType.AdditionalLabs:
                    encounter.AdditionalLabs = model.JsonString;
                    break;
                case GynEncounterType.BirthControl:
                    encounter.BirthControl = model.JsonString;
                    break;
                case GynEncounterType.Breast:
                    encounter.Breast = model.JsonString;
                    break;
                case GynEncounterType.BreastScreening:
                    encounter.BreastScreening = model.JsonString;
                    break;
                case GynEncounterType.CancerHistory:
                    encounter.CancerHistory = model.JsonString;
                    break;
                case GynEncounterType.Cardiovascular:
                    encounter.Cardiovascular = model.JsonString;
                    break;
                case GynEncounterType.GynHistory:
                    encounter.GynHistory = model.JsonString;
                    break;
                case GynEncounterType.GynLabs:
                    encounter.GynLabs = model.JsonString;
                    break;
                case GynEncounterType.GynUltraSound:
                    encounter.GynUltraSound = model.JsonString;
                    break;
                case GynEncounterType.Heent:
                    encounter.Heent = model.JsonString;
                    break;
                case GynEncounterType.LastBreastUltraSound:
                    encounter.LastBreastUltraSound = model.JsonString;
                    break;
                case GynEncounterType.LastDexaScan:
                    encounter.LastDexaScan = model.JsonString;
                    break;
                case GynEncounterType.LastMammogram:
                    encounter.LastMammogram = model.JsonString;
                    break;
                case GynEncounterType.LastPelvicUltraSound:
                    encounter.LastPelvicUltraSound = model.JsonString;
                    break;
                case GynEncounterType.Lymphatic:
                    encounter.Lymphatic = model.JsonString;
                    break;

                case GynEncounterType.MenopausalHistory:
                    encounter.MenopausalHistory = model.JsonString;
                    break;
                case GynEncounterType.MensutralHistory:
                    encounter.MensutralHistory = model.JsonString;
                    break;
                case GynEncounterType.MusculoSkeletal:
                    encounter.MusculoSkeletal = model.JsonString;
                    break;
                case GynEncounterType.PatientDeferred:
                    encounter.PatientDeferred = model.JsonString;
                    break;
                case GynEncounterType.Pelvic:
                    encounter.Pelvic = model.JsonString;
                    break;
                case GynEncounterType.PhysicalExam:
                    encounter.PhysicalExam = model.JsonString;
                    break;
                case GynEncounterType.Respiratory:
                    encounter.Respiratory = model.JsonString;
                    break;
                case GynEncounterType.Skin:
                    encounter.Skin = model.JsonString;
                    break;
                case GynEncounterType.Vitals:
                    encounter.Vitals = model.JsonString;
                    break;

                case GynEncounterType.GyneacCard:
                    encounter.GyneacCard = model.JsonString;
                    break;
                case GynEncounterType.GynaecOrders:
                    encounter.GynaecOrders = model.JsonString;
                    break;
                case GynEncounterType.GynIUI:
                    encounter.GynIUI = model.JsonString;
                    break;
                case GynEncounterType.GynaecVisit:
                    encounter.GynaecVisit = model.JsonString;
                    break;
                case GynEncounterType.ProformaForOasi:
                    encounter.ProformaForOasi = model.JsonString;
                    break;
                case GynEncounterType.Procedure:
                    encounter.Procedure = model.JsonString;
                    break;
                case GynEncounterType.GyneacPartner:
                    encounter.GyneacPartner = model.JsonString;

                    break;
                case GynEncounterType.FamilyHistory:
                    encounter.FamilyHistory = model.JsonString;
                    break;
                case GynEncounterType.ProblemList:
                    encounter.ProblemList = model.JsonString;
                    break;
                case GynEncounterType.Surgeries:
                    encounter.Surgeries = model.JsonString;
                    break;
                case GynEncounterType.BirthHistory:
                    encounter.BirthHistory = model.JsonString;
                    break;
                case GynEncounterType.Allergies:
                    encounter.Allergies = model.JsonString;
                    break;
                case GynEncounterType.OrderPrescription:
                    encounter.OrderPrescription = model.JsonString;
                    break;

                case GynEncounterType.GyneacAdmissionSheet:
                    encounter.GyneacAdmissionSheet = model.JsonString;
                    break;
                case GynEncounterType.GyneacSurgery:
                    encounter.GyneacSurgery = model.JsonString;
                    break;
                case GynEncounterType.GyneacDiscargeSummary:
                    encounter.GyneacDiscargeSummary = model.JsonString;
                    break;
                case GynEncounterType.Colposcopic:
                    encounter.Colposcopic = model.JsonString;
                    break;
                case GynEncounterType.Ectopic:
                    encounter.Ectopic = model.JsonString;
                    break;
                case GynEncounterType.SpeacialFeature:
                    encounter.SpeacialFeature = model.JsonString;
                    break;
                case GynEncounterType.ReferralForm:
                    encounter.ReferralForm = model.JsonString;
                    break;
                case GynEncounterType.Measure:
                    encounter.Measure = model.JsonString;
                    break;
                case GynEncounterType.RefferalOrder:
                    encounter.RefferalOrder = model.JsonString;
                    break;
                case GynEncounterType.ScanAppointmentDetails:
                    encounter.ScanAppointmentDetails = model.JsonString;
                    break;
                case GynEncounterType.OutSideTests:
                    encounter.OutSideTests = model.JsonString;
                    break;
                case GynEncounterType.Reminder:
                    encounter.Reminder = model.JsonString;
                    break;
            }
            if (model.Type == GynEncounterType.Measure || model.Type == GynEncounterType.GynaecVisit)
            {
                encounter.MeasureCommonData = model.JsonString;
            }
            if (model.Type == GynEncounterType.GynaecVisit)
            {
                encounter.MeasureCommonData = model.JsonString;
            }
            if (model.RefferalOrder != null)
            {
                encounter.RefferalOrder = model.RefferalOrder;
            }
            if (model.Type == GynEncounterType.ReferralForm)
            {

                var value = JsonConvert.DeserializeObject<ReferralFormModel>(model.JsonString);
                value.AppointmentId = model.AppointmentId;
                value.IsAdmission = model.IsAdmission;
                await this.InsertReferralForm(value);
            }
            try
            {
                var response = await this.unitOfWork.GynEncounters.InsertAsync(encounter);
                commonResponse.Response = response;
                var msg = " Added Gynae Encounter ";
                await this.timelineService.LogAsync(new TimelineModel
                {
                    PatientId = model.IsAdmission ? admission.PatientId : appointment.PatientId,
                    TimelineActionId = TimelineAction.EncounterAdded,
                    CreatedBy = model.ModifiedBy,
                    Description = msg,
                    AppointmentId = !model.IsAdmission ? appointment.AppointmentId : 0
                });
                return commonResponse;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        /// <inheritdoc />
        public async Task<CommonResponse> UpdateAltAsync(GynEncounterModifyModel model)
        {
            var commonResponse = new CommonResponse { Status = 1 };
            var encounter = await this.unitOfWork.GynEncounters.FindAsync(m => m.GynEncounterId == model.GynEncounterId);

            var checkIf = model.IsAdmission
                    //await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""OBEncounterId"") FROM ""ObEncounter"" WHERE ""AdmissionId"" = '{model.AppointmentId}' AND ""OBEncounterId"" <> '{model.OBEncounterId}'")
                    ? await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""GynEncounterId"") FROM ""GynEncounter"" WHERE ""AdmissionId"" = '{model.AppointmentId}' AND ""GynEncounterId"" <> '{model.GynEncounterId}'")
                    : await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""GynEncounterId"") FROM ""GynEncounter"" WHERE ""AppointmentId"" = '{model.AppointmentId}' AND ""GynEncounterId"" <> '{model.GynEncounterId}'");

            if (checkIf > 0)
            {
                commonResponse.Response = -1;
                return commonResponse;
            }

            encounter.ModifiedBy = model.ModifiedBy;
            encounter.ModifiedDate = DateTime.Now;

            switch (model.Type)
            {
                case GynEncounterType.Abdomen:
                    encounter.Abdomen = model.JsonString;
                    break;
                case GynEncounterType.AdditionalLabs:
                    encounter.AdditionalLabs = model.JsonString;
                    break;
                case GynEncounterType.BirthControl:
                    encounter.BirthControl = model.JsonString;
                    break;
                case GynEncounterType.Breast:
                    encounter.Breast = model.JsonString;
                    break;
                case GynEncounterType.BreastScreening:
                    encounter.BreastScreening = model.JsonString;
                    break;
                case GynEncounterType.CancerHistory:
                    encounter.CancerHistory = model.JsonString;
                    break;
                case GynEncounterType.Cardiovascular:
                    encounter.Cardiovascular = model.JsonString;
                    break;
                case GynEncounterType.GynHistory:
                    encounter.GynHistory = model.JsonString;
                    break;
                case GynEncounterType.GynLabs:
                    encounter.GynLabs = model.JsonString;
                    break;
                case GynEncounterType.GynUltraSound:
                    encounter.GynUltraSound = model.JsonString;
                    break;
                case GynEncounterType.Heent:
                    encounter.Heent = model.JsonString;
                    break;
                case GynEncounterType.LastBreastUltraSound:
                    encounter.LastBreastUltraSound = model.JsonString;
                    break;
                case GynEncounterType.LastDexaScan:
                    encounter.LastDexaScan = model.JsonString;
                    break;
                case GynEncounterType.LastMammogram:
                    encounter.LastMammogram = model.JsonString;
                    break;
                case GynEncounterType.LastPelvicUltraSound:
                    encounter.LastPelvicUltraSound = model.JsonString;
                    break;
                case GynEncounterType.Lymphatic:
                    encounter.Lymphatic = model.JsonString;
                    break;

                case GynEncounterType.MenopausalHistory:
                    encounter.MenopausalHistory = model.JsonString;
                    break;
                case GynEncounterType.MensutralHistory:
                    encounter.MensutralHistory = model.JsonString;
                    break;
                case GynEncounterType.MusculoSkeletal:
                    encounter.MusculoSkeletal = model.JsonString;
                    break;
                case GynEncounterType.PatientDeferred:
                    encounter.PatientDeferred = model.JsonString;
                    break;
                case GynEncounterType.Pelvic:
                    encounter.Pelvic = model.JsonString;
                    break;
                case GynEncounterType.PhysicalExam:
                    encounter.PhysicalExam = model.JsonString;
                    break;
                case GynEncounterType.Respiratory:
                    encounter.Respiratory = model.JsonString;
                    break;
                case GynEncounterType.Skin:
                    encounter.Skin = model.JsonString;
                    break;
                case GynEncounterType.Vitals:
                    encounter.Vitals = model.JsonString;
                    break;
                case GynEncounterType.GyneacCard:
                    encounter.GyneacCard = model.JsonString;
                    break;
                case GynEncounterType.GynaecOrders:
                    encounter.GynaecOrders = model.JsonString;
                    break;
                case GynEncounterType.GynIUI:
                    encounter.GynIUI = model.JsonString;
                    break;
                case GynEncounterType.GynaecVisit:
                    encounter.GynaecVisit = model.JsonString;
                    break;
                case GynEncounterType.ProformaForOasi:
                    encounter.ProformaForOasi = model.JsonString;
                    break;
                case GynEncounterType.Procedure:
                    encounter.Procedure = model.JsonString;
                    break;
                case GynEncounterType.GyneacPartner:
                    encounter.GyneacPartner = model.JsonString;
                    break;

                case GynEncounterType.FamilyHistory:
                    encounter.FamilyHistory = model.JsonString;
                    break;
                case GynEncounterType.ProblemList:
                    encounter.ProblemList = model.JsonString;
                    break;
                case GynEncounterType.Surgeries:
                    encounter.Surgeries = model.JsonString;
                    break;

                case GynEncounterType.BirthHistory:
                    encounter.BirthHistory = model.JsonString;
                    break;
                case GynEncounterType.Allergies:
                    encounter.Allergies = model.JsonString;
                    break;
                case GynEncounterType.OrderPrescription:
                    encounter.OrderPrescription = model.JsonString;
                    break;
                case GynEncounterType.GyneacSurgery:
                    encounter.GyneacSurgery = model.JsonString;
                    break;
                case GynEncounterType.GyneacDiscargeSummary:
                    encounter.GyneacDiscargeSummary = model.JsonString;
                    break;
                case GynEncounterType.GyneacAdmissionSheet:
                    encounter.GyneacAdmissionSheet = model.JsonString;
                    break;
                case GynEncounterType.Colposcopic:
                    encounter.Colposcopic = model.JsonString;
                    break;
                case GynEncounterType.Ectopic:
                    encounter.Ectopic = model.JsonString;
                    break;
                case GynEncounterType.SpeacialFeature:
                    encounter.SpeacialFeature = model.JsonString;
                    break;
                case GynEncounterType.ReferralForm:
                    encounter.ReferralForm = model.JsonString;
                    break;
                case GynEncounterType.Measure:
                    encounter.Measure = model.JsonString;
                    break;
                case GynEncounterType.ScanAppointmentDetails:
                    encounter.ScanAppointmentDetails = model.JsonString;
                    break;
                case GynEncounterType.OutSideTests:
                    encounter.OutSideTests = model.JsonString;
                    break;
                case GynEncounterType.Reminder:
                    encounter.Reminder = model.JsonString;
                    break;

            }
            if (model.Type == GynEncounterType.ReferralForm)
            {

                var value = JsonConvert.DeserializeObject<ReferralFormModel>(model.JsonString);
                value.AppointmentId = model.AppointmentId;
                value.IsAdmission = model.IsAdmission;
                await this.InsertReferralForm(value);
            }
            if (model.Type == GynEncounterType.Measure || model.Type == GynEncounterType.GynaecVisit)
            {

                encounter.MeasureCommonData = model.JsonString;
            }

            if (model.RefferalOrder != null)
            {
                encounter.RefferalOrder = model.RefferalOrder;
            }

            var updated = await this.unitOfWork.GynEncounters.UpdateAsync(encounter);


            commonResponse.Response = updated > 0 ? encounter.GynEncounterId : 0;
            return commonResponse;
        }
        public async Task<int> InsertReferralForm(ReferralFormModel model)
        {
            
                var checkIf=0;                 
                var referralForm = new ReferralForm();
                referralForm.ReferralDoctor = model.ReferralDoctor;
                referralForm.Reason = model.Reason;
                referralForm.RequiredDate = model.RequiredDate;
                referralForm.Time = model.Time;
                referralForm.ConsultantDoctor = model.ConsultantDoctor;
                referralForm.CreatedDate = DateTime.Now;
                referralForm.Active = model.Active;
                referralForm.ProviderId = model.ProviderId;
                referralForm.ProviderId = model.ProviderId;
                referralForm.PatientId = model.PatientId;
                referralForm.Opinion = model.Opinion;
                if (model.IsAdmission)
                {
                    referralForm.AdmissionId = (int)model.AppointmentId;
                    checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>($@"select count(*) from ""ReferralForm"" where  ""AdmissionId""= '{model.AppointmentId}'");
                }
                else
                {
                    referralForm.AppointmentId = (int)model.AppointmentId;
                    checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>($@"select count(*) from ""ReferralForm"" where  ""AppointmentId""= '{model.AppointmentId}'");
                }
                if (checkIf > 0)
                {
                    if (model.IsAdmission)
                    {
                        var records = this.unitOfWork.ReferralForms.Find(s => s.AdmissionId == model.AppointmentId);
                        referralForm.ReferralFormId = records.ReferralFormId;
                    }
                    else
                    {
                        var records = this.unitOfWork.ReferralForms.Find(s => s.AppointmentId == model.AppointmentId);
                        referralForm.ReferralFormId = records.ReferralFormId;
                    }
                    return await this.unitOfWork.ReferralForms.UpdateAsync(referralForm);
                }

                return await this.unitOfWork.ReferralForms.InsertAsync(referralForm);
            
           
        }        /// <inheritdoc />
        public async Task<AppointmentModel> GetAccountBasedOnAppointmentId(long appointmentId, bool isAdmission)
        {
            var query = isAdmission
                ? $@"Select A.""PatientId"", A.""AdmissionNo"" ""AppointmentNo"", A.""AdmissionDate"" ""AppointmentDate"" from ""Admission"" A 
                                where A.""AdmissionId"" = {appointmentId}"
                : $@"Select A.""PatientId"", A.""AppointmentNo"", A.""AppointmentDate"", A.""AppointmentTime"" from ""Appointment"" A 
                                where A.""AppointmentId"" = {appointmentId}";

            var record = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<AppointmentModel>(query);
            if (isAdmission)
            {
                record.AppointmentTime = record.AppointmentDate.TimeOfDay;
            }

            return record;
        }
        /// <inheritdoc />
        public Task<GynEncounterFullTranscriptModel> FindFullTranscriptAsync(int appointmentId, bool isAdmissionValue)
        {
            var query = !isAdmissionValue ? $@"SELECT A.""AppointmentId"", A.""AppointmentNo"",A.""AppointmentDate"",A.""AppointmentTime"", 
                             (case when A.""PatientFamilyId"" is not null then PF.""FullName"" else P.""FullName"" end) AS ""PatientName"", 
                             (case when A.""PatientFamilyId"" is not null then PF.""Gender"" else P.""Gender"" end) AS ""PatientGender"",C.""CountryCode"" AS ""PatientCountryCode"",
                             CONCAT(Pr.""Salutation"",' ', Pr.""FullName"") AS ""ProviderName"",pr.""FriendlyName"",pr.""Email"" as ""ProviderEmail"",pr.""ProviderNo"",p.""UMRNo"",P.""Mobile"" AS ""PatientMobile"",
                            (case when A.""PatientFamilyId"" is not null then PF.""Age"" else P.""Age"" end) AS ""PatientAge"", P.""DateOfBirth"" AS ""PatientDateOfBirth"",
							(CASE WHEN P.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', P.""Guid"", '/', P.""ThumbnailUrl"") ELSE NULL END) AS ""PatientThumbnailUrl"",
							""GynEncounterId"",""Abdomen"", ""AdditionalLabs"",  ""Breast"",""BirthControl"", ""BreastScreening"", ""CancerHistory"",
                            ""Cardiovascular"", ""GynHistory"", ""GynLabs"", ""GynUltraSound"", ""Heent"",""LastBreastUltraSound"",""LastDexaScan"",
							""LastMammogram"",""LastPelvicUltraSound"",""Lymphatic"",""MenopausalHistory"",""MensutralHistory"",""MusculoSkeletal"",""PatientDeferred"",""GynIUI"",""GynaecVisit"",""GynaecOrders"",""GyneacCard"",
							""Pelvic"" , ""PhysicalExam"",""Respiratory"",""Skin"", ""Vitals"",""OutSideTests"",
""GyneacAdmissionSheet"" ,    ""GyneacSurgery"" ,    ""GyneacDiscargeSummary"" ,    ""Colposcopic"",    ""Ectopic"" ,    ""SpeacialFeature"" ,""OutSideTests"",
    ""ReferralForm"" ,    ""Measure"" ,    ""RefferalOrder"" , ""Reminder"",L.""Name"" as ""PracticeLocation"",
""GyneacCard"",""GynaecOrders"",""GynIUI"",""GynaecVisit"",""Procedure"",""GyneacPartner"",""ProformaForOasi"",""Colposcopic"" ,""Ectopic"",""Measure"",""RefferalOrder"",
    ""Allergies"",""Procedure"",""OrderPrescription"" ,""ScanAppointmentDetails"",
CE.""BirthHistory"", CE.""FamilyHistory"", CE.""ProblemList"",CE.""Surgeries"" 
FROM ""Appointment"" A
							LEFT JOIN ""GynEncounter"" ge ON A.""AppointmentId""= ge.""AppointmentId""
left join ""CommonEncounter"" CE on CE.""PatientId""=ge.""PatientId""
							LEFT JOIN ""AppointmentSymptom"" ATS ON  ATS.""AppointmentId"" = A.""AppointmentId""
                            LEFT JOIN ""Provider"" pr on pr.""ProviderId""=A.""ProviderId""
							JOIN ""Patient"" P ON P.""PatientId"" = A.""PatientId""
                            Left join ""PatientFamily"" PF on PF.""PatientFamilyId"" = A.""PatientFamilyId""
							LEFT JOIN ""Country"" C ON C.""CountryId""=P.""CountryId""
                            LEFT JOIN ""Location"" L on L.""LocationId""=A.""LocationId""
                            where A.""AppointmentId"" = {appointmentId} AND A.""Active"" IS TRUE" :

                            $@"SELECT A.*, 
                              P.""FullName"" AS ""PatientName"", 
                             P.""Gender""  AS ""PatientGender"",C.""CountryCode"" AS ""PatientCountryCode"",
                             CONCAT(Pr.""Salutation"",' ', Pr.""FullName"") AS ""ProviderName"",pr.""FriendlyName"",pr.""Email"" as ""ProviderEmail"",pr.""ProviderNo"",p.""UMRNo"",P.""Mobile"" AS ""PatientMobile"",
                             P.""Age""  AS ""PatientAge"", P.""DateOfBirth"" AS ""PatientDateOfBirth"",
							(CASE WHEN P.""ThumbnailUrl"" IS NOT NULL THEN CONCAT('{this.amazonS3Configuration.BucketURL}', P.""Guid"", '/', P.""ThumbnailUrl"") ELSE NULL END) AS ""PatientThumbnailUrl"",
							""GynEncounterId"",""Abdomen"", ""AdditionalLabs"",  ""Breast"",""BirthControl"", ""BreastScreening"", ""CancerHistory"",
                            ""Cardiovascular"", ""GynHistory"", ""GynLabs"", ""GynUltraSound"", ""Heent"",""LastBreastUltraSound"",""LastDexaScan"",
							""LastMammogram"",""LastPelvicUltraSound"",""Lymphatic"",""MenopausalHistory"",""MensutralHistory"",""MusculoSkeletal"",""PatientDeferred"",""GynIUI"",""GynaecVisit"",""GynaecOrders"",""GyneacCard"",
							""Pelvic"" , ""PhysicalExam"",""Respiratory"",""Skin"", ""Vitals"", ""Reminder"",
""GyneacAdmissionSheet"" ,    ""GyneacSurgery"" ,    ""GyneacDiscargeSummary"" ,    ""Colposcopic"",    ""Ectopic"" ,    ""SpeacialFeature"" ,""OutSideTests"",
    ""ReferralForm"" ,    ""Measure"" ,    ""RefferalOrder"" ,L.""Name"" as ""PracticeLocation"",
""GyneacCard"",""GynaecOrders"",""GynIUI"",""GynaecVisit"",""Procedure"",""GyneacPartner"",""ProformaForOasi"",  ""Colposcopic"" ,""Ectopic"",""Measure"",""RefferalOrder"",
   ""Allergies"",""Procedure"",""OrderPrescription"" ,""ScanAppointmentDetails"",
CE.""BirthHistory"", CE.""FamilyHistory"", CE.""ProblemList"",CE.""Surgeries"" 
FROM ""Admission"" A
LEFT JOIN ""GynEncounter"" ge ON A.""AdmissionId""= ge.""AdmissionId""
left join ""CommonEncounter"" CE on CE.""PatientId""=ge.""PatientId""
							LEFT JOIN ""AppointmentSymptom"" ATS ON  ATS.""AdmissionId"" = A.""AdmissionId""
                            LEFT JOIN ""Provider"" pr on pr.""ProviderId""=A.""ProviderId""
							JOIN ""Patient"" P ON P.""PatientId"" = A.""PatientId""
							LEFT JOIN ""Country"" C ON C.""CountryId""=P.""CountryId""
                            LEFT JOIN ""Location"" L on L.""LocationId""=A.""LocationId""
                            where A.""AdmissionId"" = {appointmentId} AND A.""Active"" IS TRUE"
;
            return this.unitOfWork.Current.QueryFirstOrDefaultAsync<GynEncounterFullTranscriptModel>(query);

        }
        public async Task<GYNCardGenerationModel> FetchGynCardAsync(int patientId)
        {

            var query = $@"select * from ""GYNCardGeneration"" where ""PatientId""={patientId} and  ""Active""=true";
            return await this.unitOfWork.Current.QuerySingleOrDefaultAsync<GYNCardGenerationModel>(query);

        }
        public async Task<int> AddGYNCardAsync(GYNCardGenerationModel model, string locationId)
        {
            try
            {

                var checkIf1 = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>($@"select count(*) from ""GYNCardGeneration"" where  ""PatientId""={model.PatientId} and ""Active""= true");
                var checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>($@"select count(*) from ""GYNCardGeneration"" where  ""PatientId""={model.PatientId} and ""Active""= true");
                var gyn = new GynEncounterModifyModel();
                gyn.AppointmentId = (int)model.AppointmentId;
                gyn.JsonString = (string)model.JsonString;
                gyn.Type = model.Type;
                gyn.IsAdmission = false;
                gyn.ModifiedBy = model.ModifiedBy;
                var ebValues = await this.unitOfWork.GynEncounters.FindAsync(s => s.AppointmentId == model.AppointmentId);
                if (ebValues != null)
                {
                    gyn.GynEncounterId = ebValues.GynEncounterId;
                    var respose = await this.UpdateAltAsync(gyn);
                }
                else
                {
                    var respose = await this.AddAltAsync(gyn);
                }
                if (checkIf > 0)
                {
                    var record = await this.unitOfWork.GYNCardGeneration.FindAsync(p => p.GYNCardGenerationId == model.GYNCardGenerationId);
                    record.Department = model.Department;
                    record.HusbandName = model.HusbandName;
                    record.Remarks = model.Remarks;
                    record.RegistrationDate = model.RegistrationDate;
                    record.ProviderId = model.ProviderId;
                    record.PatientId = model.PatientId;
                    record.HusbandAge = model.HusbandAge;
                    record.Active = true;
                    record.GYNNoExists = model.GYNNoExists;
                    record.OtherDetails = model.OtherDetails;
                    record.ConsultantDoctor = model.ConsultantDoctor;
                    return await this.unitOfWork.GYNCardGeneration.UpdateAsync(record);

                }
                else
                {
                    var reason = new GYNCardGeneration
                    {
                        Department = model.Department,
                        HusbandName = model.HusbandName,
                        Remarks = model.Remarks,
                        RegistrationDate = model.RegistrationDate,
                        ProviderId = model.ProviderId,
                        PatientId = model.PatientId,
                        HusbandAge = model.HusbandAge,
                        GYNNoExists = model.GYNNoExists,
                        OtherDetails = model.OtherDetails,
                        ConsultantDoctor = model.ConsultantDoctor,
                        Active = true
                    };
                    var locations = await this.unitOfWork.Locations.FindAsync(s => s.LocationId == int.Parse(locationId));
                    var loc = locations.NameLoc;
                    var currentYear = DateTime.Now.Year.ToString();
                    var lastAncNo = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<GYNCardGenerationModel>($@"select * from ""GYNCardGeneration"" order by 1 desc limit 1");
                    var number = 0;
                    if (lastAncNo == null)
                    {
                        number = 1;
                    }
                    else
                    {
                        var split = lastAncNo.GYNNo.Split("/");
                        number = int.Parse(split[0]);
                    }
                    var newAncNumber = (number + 1) + "/" + currentYear + "/" + loc;
                    reason.GYNNo = newAncNumber;
                    var result = 0;
                    result = await this.unitOfWork.GYNCardGeneration.InsertAsync(reason);
                    if (result > 1)
                    {
                        if (ebValues != null)
                        {
                            gyn.GynEncounterId = ebValues.GynEncounterId;
                            var respose = await this.UpdateAltAsync(gyn);
                        }
                        else
                        {
                            var respose = await this.AddAltAsync(gyn);
                        }
                    }
                    //var updateAppoint = $@"update ""Appointment"" set ""ANCCardGenerationId""={result} where ""AppointmentId""={model.AppointmentId}";
                    //await this.unitOfWork.Current.ExecuteAsync(updateAppoint);

                    return result;
                }


            }
            catch (Exception e)
            {
                throw null;
            }
        }
        public async Task<GynEncounterResource> FindGyn(int appointmentId, GynEncounterType type, bool isAdmission)
        {
            try
            {
                var gynEncounter = isAdmission
                                   ? await this.unitOfWork.GynEncounters.FindAsync(m => m.AdmissionId == appointmentId)
                                   : await this.unitOfWork.GynEncounters.FindAsync(m => m.AppointmentId == appointmentId);

                var gynEncounterResource = new GynEncounterResource
                {
                    AppointmentId = appointmentId,
                    GynEncounterId = null,
                    JsonString = null
                };


                if (gynEncounter != null)
                {
                    gynEncounterResource.GynEncounterId = gynEncounter.GynEncounterId;
                    switch (type)
                    {
                        case GynEncounterType.GynaecVisit:
                            gynEncounterResource.JsonString = gynEncounter.GynaecVisit;
                            break;
                        case GynEncounterType.OrderPrescription:
                            gynEncounterResource.JsonString = gynEncounter.OrderPrescription;
                            break;
                    }
                }

                return gynEncounterResource;
            }
            catch (Exception e)
            {
                throw;
            }

        }
        public async Task<int> FetchVisitNoAsync(int patientId)
        {
            var query = $@"select count(*) from ""GynEncounter"" where ""PatientId""={patientId} and  ""Active""=true";
            return await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>(query);

        }
        public async Task<int> InsertCommonEncounter(CommonEncounterModel model)
        {
            var appRecord = new Appointment();
            var admissionRecords = new Admission();
            if (model.IsAdmission)
            { admissionRecords = this.unitOfWork.Admission.Find(s => s.AdmissionId == model.AppointmentId); }
            else  {  appRecord = this.unitOfWork.Appointments.Find(s => s.AppointmentId == model.AppointmentId); }
            var checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>($@"select count(*) from ""CommonEncounter"" where  ""AppointmentId""= '{model.AppointmentId}'");
            var commonEncounter = new CommonEncounter();
            try
            {
                switch (model.Type)
                {
                    case OBEncounterType.ProblemList:
                        commonEncounter.ProblemList = model.JsonString;
                        break;
                    case OBEncounterType.FamilyHistory:
                        commonEncounter.FamilyHistory = model.JsonString;
                        break;
                    case OBEncounterType.BirthHistory:
                        commonEncounter.BirthHistory = model.JsonString;
                        break;
                    case OBEncounterType.Surgeries:
                        commonEncounter.Surgeries = model.JsonString;
                        break;
                    case OBEncounterType.AncCard :
                        commonEncounter.GPLA = model.GPLA;
                        break;                    
                }
                if(model.GynEncounterType>0 && model.GynEncounterType== GynEncounterType.GynHistory)
                {                    
                        commonEncounter.GPLA= model.GPLA;
                }
                commonEncounter.CreatedBy = model.CreatedBy;
                commonEncounter.AppointmentId = model.AppointmentId;
                commonEncounter.CreatedDate = DateTime.Now;
                commonEncounter.Active = true;
                commonEncounter.PatientId = model.IsAdmission ? admissionRecords.PatientId:appRecord.PatientId;
                if (checkIf > 0)
                {
                    var records = this.unitOfWork.CommonEncounters.Find(s => s.AppointmentId == model.AppointmentId);
                    commonEncounter.CommonEncounterId = records.CommonEncounterId;
                    return await this.unitOfWork.CommonEncounters.UpdateAsync(commonEncounter);
                }
                return await this.unitOfWork.CommonEncounters.InsertAsync(commonEncounter);
            }
            catch (Exception e)
            {
                return 0;
            }

        }

        public async Task<int> UpdateCommonEncounter(CommonEncounterModel model)
        {
            var commonResponse = new CommonResponse { Status = 1 };
            var encounter = await this.unitOfWork.CommonEncounters.FindAsync(m => m.CommonEncounterId == model.CommonEncounterId);
            var appRecord = new Appointment();
            var admissionRecords = new Admission();
            if (model.IsAdmission)
            { admissionRecords = this.unitOfWork.Admission.Find(s => s.AdmissionId == model.AppointmentId); }
            else { appRecord = this.unitOfWork.Appointments.Find(s => s.AppointmentId == model.AppointmentId); }
            var checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>($@"select count(*) from ""CommonEncounter"" where  ""AppointmentId""= '{model.AppointmentId}' AND ""CommonEncounterId"" <> '{model.CommonEncounterId}'");
            if (checkIf > 0)
            {
                commonResponse.Response = -1;
                return -1;
            }
            try
            {
                switch (model.Type)
                {
                    case OBEncounterType.ProblemList:
                        encounter.ProblemList = model.JsonString;
                        break;
                    case OBEncounterType.FamilyHistory:
                        encounter.FamilyHistory = model.JsonString;
                        break;
                    case OBEncounterType.BirthHistory:
                        encounter.BirthHistory = model.JsonString;
                        break;
                    case OBEncounterType.Surgeries:
                        encounter.Surgeries = model.JsonString;
                        break;
                    case OBEncounterType.ANCCardGeneration:
                        encounter.GPLA = model.JsonString;
                        break;
                }
                if (model.GynEncounterType > 0 && model.GynEncounterType == GynEncounterType.GynHistory)
                {
                    encounter.GPLA = model.GPLA;
                }
                encounter.ModifiedBy = model.CreatedBy;
                encounter.ModifiedDate = DateTime.Now;
                encounter.AppointmentId = model.AppointmentId;
                encounter.CreatedDate = DateTime.Now;
                encounter.Active = true;
                encounter.PatientId = model.IsAdmission ? admissionRecords.PatientId : appRecord.PatientId;
                return await this.unitOfWork.CommonEncounters.UpdateAsync(encounter);

            }
            catch (Exception e)
            {
                return 0;
            }

        }
        public async Task<GynEncounterResource> FetchCommonEncounter(OBEncounterType type, GynEncounterType gynEncounterType, int appointmentId,  bool isAdmission)
        {
            var commonEncounter = new CommonEncounterModel();
            var appRecord = new Appointment();
            var admissionRecord = new Admission();
            if(isAdmission)
            {
                admissionRecord = this.unitOfWork.Admission.Find(s => s.AdmissionId == appointmentId);
            }
            else
            {
                appRecord = this.unitOfWork.Appointments.Find(s => s.AppointmentId == appointmentId);               
            }
            var patientId = isAdmission ? admissionRecord.PatientId : appRecord.PatientId;
           
                var query = $@"select * from ""CommonEncounter"" where  ""PatientId""=
                    {patientId} and ""Active""=true order by ""CreatedDate"" desc limit 1";
                commonEncounter = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<CommonEncounterModel>(query);
                //commonEncounter = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<CommonEncounterModel>(query);            
            var gynEncounterResource = new GynEncounterResource
            {
                AppointmentId = appointmentId,
                GynEncounterId = null,
                JsonString = null
            };
            if (commonEncounter != null && type!=null)
            {
                gynEncounterResource.CommonEncounterId = commonEncounter.CommonEncounterId;
                switch (type)
                {
                    case OBEncounterType.FamilyHistory:
                        gynEncounterResource.JsonString = commonEncounter.FamilyHistory;
                        break;
                    case OBEncounterType.BirthHistory:
                        gynEncounterResource.JsonString = commonEncounter.BirthHistory;
                        break;
                    case OBEncounterType.ProblemList:
                        gynEncounterResource.JsonString = commonEncounter.ProblemList;
                        break;
                    case OBEncounterType.Surgeries:
                        gynEncounterResource.JsonString = commonEncounter.Surgeries;
                        break;
                    case OBEncounterType.AncCard:
                        gynEncounterResource.JsonString = commonEncounter.GPLA;
                        break;
                }
                if ((gynEncounterType > 0 && gynEncounterType == GynEncounterType.GynHistory) || (type > 0 && type == OBEncounterType.AncCard))
                {
                    gynEncounterResource.JsonString = commonEncounter.GPLA;
                }

            }
            return gynEncounterResource;

        }



        public Task<IEnumerable<Trial>> FetchCreatedDateNurseNoteReport(int AdmissionId)
        {
            var qry = $@" select * from ""udf_NurseNoteReport""({AdmissionId})";
            ////var qry = $@"select distinct(""CreatedDate""::Date), from ""NurseNote"" WHERE ""AdmissionId"" = {AdmissionId}";
            //var qry = $@"select distinct(NN.""CreatedDate""::Date),Adm.""BedId"",Adm.""AdmissionNo"" ,NN.""Note"",Pat.""UMRNo"",Pat.""FullName"",Acc.""FullName"" as NurseName,bd.""BedNumber""

            //                from ""NurseNote"" NN
            //                 join ""Admission"" Adm on Adm.""AdmissionId"" = NN.""AdmissionId""

            //                 join ""Patient"" pat on Pat.""PatientId"" = Adm.""PatientId""

            //                 join ""Account"" Acc on Acc.""AccountId"" = NN.""CreatedBy""

            //                 join ""Bed"" bd on bd.""BedId"" = Adm.""BedId""  WHERE NN.""AdmissionId"" = {AdmissionId}";
            var appRecord = this.unitOfWork.Current.QueryAsync<Trial>(qry);
            return appRecord;
        }
        public Task<IEnumerable<NurseNoteReportModel>> FetchSingleNurseNoteReport(string qry)
        {
            //var qry = $@"select distinct(""CreatedDate""::Date) from ""NurseNote"" WHERE ""AdmissionId"" = {AdmissionId}";
            var appRecord = this.unitOfWork.Current.QueryAsync<NurseNoteReportModel>(qry);
            return appRecord;
        }
        public async Task<List<Trial>> FetchNurseNoteReport(int AdmissionId)
        {
            var appRecord = FetchCreatedDateNurseNoteReport(AdmissionId);
            var slots = new List<Trial>();

            foreach (var availability in appRecord.Result)
            {
                var where = " where 1=1";
                if (AdmissionId != 0)
                {
                    where += $@" and NN.""AdmissionId"" = {AdmissionId}";
                }
                //if (availability.CreatedDate != null)
                //{
                //    where += $@" and NN.""CreatedDate""::DATE='{availability.CreatedDate}'::DATE";
                //}


                var qry = $@"select NN.*,Adm.""BedId"",Adm.""AdmissionNo"" ,Pat.""UMRNo"",Pat.""FullName"",Acc.""FullName"" as NurseName,bd.""BedNumber""
							from ""NurseNote"" NN
							 join ""Admission"" Adm on Adm.""AdmissionId""=NN.""AdmissionId""
							 join ""Patient"" pat on Pat.""PatientId""=Adm.""PatientId""
							 join ""Account"" Acc on Acc.""AccountId""=NN.""CreatedBy""
							 join ""Bed"" bd on bd.""BedId""=Adm.""BedId"" {where}";
                var response = FetchSingleNurseNoteReport(qry);
                // var response =  this.unitOfWork.Current.QueryAsync<IEnumerable<NurseNoteReportModel>>(qry);
                var multipleDays = new Trial();
                multipleDays.nurseNoteReportModels = new List<NurseNoteReportModel>();
                multipleDays.CreatedDate = availability.CreatedDate;
                multipleDays.AdmissionNo = availability.AdmissionNo;
                multipleDays.FullName = availability.FullName;
                multipleDays.UMRNo = availability.UMRNo;
                foreach (var item in response.Result)
                {
                    multipleDays.nurseNoteReportModels.Add(item);
                }

                slots.Add(multipleDays);
            }


            // var   appRecord =   this.unitOfWork.Current.QueryFirstOrDefaultAsync<NurseNoteReportModel>($@"SELECT ""CreatedDate"" FROM ""NurseNote"" WHERE ""AdmissionId"" = {AdmissionId}");

            return slots;


        }

        public async Task<GynEncounterModel> FindEncounterDataAsync(int appointmentId, bool isAdmission)
        {

            //var result = new GynEncounterModel();
            var query = isAdmission ? $@"select gyn.""GynEncounterId"",gyn.""BirthControl"", gyn.""AppointmentId"",gyn.""PatientId"",gyn.""AdmissionId"",gyn.""CreatedDate"",gyn.""CreatedBy"",
                            gyn. ""GynHistory"", gyn.""GynLabs"", gyn.""GynUltraSound"",  gyn.""MeasureCommonData"",
							gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""GynaecOrders"",gyn.""GyneacCard"",gyn.""GyneacCard"",gyn.""GynaecOrders"",
                        gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""Procedure"",gyn.""GyneacPartner"",gyn.""GyneacSurgery"",gyn.""GyneacAdmissionSheet"",
                        gyn.""ProformaForOasi"",gyn.""Colposcopic"" ,gyn.""Ectopic"",gyn.""Measure"",gyn.""RefferalOrder"",gyn.""Surgeries"",gyn.""Allergies"",gyn.""Surgeries"",gyn.""Procedure"",gyn.""GyneacPartner"",
                    ""OrderPrescription"",	gyn.""GyneacDiscargeSummary"",gyn. ""ReferralForm"",gyn.""SpeacialFeature"",gyn.""MeasureCommonData"",   gyn.""Reminder"",
                     CE.""BirthHistory"", CE.""FamilyHistory"", CE.""ProblemList"",CE.""Surgeries"" from ""GynEncounter"" gyn
                    left join ""CommonEncounter"" CE on CE.""PatientId""=gyn.""PatientId""
                    where   gyn.""AdmissionId""={appointmentId} order by 1 desc" :
                    $@"select gyn.""GynEncounterId"",gyn.""BirthControl"",  gyn.""AppointmentId"",gyn.""PatientId"",gyn.""AdmissionId"",gyn.""CreatedDate"",gyn.""CreatedBy"",
                            gyn. ""GynHistory"", gyn.""GynLabs"", gyn.""GynUltraSound"", gyn.""GyneacSurgery"",gyn.""GyneacAdmissionSheet"",
							gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""GynaecOrders"",gyn.""GyneacCard"",gyn.""GyneacCard"",gyn.""GynaecOrders"",
                    gyn.""GynIUI"",gyn.""GynaecVisit"",gyn.""Procedure"",gyn.""GyneacPartner"",gyn.""GyneacDiscargeSummary"",gyn. ""ReferralForm"",gyn.""SpeacialFeature"",
                    gyn.""ProformaForOasi"",gyn.""Colposcopic"" ,gyn.""Ectopic"",gyn.""Measure"",gyn.""RefferalOrder"",gyn.""Surgeries"",gyn.""Allergies"",gyn.""Surgeries"",gyn.""Procedure"",gyn.""GyneacPartner"",
                    ""OrderPrescription"",	gyn.""MeasureCommonData"",    gyn.""Reminder"",
                    CE.""BirthHistory"", CE.""FamilyHistory"", CE.""ProblemList"",CE.""Surgeries"" from ""GynEncounter"" gyn
                    left join ""CommonEncounter"" CE on CE.""PatientId""=gyn.""PatientId""
                    where   gyn.""AppointmentId""={appointmentId} order by 1 desc";
           var  result = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<GynEncounterModel>(query);
            if(result == null)
            {
                result = new GynEncounterModel();
            }
            return result;
        }


        public Task<int> ModifyGynEncounterStatus(int appointmentId)
        {
            var query = $@"UPDATE ""GynEncounter"" SET ""IsEncounterClosed"" = true  WHERE ""AppointmentId""= {appointmentId}";
            return this.unitOfWork.Current.ExecuteAsync(query);
        }
    }
}
