using System;
using System.Collections.Generic;
using System.Linq;
using Hims.Domain.Configurations;
using Hims.Shared.UserModels.Common;
using Hims.Shared.UserModels.ServiceOrder;
using Package = Hims.Shared.UserModels.ServiceOrder.Package;

namespace Hims.Api.Controllers
{
    using System.Threading.Tasks;

    using Domain.Services;
    using Hims.Api.Models;
    using Hims.Domain.Helpers;
    using Hims.Shared.EntityModels;
    using Hims.Shared.Library.Enums;
    using Hims.Shared.UserModels.Labs;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Utilities;

    /// <inheritdoc />
    [Authorize]
    [Route("api/service-order")]
    public class ServiceOrderController : BaseController
    {
        /// <summary>
        /// The service
        /// </summary>
        private readonly IServiceOrderService service;

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

        /// <summary>
        /// The auditlog services.
        /// </summary>
        private readonly IAuditLogService auditLogServices;

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

        /// <summary>
        /// The laboratory service.
        /// </summary>
        private readonly ILaboratoryService laboratoryService;

        /// <summary>
        /// The labs service
        /// </summary>
        private readonly ILabTransactionService labTransactionService;

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

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

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

        private readonly IPackageModuleService packageModuleServices;

        /// <inheritdoc />
        public ServiceOrderController(ILaboratoryService laboratoryService, IServiceOrderService service, IAmazonS3Configuration amazonS3Configuration, IAuditLogService auditLogServices, IPatientService patientServices, IAESHelper aesHelper,
            IDocumentHelper documentHelper, IFtpHelper ftpHelper, ILabTransactionService labTransactionService, IPackageModuleService packageModuleServices)
        {
            this.service = service;
            this.amazonS3Configuration = amazonS3Configuration;
            this.auditLogServices = auditLogServices;
            this.patientServices = patientServices;
            this.laboratoryService = laboratoryService;
            this.aesHelper = aesHelper;
            this.documentHelper = documentHelper;
            this.ftpHelper = ftpHelper;
            this.labTransactionService = labTransactionService;
            this.packageModuleServices = packageModuleServices;
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("total-paid")]
        public async Task<ActionResult> GetTotalPaidAsync([FromBody] FilterModel model)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                var response = await this.service.GetTotalPaidAsync(model).ConfigureAwait(false);
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }
        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("fetch-admission")]
        public async Task<ActionResult> FetchAdmissionAsync([FromBody] FilterModel model)
        {
            var response = await this.service.FindAdmissionAsync(model);
            return this.Success(response);
        }
        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("fetch")]
        public async Task<ActionResult> FetchAsync([FromBody] FilterModel model)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                var record = new OverAllViewModel();

                var admission = await this.service.GetAdmissionCostInfoAsync(model, true).ConfigureAwait(false);
                record.ModuleTypeName = admission.ModuleTypeName;
                var discharge = await this.service.GetAdmissionCostInfoAsync(model, true).ConfigureAwait(false);
                if (model.Active == true)
                {
                    var difference = DateTime.Now.Date - admission.AdmissionDate;
                    // +2 is for join date and current date
                    record.RoomChargeCategoryId = admission.ChargeCategoryId;
                    record.ChargeCategoryName = admission.ChargeCategoryName;
                    record.NoOfDays = difference.Days < 1
                        ? difference.Hours > 0 ? 2 : 1
                        : difference.Days + 2;
                }
                else
                {
                    var difference = discharge.DischargeDate - admission.AdmissionDate;

                    // +2 is for join date and current date
                    record.RoomChargeCategoryId = admission.ChargeCategoryId;
                    record.ChargeCategoryName = admission.ChargeCategoryName;
                    record.NoOfDays = difference.Days < 1
                        ? difference.Hours > 0 ? 2 : 1
                        : difference.Days + 2;
                }
                record.BedCost = admission.BedCost;

                if (admission.ProviderCost != null && admission.ProviderCost.Any())
                {
                    var cost = admission.ProviderCost.FirstOrDefault(x => x.Day == GetDay(admission.Date.DayOfWeek));
                    if (cost != null)
                    {
                        record.DoctorCost = model.IsAdmission
                            ? cost.InPatientCharges ?? 0
                            : cost.OutPatientCharges ?? 0;
                        record.CovidCost = cost.CovidCharges ?? 0;
                    }
                }

                var generalRecords = await this.service.FetchAsync(model).ConfigureAwait(false);
                record.GeneralRecords = generalRecords;

                var surgeryServiceRecords = await this.service.FetchSurgeryServiceAsync(model).ConfigureAwait(false);
                record.SurgeryServiceRecords = surgeryServiceRecords;

                var labServicesRecords = await this.service.FetchLabServicesAsync(model).ConfigureAwait(false);
                record.LabServices = labServicesRecords;

                var scanServiceRecords = await this.service.FetchScanServiceAsync(model).ConfigureAwait(false);
                record.ScanServiceRecords = scanServiceRecords;

                var pharmacyIndentRecords = model.IsAdmission
                    ? await this.service.FetchPharmacyAsync(model).ConfigureAwait(false)
                    : new List<Shared.UserModels.ServiceOrder.PharmacyIndent.ViewModel>();

                record.PharmacyIndentRecords = pharmacyIndentRecords;

                var packageRecords = await this.service.FetchPackagesAsync(model).ConfigureAwait(false);
                record.PackageRecords = packageRecords;

                //var otRecords = await this.service.FetchOtAsync(model).ConfigureAwait(false);
                //record.otRecords

                foreach (var item in record.PackageRecords)
                {
                    if(item.CounsellingId !=  null && item.CounsellingId > 0)
                    {
                        var response = await packageModuleServices.GetCounsellingTotalAsync(item.CounsellingId ?? 0);
                        item.Total = response;
                    } else
                    {
                        var response = await packageModuleServices.GetChargeCategoryTotalAsync(admission.ChargeCategoryId, item.PackageModuleId, item.LocationId, item.ChargeModuleTemplateId, item.ModulesMasterIds);
                        if (response != null)
                        {
                            item.Total = response.Item1 - response.Item3;
                        }
                    }
                    
                }

                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = record
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("insert")]
        public async Task<ActionResult> InsertAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                var response = await this.service.InsertAsync(model).ConfigureAwait(false);
                if (model.LabServices.Count() > 0)
                {
                    model.LocationId = Convert.ToInt32(header.LocationId);
                    response += await this.InsertLabHelperAsync(model);
                }

                if (model.SurgeryServices.Count() > 0)
                {
                    model.LocationId = Convert.ToInt32(header.LocationId);
                    var surgeryResponse = await this.service.InsertSurgeryServiceAsync(model).ConfigureAwait(false);
                }

                if (model.ScanServices.Count() > 0)
                {
                    model.LocationId = Convert.ToInt32(header.LocationId);
                    var surgeryResponse = await this.service.InsertScanServiceAsync(model).ConfigureAwait(false);
                }

                if (response > 0)
                {
                    var model1 = new IdModel()
                    {
                        Id = Convert.ToInt32(model.Id),
                        IsAdmission = model.IsAdmission,
                    };
                    var res = await this.service.FetchPatientNameAsync(model1);
                    var auditLogModel = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.Services,
                        LogFrom = (short)model.RoleId,
                        LogDate = DateTime.UtcNow.AddMinutes(330),
                        LogDescription = $@"{model.FullName} <b>Added </b> <b>{(model.Packages.Count > 0 ? "Packages" : "Service")}</b>
                                                 for Patient:<b>{res}</b>",
                        LocationId = Convert.ToInt32(header.LocationId)
                    };
                    await this.auditLogServices.LogAsync(auditLogModel);
                }
                return Ok(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("insert-lab-only")]
        public async Task<ActionResult> InsertLabAsync([FromBody] InsertModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                model.LocationId = Convert.ToInt32(header.LocationId);
                var response = await this.InsertLabHelperAsync(model);

                if (response > 0)
                {
                    var model1 = new IdModel()
                    {
                        Id = Convert.ToInt32(model.Id),
                        IsAdmission = model.IsAdmission,
                    };
                    var res = await this.service.FetchPatientNameAsync(model1);
                    var auditLogModel = new AuditLogModel
                    {
                        AccountId = model.CreatedBy,
                        LogTypeId = (int)LogTypes.Services,
                        LogFrom = (short)model.RoleId,
                        LogDate = DateTime.UtcNow.AddMinutes(330),
                        LogDescription = $@"{model.FullName} <b>Added </b> <b>Lab Services</b>
                                                 for Patient:<b>{res}</b>",
                        LocationId = Convert.ToInt32(model.LocationId)
                    };
                    await this.auditLogServices.LogAsync(auditLogModel);
                }
                return Ok(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        private async Task<int> InsertLabHelperAsync([FromBody] InsertModel model)
        {
            var filterModel = new FilterModel { AdmissionId = model.AdmissionId, IsAdmission = model.IsAdmission };
            var admissionDetails = await this.service.GetAdmissionBasicAsync(filterModel).ConfigureAwait(false);

            int? admissionId = null;
            int? appointmentId = null;

            if (model.IsAdmission)
                admissionId = model.AdmissionId;
            else
                appointmentId = model.AdmissionId;

            var labBookingModel = new LabBookingModel
            {
                CreatedBy = model.CreatedBy,
                DoctorName = admissionDetails.ProviderName,
                OverallNetAmount = 0,
                PatientId = admissionDetails.PatientId,
                PatientName = admissionDetails.FullName,
                Type = "patient",
                Mobile = admissionDetails.Mobile,
                OverallDiscount = 0,
                OverallTotalAmount = 0,
                OverallDiscountPercentage = 0,
                DoctorId = admissionDetails.ProviderId,
                AdmissionId = admissionId,
                AppointmentId = appointmentId,
                LocationId = model.LocationId,
                PackageId = model.Packages.Count() > 0 ? (int?)model.Packages.FirstOrDefault() : null,
                ReceiptSaving = model.ReceiptSaving
            };
            return await this.labTransactionService.AddLabBillAsync(labBookingModel, model.LabServices);
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("add-package")]
        public async Task<ActionResult> InsertPackageAsync([FromBody] Package.InsertModel model)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                var response = await this.service.InsertPackageAsync(model).ConfigureAwait(false);
                return Ok(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        private static int GetDay(DayOfWeek day)
        {
            return day switch
            {
                DayOfWeek.Monday => 1,
                DayOfWeek.Tuesday => 2,
                DayOfWeek.Wednesday => 3,
                DayOfWeek.Thursday => 4,
                DayOfWeek.Friday => 5,
                DayOfWeek.Saturday => 6,
                _ => 7
            };
        }

        [HttpPost]
        [Route("fetch-counsellings")]
        public async Task<ActionResult> FetchCounsellingsAsync([FromBody] AutomaticFilterModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                model.LocationId = Convert.ToInt32(header.LocationId);
                var data = await this.service.GetCounsellingsAsync(model);
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = data,
                });
            }catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        [HttpPost]
        [Route("apply-counselling")]
        public async Task<ActionResult> ApplyCounsellingAsync([FromBody] AutomaticFilterModel model)
        {
            try
            {
                var response = await this.service.ApplyCounsellingAsync(model);
                return Ok(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("automatic")]
        public async Task<ActionResult> AddAutomaticChargesAsync([FromBody] AutomaticFilterModel model)
        {
            try
            {
                if (!model.IsAdmission)
                {
                    return Ok(new GenericResponse
                    {
                        Status = GenericStatus.Success
                    });
                }

                model.AdmissionId = Convert.ToInt32(model.Id);
                if (!model.ByPass)
                {
                    if (!await this.service.IsAutomaticPossibleAsync(model.AdmissionId))
                    {
                        return Ok(new GenericResponse
                        {
                            Status = GenericStatus.Success
                        });
                    }
                }

                var admission = await this.service.GetAdmissionCostInfoAsync(new FilterModel { AdmissionId = model.AdmissionId, IsAdmission = model.IsAdmission }, true).ConfigureAwait(false);
                var discharge = await this.service.GetAdmissionCostInfoAsync(new FilterModel { AdmissionId = model.AdmissionId, IsAdmission = model.IsAdmission, Active = model.Active }, true).ConfigureAwait(false);
                var noOfDays = 0;

                if (model.Active == true)
                {
                    var difference = DateTime.Now.Date - admission.AdmissionDate;
                    // +2 is for join date and current date
                    noOfDays = difference.Days < 1
                            ? difference.Hours > 0 ? 2 : 1
                            : difference.Days + 2;
                }
                else
                {
                    var difference = discharge.DischargeDate - admission.AdmissionDate;
                    // +2 is for join date and current date
                    noOfDays = difference.Days < 1
                            ? difference.Hours > 0 ? 2 : 1
                            : difference.Days + 2;
                }
                var bedCost = admission.BedCost;

                var data = new AutomaticInsertModel
                {
                    AdmissionId = model.AdmissionId,
                    BedCost = bedCost,
                    NoOfDays = noOfDays,
                    CreatedBy = model.CreatedBy,
                    DoctorCost = 0,
                    DoctorCostOnce = 0,
                    RoomChargeCategoryId = admission.ChargeCategoryId,
                    IsBed = admission.IsBed
                };
                if (admission.ProviderCost != null && admission.ProviderCost.Any())
                {
                    var cost = admission.ProviderCost.FirstOrDefault(x => x.Day == GetDay(admission.Date.DayOfWeek));
                    if (cost != null)
                    {
                        data.DoctorCostOnce = cost.InPatientCharges ?? 0;
                    }

                    //for (var i = 0; i < noOfDays; i++)
                    //{
                    //    var cost = admission.ProviderCost.FirstOrDefault(x => x.Day == GetDay(admission.Date.AddDays(i).DayOfWeek));
                    //    if (cost == null) continue;
                    //    if (i == 0)
                    //    {
                    //        data.DoctorCostOnce =  cost.InPatientCharges ?? 0;
                    //    }
                    //    data.DoctorCost += cost.InPatientCharges ?? 0;
                    //}
                }

                var response = await this.service.AutomaticInsertAsync(data).ConfigureAwait(false);
                return Ok(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("is-first")]
        public async Task<ActionResult> IsFirstTimeAsync([FromBody] AutomaticFilterModel model)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                var response = await this.service.IsFirstTimeAsync(model);
                return Ok(new GenericResponse
                {
                    Status = response ? GenericStatus.Success : GenericStatus.Warning
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("update")]
        public async Task<ActionResult> UpdateAsync([FromBody] UpdateModel model, [FromHeader] LocationHeader header)
        {
            try
            {
                int locationId = Convert.ToInt32(header.LocationId);
                model.NewRecords.AdmissionId = Convert.ToInt32(model.NewRecords.Id);
                var patient = await this.patientServices.FindPatientByAdmissionId(model.NewRecords.AdmissionId);
                var (response, unitChangedLabRecrds) = await this.service.UpdateAsync(model).ConfigureAwait(false);

                if (model.NewRecords.LabServices.Count() > 0)
                {
                    var filterModel = new FilterModel { AdmissionId = model.NewRecords.AdmissionId, IsAdmission = model.IsAdmission };
                    var admissionDetails = await this.service.GetAdmissionBasicAsync(filterModel).ConfigureAwait(false);

                    int? admissionId = null;
                    int? appointmentId = null;
                    //var labDetails = new List<LabHeaderModel>();

                    if (model.IsAdmission)
                        admissionId = model.NewRecords.AdmissionId;
                    else
                        appointmentId = model.NewRecords.AdmissionId;

                    //foreach (var lab in model.NewRecords.LabServices)
                    //{
                    //    labDetails.Add(new LabHeaderModel
                    //    {
                    //        DiscountAmount = 0,
                    //        DiscountPercentage = 0,
                    //        NetAmount = 0,
                    //        LabPackageId = null,
                    //        LabHeaderId = lab.LabHeaderId
                    //    });
                    //}

                    //var labBookingModel = new AddBooking
                    //{
                    //    CreatedBy = model.NewRecords.CreatedBy,
                    //    DoctorName = admissionDetails.ProviderName,
                    //    NetAmount = 0,
                    //    //PaidVia = "Cash",
                    //    PayTypeId = 1,
                    //    PatientId = admissionDetails.PatientId,
                    //    PatientName = admissionDetails.FullName,
                    //    PatientType = "I",
                    //    Mobile = admissionDetails.Mobile,
                    //    DiscountAmount = 0,
                    //    Amount = 0,
                    //    DiscountPercentage = 0,
                    //    ProviderId = admissionDetails.ProviderId,
                    //    //Labs = labDetails,
                    //    AdmissionId = admissionId,
                    //    AppointmentId = appointmentId,
                    //    Status = "Sample not collected",
                    //    LocationId = locationId
                    //};
                    //var result = await this.laboratoryService.AddPatientLabBooking(labBookingModel, model.NewRecords.LabServices);
                    //var labDetails = new List<NewLabBookingDetailModel>();
                    //foreach (var lab in model.NewRecords.LabServices)
                    //{
                        //labDetails.Add(new NewLabBookingDetailModel
                        //{
                        //    DiscountAmount = 0,
                        //    DiscountPercentage = 0,
                        //    NetAmount = 0,
                        //    LabMainDetailId = lab.LabMainDetailId,
                        //    TotalAmount = 0,
                        //    ChargeCategoryId = (int)model.ChargeCategoryId,
                        //    LabServicesId = model.LabServiceId
                        //}); ;
                    //}
                    var labBookingModel = new LabBookingModel
                    {
                        CreatedBy = model.NewRecords.CreatedBy,
                        DoctorName = admissionDetails.ProviderName,
                        OverallNetAmount = 0,
                        //PaidVia = "Cash",
                        //PayTypeId = 1,
                        PatientId = admissionDetails.PatientId,
                        PatientName = admissionDetails.FullName,
                        Type = "patient",
                        Mobile = admissionDetails.Mobile,
                        OverallDiscount = 0,
                        OverallTotalAmount = 0,
                        OverallDiscountPercentage = 0,
                        DoctorId = admissionDetails.ProviderId,
                        //Labs = labDetails,
                        AdmissionId = admissionId,
                        AppointmentId = appointmentId,
                        LocationId = locationId,
                        PackageId = model.NewRecords.Packages.Count() > 0 ? (int?)model.NewRecords.Packages.FirstOrDefault() : null,
                        ReceiptSaving = model.ReceiptSaving
                    };
                    var result = await this.labTransactionService.AddLabBillAsync(labBookingModel, model.NewRecords.LabServices.Where(x => !unitChangedLabRecrds.Contains(x.LabServicesId)).ToList());

                }

                if (response > 0)
                {
                    var model1 = new IdModel()
                    {
                        Id = Convert.ToInt32(model.NewRecords.Id),
                        IsAdmission = model.IsAdmission,
                    };
                    var res = await this.service.FetchPatientNameAsync(model1);
                    string logDescription;
                    if (model.DeletedPackages.Count > 0)
                    {
                        logDescription = $@"{model.NewRecords.FullName} <b>Deleted Packages</b> For Patient: <b>{res}</b>";
                    }
                    else if (model.DeletedRecords.Count > 0)
                    {
                        logDescription = $@"{model.NewRecords.FullName} <b>Deleted Service</b> For Patient: <b>{res}</b>";
                    }
                    else if (model.DeletedLabServices.Count > 0)
                    {
                        logDescription = $@"{model.NewRecords.FullName} <b>Deleted Lab Services</b> For Patient: <b>{res}</b>";
                    }
                    else
                    {
                        logDescription = $@"{model.NewRecords.FullName} <b>{(model.NewRecords.Packages.Count > 0 ? "Added Packages" : "Added Services")}</b> For Patient: <b>{res}</b>";
                    }

                    var auditLogModel = new AuditLogModel
                    {
                        AccountId = model.ModifiedBy,
                        LogTypeId = (int)LogTypes.Services,
                        LogFrom = (short)model.NewRecords.RoleId,
                        LogDate = DateTime.UtcNow,
                        LogDescription = logDescription,
                        LocationId = Convert.ToInt32(header.LocationId)
                        //$@"{model.NewRecords.FullName} <b>Updated - </b> {(model.NewRecords.Packages.Count > 0 ? "Added Packages" : "Added Services")}
                        //                  {(model.DeletedPackages.Count > 0 ? "Deleted Packages":"")}
                        //                   {(model.DeletedRecords.Count >0 ? "Deleted Service" : "")}
                        //               </b> for Patient: <b>{res}</b>"

                    };
                    await this.auditLogServices.LogAsync(auditLogModel);
                }
                return Ok(new GenericResponse
                {
                    Status = response > 0 ? GenericStatus.Success : GenericStatus.Error,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        /// <summary>
        /// The add icons async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        [HttpPost]
        [Route("get-admission-basic")]
        public async Task<ActionResult> GetAdmissionBasicAsync([FromBody] FilterModel model)
        {
            try
            {
                model.AdmissionId = Convert.ToInt32(model.Id);
                if (!string.IsNullOrEmpty(model.EncryptedProviderId))
                {
                    model.ProviderId = Convert.ToInt32(this.aesHelper.Decode(model.EncryptedProviderId));
                }
                var response = await this.service.GetAdmissionBasicAsync(model).ConfigureAwait(false);
                //var responseModels = response.ToString();

                response.EncryptedProviderId = this.aesHelper.Encode(response.ProviderId.ToString());

                //if (response?.ThumbnailUrl != null)
                //{
                //    response.ThumbnailUrl = this.amazonS3Configuration.BucketURL + response.Guid + "/" + response.ThumbnailUrl;
                //    response.Guid = null;
                //}
                if (!string.IsNullOrEmpty(response.ThumbnailUrl) && response.ThumbnailUrl.StartsWith("ftp"))
                {
                    //response.ThumbnailUrl = await this.documentHelper.FetchImageBase64(response.PatientId, response.ThumbnailUrl);
                    string url = this.ftpHelper.GetFtpUrl("PatientProfile");
                    string ftpfullpath = url + response.PatientId + "/" + response.ThumbnailUrl;
                    try
                    {
                        response.ThumbnailUrl = await this.ftpHelper.FetchImageBase64(response.PatientId, ftpfullpath);
                    }
                    catch (Exception e) { }
                }
                else
                {
                    response.ThumbnailUrl = null;
                }

                if (response?.AdmissionTime != null)
                {
                    response.TimeString = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).Add(response.AdmissionTime).ToString("hh:mm tt");
                }

                if (response?.DischargeTime != null)
                {
                    response.DischargeTimeString = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).Add((TimeSpan)response.DischargeTime).ToString("hh:mm tt");
                }
                if (response.StreetAddress != null) response.FullAddress = response.StreetAddress;
                if (response.AddressLine2 != null) response.FullAddress += " " + response.AddressLine2;
                if (response.City != null) response.FullAddress += ", " + response.City;
                if (response.State != null) response.FullAddress += ", " + response.State;
                if (response.Zipcode != null) response.FullAddress += ", " + response.Zipcode;
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Success,
                    Data = response
                });
            }
            catch (Exception ex)
            {
                return Ok(new GenericResponse
                {
                    Status = GenericStatus.Error,
                    Message = ex.Message
                });
            }
        }

        [HttpPost]
        [Route("fetch-previous-packages")]
        public async Task<ActionResult> FetchPreviousPackagesAsync([FromBody] StringIdRequest model)
        {
            model.MainId = Convert.ToInt32(model.Id);
            var packageRecords = await this.service.FetchPreviousPackagesAsync(model).ConfigureAwait(false);
            return Ok(new GenericResponse
            {
                Status = GenericStatus.Success,
                Data = packageRecords
            });
        }
    }
}