using System.Collections.Generic;
using System;
using System.Linq;
using Hims.Api.Models.Account;
using Hims.Shared.EntityModels;
using Hims.Shared.Library;

namespace Hims.Api.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using AutoMapper;
    using Domain.Helpers;
    using Domain.Services;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Models.Patient;
    using Senders;
    using Shared.DataFilters;
    using Shared.EntityModels;
    using Shared.Library;
    using Shared.Library.Enums;
    using Shared.UserModels;
    using Shared.UserModels.Filters;
    using Shared.UserModels.Common;
    using Utilities;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using Npgsql;
    using Hims.Domain.Configurations;
    using Hims.Api.Helper;
    using Hims.Api.Models;
    using Hims.Domain.Entities;
    using Microsoft.EntityFrameworkCore.Internal;
    using Hims.Domain.Repositories.UnitOfWork;
    using Hims.Shared.UserModels.Queue;
    using PatientModel = Shared.EntityModels.PatientModel;
    using DocumentFormat.OpenXml.Office2010.Excel;
    using System.Security.Policy;
    using Hims.Shared.UserModels.Slots;
    using Hims.Shared.UserModels.UserExcel;
    using Newtonsoft.Json;
    using DocumentFormat.OpenXml.Presentation;
    using Org.BouncyCastle.Asn1.Ocsp;

    // ReSharper disable StyleCop.SA1126

    /// <summary>
    /// The patients controller.
    /// </summary>
    [Route("api/patients")]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class PatientsController : BaseController
    {
        /// <summary>
        /// The Auto Mapper
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// the patient service
        /// </summary>
        private readonly IPatientService patientServices;

        /// <summary>
        /// The account services.
        /// </summary>
        private readonly IAccountService accountServices;

        /// <summary>
        /// The patient insurance services.
        /// </summary>
        private readonly IPatientInsuranceService patientInsuranceServices;

        /// <summary>
        /// The patient emergency services.
        /// </summary>
        private readonly IPatientEmergencyService patientEmergencyServices;

        /// <summary>
        /// The document helper.
        /// </summary>
        private readonly IDocumentHelper documentHelper;

        /// <summary>
        /// The AES helper.
        /// </summary>
        private readonly IAESHelper aesHelper;

        /// <summary>
        /// The SMS sender.
        /// </summary>
        private readonly ISMSSender smsSender;

        /// <summary>
        /// The email sender.
        /// </summary>
        private readonly IEmailSender emailSender;

        /// <summary>
        /// The application configuration.
        /// </summary>
        private readonly IApplicationConfiguration applicationConfiguration;

        /// <summary>
        /// The url shortner helper.
        /// </summary>
        private readonly IURLShortnerHelper uRLShortnerHelper;
        /// <summary>
        /// The auditlog services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;

        ///// <summary>
        ///// The ftp configuration.
        ///// </summary>
        //private readonly INewFtpConfiguration newftpConfiguration;

        /// <summary>
        /// the unit of work
        /// </summary>
        private readonly IUnitOfWork unitOfWork;

        /// <summary>
        /// The ftp helper.
        /// </summary>
        private readonly IFtpHelper ftpHelper;

        /// <summary>
        /// The FTP upload helper.
        /// </summary>
        private readonly IFtpUploadHelper ftpUploadHelper;

        /// <summary>
        /// The running environment.
        /// </summary>
        private readonly IRunningEnvironment runningEnvironment;

        /// <summary>
        /// The patient document services.
        /// </summary>
        private readonly IPatientDocumentService patientDocumentServices;

        /// <summary>
        /// The whats application SMS sender
        /// </summary>
        private readonly IWhatsAppSMSSender whatsAppSMSSender;

        /// <summary>
        /// The setting service
        /// </summary>
        private readonly ISettingService settingService;

        /// <inheritdoc />
        public PatientsController(IPatientService patientServices,
            IMapper mapper,
            IAESHelper aesHelper,
            IPatientInsuranceService patientInsuranceServices,
            IPatientEmergencyService patientEmergencyServices,
            IDocumentHelper documentHelper,
            IAccountService accountServices,
            ISMSSender smsSender,
            IEmailSender emailSender,
            IApplicationConfiguration applicationConfiguration,
            IURLShortnerHelper uRLShortnerHelper,
            IAuditLogService auditLogServices,
            //INewFtpConfiguration NewftpConfiguration,
            IUnitOfWork unitOfWork,
            IFtpHelper ftpHelper,
            IFtpUploadHelper ftpUploadHelper, IRunningEnvironment runningEnvironment, IPatientDocumentService patientDocumentServices,
            IWhatsAppSMSSender whatsAppSMSSender,
            ISettingService settingService)
        {
            this.patientServices = patientServices;
            this.mapper = mapper;
            this.aesHelper = aesHelper;
            this.patientInsuranceServices = patientInsuranceServices;
            this.patientEmergencyServices = patientEmergencyServices;
            this.documentHelper = documentHelper;
            this.accountServices = accountServices;
            this.smsSender = smsSender;
            this.emailSender = emailSender;
            this.applicationConfiguration = applicationConfiguration;
            this.uRLShortnerHelper = uRLShortnerHelper;
            this.auditLogServices = auditLogServices;
            //this.newftpConfiguration = NewftpConfiguration;
            this.unitOfWork = unitOfWork;
            this.ftpHelper = ftpHelper;
            this.ftpUploadHelper = ftpUploadHelper;
            this.runningEnvironment = runningEnvironment;
            this.patientDocumentServices = patientDocumentServices;
            this.whatsAppSMSSender = whatsAppSMSSender;
            this.settingService = settingService;
        }

        /// <summary>
        /// To register patient
        /// </summary>
        /// <param name="model" >
        /// The patient registration request Model.
        /// </param>
        /// <returns>
        /// The http status.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Registration successful.
        /// - 409 - Email or Mobile or NPI already exists.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [AllowAnonymous]
        [Route("register")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(OTPResponse), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> RegisterAsync([FromBody] PatientRegistrationModel model)
        {
            model = (PatientRegistrationModel)EmptyFilter.Handler(model);

            if (model.CountryId == null && model.Username.Contains("@"))
            {
                if (string.IsNullOrEmpty(model.Username))
                {
                    return this.BadRequest();
                }

                var email = model.Username;
                var fullName = CoreFilter.FullName(model.FirstName, string.Empty, model.LastName);
                var patientExists = await this.patientServices.CheckPatientAsync(null, null, email, 0);
                if (patientExists == -2)
                {
                    return this.Conflict("Given email address has already been exists with us.");
                }

                if (string.IsNullOrEmpty(model.Password))
                {
                    return this.Success(await this.emailSender.SendOTPAsync(email, fullName));
                }

                var response = await this.patientServices.RegisterAsync(model);
                if (response <= 0)
                {
                    return this.ServerError();
                }

                var mailSent = await this.emailSender.SendPatientWelcomeMailAsync(email, fullName);
                return mailSent
                           ? this.Success(this.MailServerError())
                           : this.Success("Patient has been registered successfully.");
            }
            else
            {
                if (string.IsNullOrEmpty(model.Username) || model.CountryId == null || model.CountryId == 0)
                {
                    return this.BadRequest();
                }

                var mobile = model.Username;
                var countryId = Convert.ToInt32(model.CountryId);
                var fullName = CoreFilter.FullName(model.FirstName, string.Empty, model.LastName);
                var patientExists = await this.patientServices.CheckPatientAsync(mobile, countryId, null, 0);
                if (patientExists == -1)
                {
                    return this.Conflict("Given mobile number has already been exists with us.");
                }

                if (string.IsNullOrEmpty(model.Password))
                {
                    var otp = CoreFilter.RandomNumbers(4);
                    var WhatsAppMessageSetting = await this.settingService.FetchAsync("WhatsAppMsgService", null, null);
                    var WhatsAppMessage = WhatsAppMessageSetting.ToList();
                    if ((bool)WhatsAppMessage[0].Active)
                    {
                        bool Ret = await this.whatsAppSMSSender.SendOTPAsync(mobile, otp);
                    }
                    return this.Success(await this.smsSender.SendOTPAsync(mobile, countryId, otp));
                }

                var response = await this.patientServices.RegisterAsync(model);
                if (response <= 0)
                {
                    return this.ServerError();
                }
                var smsSent = await this.smsSender.SendSMSAsync(mobile, countryId, $"Hi {fullName}, Welcome to {""} - Careaxes. Thank you for being registered with us.", "1207162031726799648");
                return smsSent
                           ? this.Success(this.SMSServerError())
                           : this.Success("Patient has been registered successfully.");
            }
        }

        /// <summary>
        /// To register patient
        /// </summary>
        /// <param name="model" >
        /// The patient registration request Model.
        /// </param>
        /// <returns>
        /// The http status.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Registration successful.
        /// - 409 - Email or Mobile or NPI already exists.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [AllowAnonymous]
        [Route("register-with-out-otp")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(OTPResponse), 200)]
        [ProducesResponseType(409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> RegisterWithOutOtpAsync([FromBody] PatientRegistrationModel model)
        {
            model = (PatientRegistrationModel)EmptyFilter.Handler(model);

            if (model.CountryId == null && model.Username.Contains("@"))
            {
                if (string.IsNullOrEmpty(model.Username))
                {
                    return this.BadRequest();
                }

                var email = model.Username;
                var patientExists = await this.patientServices.CheckPatientAsync(null, null, email, 0);
                if (patientExists == -2)
                {
                    return this.Conflict("Given email address has already been exists with us.");
                }

                var response = await this.patientServices.RegisterWithOutOtpAsync(model);
                if (response <= 0)
                {
                    return this.ServerError();
                }
            }
            else
            {
                if (string.IsNullOrEmpty(model.Username) || model.CountryId == null || model.CountryId == 0)
                {
                    return this.BadRequest();
                }

                var mobile = model.Username;
                var countryId = Convert.ToInt32(model.CountryId);
                var patientExists = await this.patientServices.CheckPatientAsync(mobile, countryId, null, 0);
                if (patientExists == -1)
                {
                    return this.Conflict("Given mobile number has already been exists with us.");
                }

                var response = await this.patientServices.RegisterWithOutOtpAsync(model);
                if (response <= 0)
                {
                    return this.ServerError();
                }
            }

            return this.Success("Patient has been registered successfully.");
        }

        [HttpPost]
        [Authorize]
        [Route("get-raw")]
        public async Task<ActionResult> GetRawAsync([FromBody] EncryptedIdRequest model)
        {
            var id = model.Id ?? 0;
            model = (EncryptedIdRequest)EmptyFilter.Handler(model);
            if (!string.IsNullOrEmpty(model.EncryptedId))
            {
                id = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedId));
            }
            var data = await this.patientServices.GetRawAsync(id);
            return this.Success(data);
        }

        /// <summary>
        /// To find patient
        /// </summary>
        /// <param name="model" >
        /// The patient find request Model.
        /// </param>
        /// <returns>
        /// The patient model.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Patient model.
        /// - 400 - Sorry! We don't have a patient in the system.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Authorize]
        [Route("find")]
        [ProducesResponseType(typeof(PatientModel), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(500)]

        public async Task<ActionResult> FindAsync([FromBody] FindPatientRequest model)
        {
            model = (FindPatientRequest)EmptyFilter.Handler(model);
            var patientId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedPatientId));
            var patient = await this.patientServices.FindAsync(patientId);
            if (patient == null || patient.PatientId == 0)
            {
                return this.BadRequest("Sorry! We don't have a patient in the system.");
            }

            var defaultTimes = ProgressReportHelper.GetDefaultTimes();
            if (patient.PatientId > 0)
            {
                patient.EncryptedPatientId = this.aesHelper.Encode(patient.PatientId.ToString());
                patient.IsDischarged = patient.DischargeId != null;
                patient.BreakfastTime = new TimeModelHelper
                {
                    Hour = patient.Breakfast != null
                    ? patient.Breakfast.Value.Hours
                    : defaultTimes.Morning.Hour,
                    Minute = patient.Breakfast != null
                    ? patient.Breakfast.Value.Minutes
                    : defaultTimes.Morning.Minute
                };
                patient.LunchTime = new TimeModelHelper
                {
                    Hour = patient.Lunch != null
                    ? patient.Lunch.Value.Hours
                    : defaultTimes.Afternoon.Hour,
                    Minute = patient.Lunch != null
                    ? patient.Lunch.Value.Minutes
                    : defaultTimes.Afternoon.Minute
                };
                patient.DinnerTime = new TimeModelHelper
                {
                    Hour = patient.Dinner != null
                    ? patient.Dinner.Value.Hours
                    : defaultTimes.Night.Hour,
                    Minute = patient.Dinner != null
                    ? patient.Dinner.Value.Minutes
                    : defaultTimes.Night.Minute
                };

                patient.Breakfast = null;
                patient.Lunch = null;
                patient.Dinner = null;
            }
            return this.Success(patient);
        }

        /// <summary>
        /// To find patient profile
        /// </summary>
        /// <param name="model" >
        /// The patient find request Model.
        /// </param>
        /// <returns>
        /// The patient model.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Patient profile model.
        /// - 400 - Sorry! We don't have a patient in the system.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [AllowAnonymous]
        [Route("profile")]
        [ProducesResponseType(typeof(PatientProfileModel), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(500)]

        public async Task<ActionResult> FindProfileAsync([FromBody] FindPatientRequest model)
        {
            model = (FindPatientRequest)EmptyFilter.Handler(model);
            var patientId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedPatientId));
            var patient = await this.patientServices.FindAsync(patientId);
            if (patient != null)
            {
                if (patient.ReferredByNameId != null && patient.ReferredByName == null)
                {
                    var referredByType = await this.unitOfWork.ReferenceTypes.FindAsync(x => x.PatientReferredById == patient.PatientReferredById);
                    if (referredByType.Name == "Referral")
                    {
                        var referredByDetails = await this.unitOfWork.ReferralDoctor.FindAsync(x => x.ReferralDoctorId == patient.ReferredByNameId);
                        patient.ReferredByName = referredByDetails.FullName;
                    }
                    else
                    {
                        var referredByDetails = await this.unitOfWork.Providers.FindAsync(x => x.ProviderId == patient.ReferredByNameId);
                        patient.ReferredByName = referredByDetails.FullName;
                    }
                }
            }
            if (patient == null || patient.PatientId == 0)
            {
                return this.BadRequest("Sorry! We don't have a patient in the system.");
            }
            var patientProfile = new PatientProfileModel
            {
                Patient = patient,
                Insurances = await this.patientInsuranceServices.FetchAsync(patient.PatientId),
                EmergencyContacts = await this.patientEmergencyServices.FetchAsync(patient.PatientId),
                RelativeDetails = await this.patientServices.FetchPatientFamilyAsync(patient.PatientId)
            };
            return this.Success(patientProfile);
        }

        /// <summary>
        /// To fetch patients
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The list of patients.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - List of patients.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Authorize]
        [Route("fetch")]
        [ProducesResponseType(typeof(IEnumerable<PatientModel>), 200)]
        [ProducesResponseType(500)]

        public async Task<ActionResult> FetchAsync([FromBody] PatientFilterModel model)
        {
            model = (PatientFilterModel)EmptyFilter.Handler(model);
            var patients = await this.patientServices.FetchAsync(model);
            if (patients == null)
            {
                return this.ServerError();
            }
            foreach (var patient in patients.OrderBy(m => m.PatientId))
            {
                patient.EncryptedPatientId = this.aesHelper.Encode(patient.PatientId.ToString());
            }
            return this.Success(patients);
        }

        /// <summary>
        /// The add patient.
        /// </summary>
        /// <param name="request">
        /// The add request model.
        /// </param>
        /// <param name="header"></param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Patient details has been updated successfully.
        /// - 409 - Patient has already exist with us.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Authorize]
        [Route("add")]
        [Consumes("multipart/form-data")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> AddAsync([FromForm] ModifyPatientRequest request)
        {
            var files = this.Request != null ? this.Request.Form.Files : null;
            request.Files = files;
            request = (ModifyPatientRequest)EmptyFilter.Handler(request);
            request.RelativeDetails = request.RelativeDetails.Count > 0 ? request.RelativeDetails : JsonConvert.DeserializeObject<List<PatientFamilyModel>>(request.Relative);
            var model = this.mapper.Map<PatientModel>(request);
            model.LocationId = (int)request.LocationId;
            model.Email = string.IsNullOrEmpty(model.Email) ? null : model.Email;
            model.FullName = CoreFilter.FullName(model.FirstName, model.MiddleName, model.LastName);
            model.Total = (double)request.PatientTotal;
            model.DiscountInPercentage = request.DiscountPerItem;
            model.DiscountInRupees = request.DiscountPerItemInRupees;
            PatientFamilyModel pfModel = new PatientFamilyModel();
            pfModel.FullName = request.RelationName;
            pfModel.Education = request.RealtiveEducation;
            pfModel.DOB = Convert.ToDateTime(request.RelativeDateOfBirth);
            pfModel.ContactNo = request.RelativeMobile;
            pfModel.RelativeGender = request.RelativeGender;
            pfModel.Relation = request.Relation;
            pfModel.CreatedBy = request.CreatedBy;
            pfModel.CreatedDate = DateTime.UtcNow.AddMinutes(330);
            pfModel.Occupation = request.RelativeOccupation;


            var (accountId, patientId, guid) = await this.patientServices.AddAsync(model, request.EmergencyContacts ?? new List<PatientEmergencyModel>(), request.Insurances ?? new List<PatientInsuranceModel>(), pfModel, request.RelativeDetails ?? new List<PatientFamilyModel>());


            if (accountId > 0)
            {
                var auditLogModel = new AuditLogModel
                {
                    AccountId = model.CreatedBy,
                    LogTypeId = (int)LogTypes.Patient,
                    LogFrom = (short)model.RoleId,
                    LogDate = DateTime.UtcNow.AddMinutes(330),
                    LogDescription = $@"{model.CreatedByName} <b>Registered</b> the Patient:<b>{model.FullName}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                    LocationId = model.LocationId
                };
                await this.auditLogServices.LogAsync(auditLogModel);

                //if (request.PaymentStatus == true && request.Charges != null && request.Charges > 0)
                //{
                //    var logModel = new AuditLogModel
                //    {
                //        AccountId = model.CreatedBy,
                //        LogTypeId = (int)LogTypes.Transaction,
                //        LogFrom = (short)model.RoleId,
                //        LogDate = DateTime.UtcNow.AddMinutes(330),
                //        LogDescription = $@"{model.CreatedByName} Added Patient <b>Payment Transaction</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                //        LocationId = model.LocationId
                //    };
                //    await this.auditLogServices.LogAsync(logModel);

                //    if (request.SalucroStatusCode != 1201)
                //    {
                //        var auditmodel = new AuditLogModel
                //        {
                //            AccountId = model.CreatedBy,
                //            LogTypeId = (int)LogTypes.Receipt,
                //            LogFrom = (short)model.RoleId,
                //            LogDate = DateTime.UtcNow.AddMinutes(330),
                //            LogDescription = $@"{model.CreatedByName} Added Patient <b>Payment Receipt</b> with amount :<b>{request.Charges}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                //            LocationId = model.LocationId
                //        };
                //        await this.auditLogServices.LogAsync(auditmodel);
                //    }
                //}
            }

            switch (accountId)
            {
                case -2:
                    return this.Conflict("Given email address has already been exists with us.");
                case -1:
                    return this.Conflict("Given mobile number has already been exists with us.");
                case 0:
                    return this.ServerError();
            }

            if (!string.IsNullOrEmpty(model.Base64ProfileImage))
            {
                var filePath = $@"{this.runningEnvironment.CurrentEnvironment}/{guid}/ProfileImage";

                try
                {
                    await this.ftpUploadHelper.CreateDirectory(filePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                var dbPath = $@"{model.FullName}_{DateTime.UtcNow.Ticks}.jpg";
                filePath += $@"/{dbPath}";

                try
                {
                    var uploadResponse = await this.ftpUploadHelper.UploadProfileImageAsync(model.Base64ProfileImage, filePath);
                    if (uploadResponse > 0)
                    {
                        model.ProfileImageUrl = $@"ProfileImage/{dbPath}";
                        model.ThumbnailUrl = $@"ProfileImage/{dbPath}";
                        await this.patientServices.UpdateImageUrlsAsync(model, (Guid)guid);
                    }
                }
                catch (Exception e)
                {
                    model.ProfileImageUrl = null;
                    model.ThumbnailUrl = null;
                }
            }

            if (request.FilePaths != null && request.FilePaths.Count > 0)
            {
                var patientDocuments = new List<PatientDocumentModel>();
                var index = 0;
                foreach (var path in request.FilePaths)
                {
                    var tokens = path.Split("/");
                    var fileName = tokens[tokens.Length - 1];
                    var type = fileName.Split("_")[fileName.Split("_").Length - 2];
                    var contentType = "";
                    switch (type)
                    {
                        case "imeg":
                            contentType = "image/jpeg";
                            break;
                        case "impeg":
                            contentType = "image/pjpeg";
                            break;
                        case "imng":
                            contentType = "image/png";
                            break;
                        case "imif":
                            contentType = "image/gif";
                            break;
                        case "apdf":
                            contentType = "application/pdf";
                            break;
                        default:
                            contentType = type;
                            break;
                    }
                    var size = fileName.Split("_")[fileName.Split("_").Length - 3];
                    var filePath = $@"{this.runningEnvironment.CurrentEnvironment}/{guid}/{request.DocumentType}";
                    await this.ftpUploadHelper.CreateDirectory(filePath);
                    request.DocumentName = index == 0 ? request.DocumentName : $"{request.DocumentName}_{index}";
                    var dbPath = $@"{request.DocumentName}_{DateTime.UtcNow.Ticks}{Path.GetExtension(fileName)}";
                    filePath += $@"/{dbPath}";

                    try
                    {
                        var response = await this.ftpUploadHelper.Rename(path, filePath);
                        if (response)
                        {
                            var documentModel = new PatientDocumentModel
                            {
                                DocumentType = request.DocumentType,
                                Description = request.Description,
                                DocumentName = index == 0 ? request.DocumentName : $"{request.DocumentName}_{index}",
                                UploadedBy = request.CreatedBy,
                                PatientId = (int)patientId,
                                ContentType = contentType,
                                Size = float.Parse(size)
                            };
                            documentModel.ThumbnailUrl = this.documentHelper.GetThumbnail(contentType);
                            documentModel.DocumentUrl = dbPath;
                            patientDocuments.Add(documentModel);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                    index++;
                }
                await this.patientDocumentServices.AddAsync(patientDocuments);

                //delete temp folder 
                //var fileTokens = new ArrayList(request.FilePaths[0].Split("/"));

                //fileTokens.RemoveAt(fileTokens.Count - 1);
                //fileTokens.RemoveAt(fileTokens.Count - 1);

                //var fileJoinedStringResult = string.Join("/", fileTokens.ToArray());

                //await this.ftpUploadHelper.DeleteDirectory(fileJoinedStringResult);
            }
            if (request.Files != null && request.Files.Count > 0)
            {
                var patientDocuments = new List<PatientDocumentModel>();
                var index = 0;
                foreach (var file in request.Files)
                {
                    var docModel = new PatientDocumentModel
                    {
                        DocumentType = request.DocumentType,
                        Description = request.Description,
                        DocumentName = index == 0 ? request.DocumentName : $"{request.DocumentName}_{index}",
                        UploadedBy = request.CreatedBy,
                        PatientId = (int)patientId,
                        ContentType = file.ContentType,
                        Size = file.Length
                    };

                    var filePath = $@"{this.runningEnvironment.CurrentEnvironment}/{guid}/{request.DocumentType}";

                    try
                    {
                        await this.ftpUploadHelper.CreateDirectory(filePath);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                    request.DocumentName = index == 0 ? request.DocumentName : $"{request.DocumentName}_{index}";
                    var dbPath = $@"{request.DocumentName}_{DateTime.UtcNow.Ticks}{Path.GetExtension(file.FileName)}";
                    filePath += $@"/{dbPath}";

                    var uploadResponse = await this.ftpUploadHelper.UploadFromFileAsync(filePath, file);
                    if (uploadResponse <= 0)
                    {
                        return this.ServerError("Unable to upload the document");
                    }
                    docModel.ThumbnailUrl = this.documentHelper.GetThumbnail(file.ContentType);
                    docModel.DocumentUrl = dbPath;
                    patientDocuments.Add(docModel);
                    index++;
                }
                await this.patientDocumentServices.AddAsync(patientDocuments);
            }

            // var encryptedAccountId = this.aesHelper.Encode(accountId.ToString());
            // var createPasswordLink = this.applicationConfiguration.CreatePasswordLink + encryptedAccountId;

            //var shortnerUrl = await this.uRLShortnerHelper.MakeShorterUrl(createPasswordLink);

            //if (!string.IsNullOrEmpty(model.Email))
            //{
            //    var response = await this.emailSender.SendWelcomeMailAsync(model.Email, model.FullName, null, createPasswordLink);
            //    return response ? this.Success(patientId) : this.Success(this.MailServerError());
            //}
            //else if (!string.IsNullOrEmpty(model.Mobile))
            //{
            //    try
            //    {

            //        var smsSent = await this.smsSender.SendWelcomeMessageAsync(model.Mobile, model.FullName, null, shortnerUrl, Convert.ToInt32(model.CountryId));
            //        return smsSent ? this.Success(patientId) : this.ServerError("Patient added but unable to send SMS");
            //    }
            //    catch (Exception e)
            //    {
            //        //ignore
            //    }
            //}
            // return this.Success(patientId);
            return this.Success(new GenericResponse
            {
                Status = GenericStatus.Success,
                Data = patientId
            });
        }

        /// <summary>
        /// The update patient.
        /// </summary>
        /// <param name="request">
        /// The update request model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Patient details has been updated successfully.
        /// - 409 - Patient has already exist with us.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Authorize]
        [Route("update")]
        [Consumes("multipart/form-data")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> UpdateAsync([FromForm] ModifyPatientRequest request)
        {
            var files = this.Request != null ? this.Request.Form.Files : null;
            request.Files = files;
            request = (ModifyPatientRequest)EmptyFilter.Handler(request);
            request.RelativeDetails = request.RelativeDetails.Count > 0 ? request.RelativeDetails : JsonConvert.DeserializeObject<List<PatientFamilyModel>>(request.Relative);
            // request.LocationId = int.Parse(header.LocationId);// removed becx we have to call for salucro from there  we cant pass location id/
            var model = this.mapper.Map<PatientModel>(request);
            model.Email = !string.IsNullOrEmpty(request.Email) ? request.Email : null;
            model.FullName = CoreFilter.FullName(model.FirstName, model.MiddleName, model.LastName);
            model.Total = (double)request.PatientTotal;
            model.DiscountInPercentage = request.DiscountPerItem;
            model.DiscountInRupees = request.DiscountPerItemInRupees;
            PatientFamilyModel pfModel = new PatientFamilyModel();
            pfModel.FullName = request.RelationName;
            pfModel.PatientFamilyId = await this.patientServices.FetchPatientFamilyIdAsync(request.PatientId);
            pfModel.Education = request.RealtiveEducation;
            pfModel.ContactNo = request.RelativeMobile;
            pfModel.RelativeGender = request.RelativeGender;
            pfModel.Relation = request.Relation;

            pfModel.CreatedBy = request.CreatedBy;
            pfModel.CreatedDate = DateTime.UtcNow.AddMinutes(330);
            pfModel.Occupation = request.RelativeOccupation;

            var checkReferralCode = !string.IsNullOrEmpty(model.ReferralCode) ? await this.patientServices.VerifyReferralCodeAsync(model.ReferralCode) : true;
            if (!checkReferralCode) { return this.Conflict("Given referral code is invalid"); }

            if (!string.IsNullOrEmpty(model.Base64ProfileImage))
            {
                var imageModel = new UpdatePatientProfileImageRequest
                {
                    PatientId = request.PatientId,
                    Image = model.Base64ProfileImage
                };
                await this.UpdateProfileImageAsync(imageModel);
            }
            var patient = await this.unitOfWork.Patients.FindAsync(x => x.PatientId == request.PatientId);
            var response = await this.patientServices.UpdateAsync(model, request.EmergencyContacts ?? new List<PatientEmergencyModel>(), request.Insurances ?? new List<PatientInsuranceModel>(), pfModel, request.RelativeDetails ?? new List<PatientFamilyModel>());
            if (response > 0)
            {
                if (request.FilePaths != null && request.FilePaths.Count > 0)
                {
                    var patientDocuments = new List<PatientDocumentModel>();
                    var index = 0;
                    foreach (var path in request.FilePaths)
                    {
                        var tokens = path.Split("/");
                        var fileName = tokens[tokens.Length - 1];
                        var type = fileName.Split("_")[fileName.Split("_").Length - 2];
                        var contentType = "";
                        switch (type)
                        {
                            case "imeg":
                                contentType = "image/jpeg";
                                break;
                            case "impeg":
                                contentType = "image/pjpeg";
                                break;
                            case "imng":
                                contentType = "image/png";
                                break;
                            case "imif":
                                contentType = "image/gif";
                                break;
                            case "apdf":
                                contentType = "application/pdf";
                                break;
                            default:
                                contentType = type;
                                break;
                        }
                        var size = fileName.Split("_")[fileName.Split("_").Length - 3];
                        var filePath = $@"{this.runningEnvironment.CurrentEnvironment}/{patient.Guid}/{request.DocumentType}";
                        await this.ftpUploadHelper.CreateDirectory(filePath);
                        request.DocumentName = index == 0 ? request.DocumentName : $"{request.DocumentName}_{index}";
                        var dbPath = $@"{request.DocumentName}_{DateTime.UtcNow.Ticks}{Path.GetExtension(fileName)}";
                        filePath += $@"/{dbPath}";

                        try
                        {
                            var res = await this.ftpUploadHelper.Rename(path, filePath);
                            if (res)
                            {
                                var documentModel = new PatientDocumentModel
                                {
                                    DocumentType = request.DocumentType,
                                    Description = request.Description,
                                    DocumentName = index == 0 ? request.DocumentName : $"{request.DocumentName}_{index}",
                                    UploadedBy = request.CreatedBy,
                                    PatientId = request.PatientId,
                                    ContentType = contentType,
                                    Size = float.Parse(size)
                                };
                                documentModel.ThumbnailUrl = this.documentHelper.GetThumbnail(contentType);
                                documentModel.DocumentUrl = dbPath;
                                patientDocuments.Add(documentModel);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw;
                        }
                        index++;
                    }
                    await this.patientDocumentServices.AddAsync(patientDocuments);

                    //delete temp folder 
                    //var fileTokens = new ArrayList(request.FilePaths[0].Split("/"));

                    //fileTokens.RemoveAt(fileTokens.Count - 1);
                    //fileTokens.RemoveAt(fileTokens.Count - 1);

                    //var fileJoinedStringResult = string.Join("/", fileTokens.ToArray());

                    //await this.ftpUploadHelper.DeleteDirectory(fileJoinedStringResult);
                }
                if (request.Files != null && request.Files.Count > 0)
                {
                    var patientDocuments = new List<PatientDocumentModel>();
                    var index = 0;
                    foreach (var file in request.Files)
                    {
                        var docModel = new PatientDocumentModel
                        {
                            DocumentType = request.DocumentType,
                            Description = request.Description,
                            DocumentName = index == 0 ? request.DocumentName : $"{request.DocumentName}_{index}",
                            UploadedBy = request.CreatedBy,
                            PatientId = request.PatientId,
                            ContentType = file.ContentType,
                            Size = file.Length
                        };

                        var filePath = $@"{this.runningEnvironment.CurrentEnvironment}/{patient.Guid}/{request.DocumentType}";

                        try
                        {
                            await this.ftpUploadHelper.CreateDirectory(filePath);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                        request.DocumentName = index == 0 ? request.DocumentName : $"{request.DocumentName}_{index}";
                        var dbPath = $@"{request.DocumentName}_{DateTime.UtcNow.Ticks}{Path.GetExtension(file.FileName)}";
                        filePath += $@"/{dbPath}";

                        var uploadResponse = await this.ftpUploadHelper.UploadFromFileAsync(filePath, file);
                        if (uploadResponse <= 0)
                        {
                            return this.ServerError("Unable to upload the document");
                        }
                        docModel.ThumbnailUrl = this.documentHelper.GetThumbnail(file.ContentType);
                        docModel.DocumentUrl = dbPath;
                        patientDocuments.Add(docModel);
                        index++;
                    }
                    await this.patientDocumentServices.AddAsync(patientDocuments);
                }
            }
            switch (response)
            {
                case -2:
                    return this.Conflict("Given email address has already been exists with us.");
                case -1:
                    return this.Conflict("Given mobile number has already been exists with us.");
                case 0:
                    return this.ServerError();
                default:
                    if (response > 0)
                    {
                        try
                        {
                            var auditLogModel = new AuditLogModel
                            {
                                AccountId = model.ModifiedBy,
                                LogTypeId = (int)LogTypes.Patient,
                                LogFrom = (short)model.RoleId,
                                LogDate = DateTime.UtcNow.AddMinutes(330),
                                LogDescription = $@"{model.ModifiedByName} <b>Updated</b> the Patient:<b>{model.FullName}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                                LocationId = model.LocationId
                            };
                            await this.auditLogServices.LogAsync(auditLogModel);

                            //if (patient.PaymentStatus!=true && request.TotalAmount != null && request.TotalAmount > 0)
                            //{
                            //    var logModel = new AuditLogModel
                            //    {
                            //        AccountId = model.ModifiedBy,
                            //        LogTypeId = (int)LogTypes.Transaction,
                            //        LogFrom = (short)model.RoleId,
                            //        LogDate = DateTime.UtcNow.AddMinutes(330),
                            //        LogDescription = $@"{model.ModifiedByName} Added Patient <b>Payment Transaction</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                            //        LocationId = model.LocationId
                            //    };
                            //    await this.auditLogServices.LogAsync(logModel);

                            //    if (request.SalucroStatusCode != 1201)
                            //    {
                            //        var auditmodel = new AuditLogModel
                            //        {
                            //            AccountId = model.ModifiedBy,
                            //            LogTypeId = (int)LogTypes.Receipt,
                            //            LogFrom = (short)model.RoleId,
                            //            LogDate = DateTime.UtcNow.AddMinutes(330),
                            //            LogDescription = $@"{model.ModifiedByName} Added Patient <b>Payment Receipt</b> with amount :<b>{request.TotalAmount}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                            //            LocationId = model.LocationId
                            //        };
                            //        await this.auditLogServices.LogAsync(auditmodel);
                            //    }
                            //}
                        }
                        catch (Exception)
                        {
                            // ignore
                        }
                    }
                    // return this.Success("Patient details has been updated successfully.");                  
                    return this.Success(new GenericResponse
                    {
                        Status = GenericStatus.Success,

                    });
            }
        }

        /// <summary>
        /// The update patient.
        /// </summary>
        /// <param name="request">
        /// The update request model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Patient details has been updated successfully.
        /// - 409 - Patient has already exist with us.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Authorize]
        [Route("update-patient-details")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> UpdatePatientDetailsAsync([FromBody] ModifyPatientRequest request, [FromHeader] LocationHeader header)
        {
            request = (ModifyPatientRequest)EmptyFilter.Handler(request);
            var model = this.mapper.Map<PatientModel>(request);
            model.Email = !string.IsNullOrEmpty(request.Email) ? request.Email : null;
            model.FullName = CoreFilter.FullName(model.FirstName, model.MiddleName, model.LastName);

            PatientFamilyModel pfModel = new PatientFamilyModel();
            pfModel.FullName = request.RelationName;
            pfModel.PatientFamilyId = await this.patientServices.FetchPatientFamilyIdAsync(request.PatientId);
            pfModel.Education = request.RealtiveEducation;
            pfModel.ContactNo = request.RelativeMobile;
            pfModel.RelativeGender = request.RelativeGender;
            pfModel.Relation = request.Relation;

            pfModel.CreatedBy = request.CreatedBy;
            pfModel.CreatedDate = DateTime.UtcNow.AddMinutes(330);
            pfModel.Occupation = request.RelativeOccupation;


            var response = await this.patientServices.UpdatePatientDetailsAsync(model, pfModel);
            switch (response)
            {
                case -2:
                    return this.Conflict("Given email address has already been exists with us.");
                case -1:
                    return this.Conflict("Given mobile number has already been exists with us.");
                case 0:
                    return this.ServerError();
                default:
                    if (response > 0)
                    {
                        try
                        {
                            var auditLogModel = new AuditLogModel
                            {
                                AccountId = model.ModifiedBy,
                                LogTypeId = (int)LogTypes.Patient,
                                LogFrom = (short)model.RoleId,
                                LogDate = DateTime.UtcNow.AddMinutes(330),
                                LogDescription = $@"{model.ModifiedByName} <b>Updated</b> the Patient:<b>{model.FullName}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                                LocationId = Convert.ToInt32(header.LocationId)
                            };
                            await this.auditLogServices.LogAsync(auditLogModel);
                        }
                        catch (Exception)
                        {
                            // ignore
                        }
                    }
                    // return this.Success("Patient details has been updated successfully.");                  
                    return this.Success(response);
            }
        }
        /// <summary>
        /// The edit async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPut]
        [Authorize]
        [Route("edit")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> EditAsync([FromBody] EditPatientModel model)
        {
            model = (EditPatientModel)EmptyFilter.Handler(model);
            model.FullName = CoreFilter.FullName(model.FirstName, string.Empty, model.LastName);

            var response = await this.patientServices.EditAsync(model);
            switch (response)
            {
                case -3:
                    return this.Conflict("Invalid referral code.");
                case -2:
                    return this.Conflict("Given email address has already been exists with us.");
                case -1:
                    return this.Conflict("Given mobile number has already been exists with us.");
                case 0:
                    return this.ServerError();
                default:
                    return this.Success("Patient details has been updated successfully.");
            }
        }

        /// <summary>
        /// The update patient profile image.
        /// </summary>
        /// <param name="model">
        /// The update patient profile image request model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Patient profile image has been updated successfully.
        /// - 400 - No image found.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPut]
        [Authorize]
        [Route("update-profile-image")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 400)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> UpdateProfileImageAsync([FromBody] UpdatePatientProfileImageRequest model)
        {
            model = (UpdatePatientProfileImageRequest)EmptyFilter.Handler(model);

            if (string.IsNullOrEmpty(model.Image))
            {
                return this.BadRequest("No profile image found. Please try again.");
            }
            var patientModel = new PatientModel
            {
                PatientId = model.PatientId,
                ProfileImageUrl = model.Image
            };
            var path = await this.unitOfWork.Patients.FindAsync(m => m.PatientId == model.PatientId);

            if (!string.IsNullOrEmpty(patientModel.ProfileImageUrl))
            {
                var filePath = $@"{this.runningEnvironment.CurrentEnvironment}/{path.Guid}/ProfileImage";

                try
                {
                    await this.ftpUploadHelper.CreateDirectory(filePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                var dbPath = $@"{path.FullName}_{DateTime.UtcNow.Ticks}.jpg";
                filePath += $@"/{dbPath}";

                try
                {
                    var uploadResponse = await this.ftpUploadHelper.UploadProfileImageAsync(patientModel.ProfileImageUrl, filePath);
                    if (uploadResponse > 0)
                    {
                        patientModel.ProfileImageUrl = $@"ProfileImage/{dbPath}";
                        patientModel.ThumbnailUrl = $@"ProfileImage/{dbPath}";
                        if (!string.IsNullOrEmpty(path.ProfileImageUrl))
                        {
                            var imageFullPath = $@"{this.runningEnvironment.CurrentEnvironment}/{path.Guid}/{path.ProfileImageUrl}";
                            await this.ftpUploadHelper.DeleteFile(imageFullPath);
                        }
                    }
                }
                catch (Exception)
                {
                    patientModel.ProfileImageUrl = null;
                    patientModel.ThumbnailUrl = null;
                }
            }
            var response = await this.patientServices.UpdateImageUrlsAsync(patientModel, path.Guid);
            return response switch
            {
                0 => this.ServerError(),
                _ => this.Success("uploaded"),
            };
        }
        /// <summary>
        /// The modify status async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPut]
        [Authorize]
        [Route("modify-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ModifyStatusAsync([FromBody] PatientModel request)
        {
            var model = this.mapper.Map<PatientModel>(request);

            model.PatientId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedPatientId));

            var response = await this.patientServices.ModifyStatusAsync(model);
            switch (response)
            {
                case 0:
                    return this.ServerError();
                default:
                    return this.Success("Patient " + (request.Active ? "activated" : "deactivated") + " successfully.");
            }
        }

        /// <summary>
        /// The locked status async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPut]
        [Authorize]
        [Route("lock-status")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> LockedStatusAsync([FromBody] PatientModel request)
        {
            var model = this.mapper.Map<PatientModel>(request);

            model.PatientId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedPatientId));

            var response = await this.patientServices.LockedStatusAsync(model);
            switch (response)
            {
                case 0:
                    return this.ServerError();
                default:
                    return this.Success("Patient has been " + (request.IsLocked == true ? "locked" : "Unlock") + " successfully.");
            }
        }

        /// <summary>
        /// The add family member.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.add-member
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("add-member")]
        public async Task<ActionResult> AddFamilyMember([FromBody] PatientFamilyModel request, [FromHeader] LocationHeader header)
        {
            request = (PatientFamilyModel)EmptyFilter.Handler(request);
            if (!string.IsNullOrEmpty(request.EncryptedPatientId))
            {
                request.PatientId = Convert.ToInt32(this.aesHelper.Decode(request.EncryptedPatientId));
            }
            var response = await this.patientServices.AddFamilyMember(request);
            var auditLogModel = new AuditLogModel
            {
                AccountId = request.CreatedBy,
                LogTypeId = (int)LogTypes.Patient,
                LogFrom = (short)request.RoleId,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $@"<b>{request.CreatedByName} </b>has Added the Family Member:<b>{request.FullName}</b> of Patient:<b>{request.PatientName}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                LocationId = Convert.ToInt32(header.LocationId)

            };
            await this.auditLogServices.LogAsync(auditLogModel);
            return this.Success(response);
        }

        /// <summary>
        /// The fetch family members.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("fetch-family-member")]
        public async Task<ActionResult> FetchFamilyMembers([FromBody] PatientFamilyModel request)
        {
            request = (PatientFamilyModel)EmptyFilter.Handler(request);
            if (!string.IsNullOrEmpty(request.EncryptedPatientId))
            {
                request.PatientId = Convert.ToInt32(this.aesHelper.Decode(request.EncryptedPatientId));
            }
            //            var response = await this.patientServices.FetchFamilyMembers(request.PatientId);

            var response = await this.patientServices.FetchFamilyMembers((int)request.PatientId);
            return this.Success(response);
        }

        /// <summary>
        /// The update family member.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("update-family-member")]
        public async Task<ActionResult> UpdateFamilyMember([FromBody] PatientFamilyModel request, [FromHeader] LocationHeader header)
        {
            request = (PatientFamilyModel)EmptyFilter.Handler(request);
            if (!string.IsNullOrEmpty(request.EncryptedPatientId))
            {
                request.PatientId = Convert.ToInt32(this.aesHelper.Decode(request.EncryptedPatientId));
            }
            var response = await this.patientServices.UpdateFamilyMembers(request);
            var auditLogModel = new AuditLogModel
            {
                AccountId = request.ModifiedBy,
                LogTypeId = (int)LogTypes.Patient,
                LogFrom = (short)request.RoleId,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $@"<b>{request.ModifiedByName} </b>has Updated the Family Member:<b>{request.FullName}</b> of Patient:<b>{request.PatientName}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);
            return this.Success(response);
        }

        /// <summary>
        /// The delete family member.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("delete-family-member")]
        public async Task<ActionResult> DeleteFamilyMember([FromBody] PatientFamilyModel request, [FromHeader] LocationHeader header)
        {
            request = (PatientFamilyModel)EmptyFilter.Handler(request);
            if (!string.IsNullOrEmpty(request.EncryptedPatientId))
            {
                request.PatientId = Convert.ToInt32(this.aesHelper.Decode(request.EncryptedPatientId));
            }
            var response = await this.patientServices.DeleteFamilyMember(request);
            var auditLogModel = new AuditLogModel
            {
                AccountId = request.ModifiedBy,
                LogTypeId = (int)LogTypes.Patient,
                LogFrom = (short)request.RoleId,
                LogDate = DateTime.UtcNow.AddMinutes(330),
                LogDescription = $@"<b>{request.ModifiedByName}</b> has deleted the Family Member:<b>{request.FullName}</b> of Patient:<b>{request.PatientName}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                LocationId = Convert.ToInt32(header.LocationId)
            };
            await this.auditLogServices.LogAsync(auditLogModel);
            return this.Success(response);
        }

        /// <summary>
        /// The modify status async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPut]
        [Authorize]
        [Route("manual-verify")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> ManualVerifyAsync([FromBody] PatientModel request)
        {
            var model = this.mapper.Map<PatientModel>(request);

            model.PatientId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedPatientId));

            var response = await this.patientServices.ManualVerifyAsync(model);
            switch (response)
            {
                case 0:
                    return this.ServerError();
                default:
                    return this.Success("Updated successfully.");
            }
        }

        /// <summary>
        /// The locked status async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPut]
        [AllowAnonymous]
        [Route("check-user")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindPatientAsync([FromBody] LoginRequest model)
        {
            model = (LoginRequest)EmptyFilter.Handler(model);

            var accountInfo = await this.accountServices.GetAccountDetailAsync(model.Username, string.Join(",", model.AccountTypes.Select(m => (int)m)));
            ObjectResult otpResponse = null;
            if (accountInfo == null)
            {
                var data = new PatientRegistrationModel
                {
                    Username = model.Username.Split(":")[1],
                    CountryId = Convert.ToInt32(model.Username.Split(":")[0])
                };

                await this.patientServices.RegisterWithOutOtpAsync(data);

                var mobile = model.Username.Split(":")[1];
                var countryId = Convert.ToInt32(model.Username.Split(":")[0]);
                var otp = CoreFilter.RandomNumbers(4);
                var WhatsAppMessageSetting = await this.settingService.FetchAsync("WhatsAppMsgService", null, null);
                var WhatsAppMessage = WhatsAppMessageSetting.ToList();
                if ((bool)WhatsAppMessage[0].Active)
                {
                    bool Ret = await this.whatsAppSMSSender.SendOTPAsync(mobile, otp);
                }
                otpResponse = this.Success(await this.smsSender.SendOTPAsync(mobile, countryId, otp));
            }

            accountInfo = await this.accountServices.GetAccountDetailAsync(model.Username, string.Join(",", model.AccountTypes.Select(m => (int)m)));

            return this.Success(new { EncryptedAccountId = accountInfo != null ? this.aesHelper.Encode(accountInfo.AccountId.ToString()) : null, AccountId = accountInfo != null ? accountInfo.AccountId : (int?)null, ManualVerified = accountInfo != null ? accountInfo.ManualVerified : null, PasswordExist = accountInfo != null ? accountInfo.PasswordExist : null, OTPResponse = otpResponse?.Value });
        }


        /// <summary>
        /// The locked status async.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPut]
        [AllowAnonymous]
        [Route("check-user-list")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FindPatientListAsync([FromBody] LoginRequest model)
        {
            model = (LoginRequest)EmptyFilter.Handler(model);
            var accountInfo = await this.accountServices.GetPatientAccountDetailListAsync(model.Mobile, string.Join(",", model.AccountTypes.Select(m => (int)m)), model.Username);
            ObjectResult otpResponse = null;
            var length = accountInfo.Count();
            if (length == 0 && model.Username.Contains(":") && !model.Username.ToLower().Contains("umr"))
            {
                var data = new PatientRegistrationModel
                {
                    Username = model.Username.Split(":")[1],
                    CountryId = Convert.ToInt32(model.Username.Split(":")[0])
                };

                await this.patientServices.RegisterWithOutOtpAsync(data);

                var mobile = model.Username.Split(":")[1];
                var countryId = Convert.ToInt32(model.Username.Split(":")[0]);
                var otp = CoreFilter.RandomNumbers(4);
                var WhatsAppMessageSetting = await this.settingService.FetchAsync("WhatsAppMsgService", null, null);
                var WhatsAppMessage = WhatsAppMessageSetting.ToList();
                if ((bool)WhatsAppMessage[0].Active)
                {
                    bool Ret = await this.whatsAppSMSSender.SendOTPAsync(mobile, otp);
                }
                otpResponse = this.Success(await this.smsSender.SendOTPAsync(mobile, countryId, otp));
            }
            accountInfo = await this.accountServices.GetPatientAccountDetailListAsync(model.Mobile, string.Join(",", model.AccountTypes.Select(m => (int)m)), model.Username);
            if (accountInfo != null && accountInfo.Count() != 0)
                return this.Success(new Tuple<IEnumerable<AccountModel>, OTPResponse>(accountInfo, otpResponse != null ? (OTPResponse)(otpResponse?.Value) : null));
            else
                return this.ServerError("User does not exists");
            //return this.Success(new { accountInfo, OTPResponse = otpResponse?.Value });
        }

        /// <summary>
        /// The modify status async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Authorize]
        [Route("get-referral-code")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> GetReferralCodeAsync([FromBody] PatientModel request)
        {
            var model = this.mapper.Map<PatientModel>(request);

            model.PatientId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedPatientId));

            var response = await this.patientServices.GetReferralCodeAsync(model.PatientId);
            return this.Success(response);
        }

        /// <summary>
        /// The modify status async.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [AllowAnonymous]
        [Route("verify-referral-code")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(typeof(string), 409)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> VerifyReferralCodeAsync([FromBody] PatientModel request)
        {
            var model = this.mapper.Map<PatientModel>(request);

            var response = await this.patientServices.VerifyReferralCodeAsync(model.ReferralCode);
            return this.Success(response);
        }

        /// <summary>
        /// To send refer to mobile.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The OTP <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - OTP send to email/mobile successful.
        /// - 400 - Invalid email/mobile.
        /// - 500 - Problem with Email/SMS server or server side code.
        /// </remarks>
        [HttpPost]
        [AllowAnonymous]
        [Route("send-referral-link")]
        [ProducesResponseType(typeof(string), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(500)]
        public async Task<ActionResult> SendReferralLinkAsync([FromBody] ReferralRequest model)
        {
            model = (ReferralRequest)EmptyFilter.Handler(model);
            if (string.IsNullOrEmpty(model.ReferralCode))
            {
                model.ReferralCode = await this.patientServices.GetReferralCodeAsync(model.PatientId);
            }
            var link = !string.IsNullOrEmpty(model.ReferralCode) ? $"{this.applicationConfiguration.AndroidAppLink}&referrer={model.ReferralCode}" : $"{this.applicationConfiguration.AndroidAppLink}";
            var response = await this.smsSender.SendReferralCodeSMSAsync(model.Username, model.CountryId, model.ReferralCode, model.FullName, link);
            return response ? this.Success("Referral Link Sent Successfully.") : this.BadRequest("We are Sorry! Something Error");
        }

        /// <summary>
        /// Modifies the patientregistration charge asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="location">The location.</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [Route("modify-registration-charge")]
        public async Task<ActionResult> ModifyPatientregistrationChargeAsync([FromBody] PatientRegistrationChargeModel model, [FromHeader] LocationHeader location)
        {
            model = (PatientRegistrationChargeModel)EmptyFilter.Handler(model);
            model.LocationId = !string.IsNullOrEmpty(location.LocationId) ? int.Parse(location.LocationId) : (int?)null;
            var response = await this.patientServices.ModifyPatientRegistrationCharge(model);
            switch (response)
            {
                case -1:
                    return this.Success(-1);
                //return this.Conflict("Given Charge already exists.");
                case 0:
                    return this.ServerError();
            }
            return this.Success(response);

        }

        /// <summary>
        /// Fetches the patient registration charge asynchronous.
        /// </summary>
        /// <param name="location">The location.</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [Route("fetch-registration-charge")]
        public async Task<ActionResult> FetchPatientRegistrationChargeAsync([FromHeader] LocationHeader location)
        {
            var response = await this.patientServices.FetchRegistrationChargesAsync(int.Parse(location.LocationId));
            return this.Success(response);
        }

        /// <summary>
        /// Fetches the patient registration charge asynchronous.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="location"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Route("apply-registration-charge")]
        public async Task<ActionResult> FetchPatientRegistrationChargeAsync(int id, [FromHeader] LocationHeader location)
        {
            var response = await this.patientServices.ApplyRegistrationAsync(id, int.Parse(location.LocationId));
            return this.Success(response);
        }

        /// <summary>
        /// Fetches the patient registration charge asynchronous.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Route("fetch-registration-bill")]
        public async Task<ActionResult> FetchPatientRegistrationBillAsync(int id)
        {
            var response = await this.patientServices.FetchPatientRegistrationBillAsync(id);
            return this.Success(response);
        }

        [HttpGet]
        [Authorize]
        [Route("fetch-registration-bill-with-relative")]
        public async Task<ActionResult> FetchPatientRegistrationBillWithRelativeAsync(int id)
        {
            var response = await this.patientServices.FetchPatientRegistrationBillForRelativePatient(id);
            return this.Success(response);
        }

        /// <summary>
        /// Adds the unidentified patient.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="header">The header.</param>
        /// <returns></returns>
        [HttpPost]
        [HttpPost]
        [Authorize]
        [Route("add-unidentified-patient")]
        [Consumes("multipart/form-data")]
        public async Task<ActionResult> AddUnidentifiedPatient([FromForm] ModifyPatientRequest request)
        {
            request ??= new ModifyPatientRequest();
            // request.LocationId = !string.IsNullOrEmpty(header.LocationId) ? int.Parse(header.LocationId) : 0;
            // request.LocationId =  getting from front End , passing fron where its called.
            var model = this.mapper.Map<PatientModel>(request);
            model.Total = (double)request.PatientTotal;
            //model.Amount = request.Charges;
            model.DiscountInPercentage = request.DiscountPerItem;
            model.DiscountInRupees = request.DiscountPerItemInRupees;
            var (response, guid) = await this.patientServices.AddUnidentifiedPatientAsync(model);
            try
            {
                if (response > 0)
                {
                    var auditLogModel = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.Patient,
                        LogFrom = (short)model.RoleId,
                        LogDate = DateTime.UtcNow.AddMinutes(330),
                        LogDescription = $@"{model.CreatedByName} <b>Added</b> new unidentified Patient on {DateTime.UtcNow.AddMinutes(330):MM/dd/yyyy hh:mm tt}",
                        LocationId = request.LocationId
                    };
                    await this.auditLogServices.LogAsync(auditLogModel);

                    if (request.PaymentStatus == true && request.Charges != null && request.Charges > 0)
                    {
                        var logModel = new AuditLogModel
                        {
                            AccountId = model.CreatedBy,
                            LogTypeId = (int)LogTypes.Transaction,
                            LogFrom = (short)model.RoleId,
                            LogDate = DateTime.UtcNow.AddMinutes(330),
                            LogDescription = $@"{model.CreatedByName} Added Patient <b>Payment Transaction</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                            LocationId = model.LocationId
                        };
                        await this.auditLogServices.LogAsync(logModel);

                        if (request.SalucroStatusCode != 1201)
                        {
                            var auditmodel = new AuditLogModel
                            {
                                AccountId = model.CreatedBy,
                                LogTypeId = (int)LogTypes.Receipt,
                                LogFrom = (short)model.RoleId,
                                LogDate = DateTime.UtcNow.AddMinutes(330),
                                LogDescription = $@"{model.CreatedByName} Added Patient <b>Payment Receipt</b> with amount :<b>{request.Charges}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                                LocationId = model.LocationId
                            };
                            await this.auditLogServices.LogAsync(auditmodel);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //ignore
                Console.WriteLine(guid);
            }

            // return this.Success(response);
            return this.Success(new GenericResponse
            {
                Status = GenericStatus.Success,
                Data = response
            });
        }

        /// <summary>
        /// The fetch all notification types.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        ///// </returns>
        [HttpGet]
        [Route("patient-registration-charges")]
        [ProducesResponseType(200, Type = typeof(List<Resource>))]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchPatientRegistrationCharges([FromHeader] LocationHeader header)
        {
            var resources = await this.patientServices.FetchPatientRegistrationCharges(Convert.ToInt32(header.LocationId));
            return this.Success(resources);
        }

        /// <summary>
        /// The fetch all notification types.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        ///// </returns>
        [HttpGet]
        [Route("registration-charges")]
        [ProducesResponseType(200, Type = typeof(List<Resource>))]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchRegistrationCharges(int locationId)
        {
            var resources = await this.patientServices.FetchPatientRegistrationCharges(locationId);
            return this.Success(resources);
        }

        [HttpPost]
        [Route("fetch-anc-card")]
        [ProducesResponseType(200, Type = typeof(List<Resource>))]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchANCCard([FromBody] FindPatientRequest model)
        {
            model = (FindPatientRequest)EmptyFilter.Handler(model);
            var patientId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedPatientId));
            var patientDetails = await this.patientServices.FindAsync(patientId);
            var response = await this.patientServices.FetchANCCard(patientId);
            if (response == null || response.Count() == 0)
            {
                return this.BadRequest("Sorry! We don't have a patient in the system.");
            }
            return this.Success(new Tuple<IEnumerable<ANCCardGenerationModel>, PatientModel>(response, patientDetails));
        }
        [HttpPost]
        [Route("patient-timeline")]
        [ProducesResponseType(200, Type = typeof(List<Resource>))]
        [ProducesResponseType(500)]
        public async Task<ActionResult> FetchPatientTimeLine([FromBody] FindPatientRequest request)
        {
            request = (FindPatientRequest)EmptyFilter.Handler(request);
            var patientId = Convert.ToInt32(this.aesHelper.Decode(request.EncryptedPatientId));
            var response = await this.patientServices.FetchPatientTimeLine(patientId);
            if (response.Appointments.Count() > 0)
            {
                foreach (var item in response.Appointments)
                {
                    item.AppointmentTimeString = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).Add(item.AppointmentTime).ToString("hh:mm tt");
                }
            }
            if (response.Scan.Count() > 0)
            {
                foreach (var item in response.Scan)
                {
                    DateTime d1 = Convert.ToDateTime(item.AppointmentTime);
                    item.AppointmentTimeString = d1.ToString("hh:mm tt");
                    if (item.Status == "C") { item.Status = "Cancelled"; }
                    else if (item.Status == "B") { item.Status = "Booked"; }
                    else if (item.Status == "R") { item.Status = "Rescheduled"; }
                }
            }
            if (response.OTData.Count() > 0)
            {
                foreach (var item in response.OTData)
                {
                    if (item.Status == "C") { item.Status = "Cancelled"; }
                    else if (item.Status == "B") { item.Status = "Booked"; }
                    else if (item.Status == "R") { item.Status = "Rescheduled"; }
                }
            }
            return this.Success(response);
        }
        [HttpPost]
        [Route("add-baby-patient")]
        [Consumes("multipart/form-data")]
        [ProducesResponseType(200, Type = typeof(List<Resource>))]
        [ProducesResponseType(500)]
        public async Task<ActionResult> AddBabyPatientAsync([FromForm] BabyregistrationRequest request)
        {
            request = (BabyregistrationRequest)EmptyFilter.Handler(request);
            //request.RelativeDetails.Count > 0 ? request.RelativeDetails : JsonConvert.DeserializeObject<List<PatientFamilyModel>>(request.Relative);/////
            request.BabyDetails = request.BabyDetails.Count > 0 ? request.BabyDetails : JsonConvert.DeserializeObject<List<ModifyPatientRequest>>(request.BabyData);
            var model = new PatientModel();
            //int accountId = 0;
            int patientId = 0;
            //Guid guid;
            if (request.BabyDetails.Count() > 0)
            {
                foreach (var record in request.BabyDetails)
                {
                    model = this.mapper.Map<PatientModel>(record);
                    //model.TimeOfBirth = TimeSpan.Parse(record.TimeOfBirth);
                    model.LocationId = (int)request.LocationId;
                    model.FullName = CoreFilter.FullName(record.FirstName, record.MiddleName, record.LastName);
                    var (accountId, newPatientId, guid) = await this.patientServices.AddBabyPatientAsync(model, request.EmergencyContacts ?? new List<PatientEmergencyModel>(), request.Insurances ?? new List<PatientInsuranceModel>(), null, request.RelativeDetails ?? new List<PatientFamilyModel>());
                    patientId = newPatientId;
                    if (accountId > 0)
                    {
                        var auditLogModel = new AuditLogModel
                        {
                            AccountId = model.CreatedBy,
                            LogTypeId = (int)LogTypes.Patient,
                            LogFrom = (short)model.RoleId,
                            LogDate = DateTime.UtcNow.AddMinutes(330),
                            LogDescription = $@"{model.CreatedByName} <b>Registered/b> the Patient:<b>{model.FullName}</b> on {DateTime.UtcNow.AddMinutes(330).ToString("MM/dd/yyyy hh:mm tt")}",
                            LocationId = model.LocationId
                        };
                        await this.auditLogServices.LogAsync(auditLogModel);

                    }

                    switch (accountId)
                    {
                        case -2:
                            return this.Conflict("Given email address has already been exists with us.");
                        case -1:
                            return this.Conflict("Given mobile number has already been exists with us.");
                        case 0:
                            return this.ServerError();
                    }
                }
            }
            //var model = this.mapper.Map<PatientModel>(request.BabyDetails);
            // model.FullName = CoreFilter.FullName(model.FirstName, model.MiddleName, model.LastName);
            //model.LocationId = (int)request.LocationId;
            //model.TimeOfBirth = TimeSpan.Parse(request.TimeOfBirth);

            //var (accountId, newPatientId, guid) = await this.patientServices.AddBabyPatientAsync(model, request.EmergencyContacts ?? new List<PatientEmergencyModel>(), request.Insurances ?? new List<PatientInsuranceModel>(), null, request.RelativeDetails ?? new List<PatientFamilyModel>());

            return this.Success(new GenericResponse
            {
                Status = GenericStatus.Success,
                Data = patientId
            });
        }

        /// <summary>
        /// The upload patient documents.
        /// </summary>
        /// <param name="logPath">
        /// The log Path.
        /// </param>
        /// <param name="files">
        /// The files.
        /// </param>
        /// <param name="documentType">
        /// The document Type.
        /// </param>
        /// <param name="account">
        /// The account.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        //    [NonAction]
        //    private async Task<List<PatientModel>> UploadPatientProfilePic( IEnumerable<string> files, string  base64ProfileImage, AccountModel account)
        //    {
        //        var patientProfile = new List<PatientModel>();
        //        foreach (var item in files)
        //        {
        //            var fileInfo = new FileInfo(item);
        //            using (var fileStream = new FileStream(item, FileMode.Open, FileAccess.Read))
        //            {
        //                var bytes = new byte[fileStream.Length];
        //                fileStream.Read(bytes, 0, Convert.ToInt32(fileStream.Length));
        //                var name = fileInfo.Name.Split(".")[0];
        //                var extension = fileInfo.Name.Split(".")[1];
        //                var formFile = new FormFile(fileStream, 0, fileStream.Length, null, name)
        //                {
        //                    Headers = new HeaderDictionary(),
        //                    ContentType = "image/" + extension
        //                };
        //                var model = new PatientModel
        //                {
        //                    Base64ProfileImage = base64ProfileImage,
        //                    Description = formFile.FileName,
        //                    DocumentName = name,
        //                    UploadedBy = 1,
        //                    PatientId = account.ReferenceId,
        //                    ContentType = formFile.ContentType,
        //                    Size = formFile.Length
        //                };

        //                var fileName = $"{model.Base64ProfileImage}_{DateTime.UtcNow.Ticks}.{extension}";
        //                model.ProfileImageUrl = await this.documentHelper.UploadAsync(formFile, account.PatientGuid, model.Base64ProfileImage, fileName);
        //                string[] imageFormats = { "jpg", "bmp", "gif", "png", "jpeg" };


        //                    if (imageFormats.Contains(extension))
        //                    {
        //                        var image = Image.FromStream(fileStream);
        //                        var thumbnail = image.GetThumbnailImage(150, 150, () => false, IntPtr.Zero);
        //                        var stream = new MemoryStream();
        //                        thumbnail.Save(stream, image.RawFormat);
        //                        stream.Position = 0;
        //                        var thumbnailFormFile = new FormFile(stream, 0, stream.Length, null, name)
        //                        {
        //                            Headers = new HeaderDictionary(),
        //                            ContentType = "image/" + extension
        //                        };
        //                        model.ThumbnailUrl = await this.documentHelper.UploadThumbnailAsync(thumbnailFormFile, account.PatientGuid, model.DocumentType, fileName);
        //                    }


        //                patientProfile.Add(model);

        //        }

        //        return patientProfile;
        //    }
        //}
    }
}
