#nullable enable
using System.Threading.Tasks;

namespace Hims.Infrastructure.Services
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Dapper;
    using Domain.Configurations;
    using Domain.Repositories.UnitOfWork;
    using Domain.Services;
    using Shared.Library;

    using Hims.Shared.Library.Enums;
    using Hims.Shared.UserModels.Filters;
    using Hims.Shared.UserModels;
    using Hims.Shared.UserModels.Common;
    using Hims.Shared.UserModels.Pharmacy;
    using Hims.Domain.Entities;
    using Hims.Shared.EntityModels;
    using System;
    using System.Reflection;
    using Hims.Domain.Entities.Enums;
    using Hims.Shared.UserModels.Scan.ScanAppointment;
    using Hims.Shared.UserModels.MasterBill;
    using FilterModel = Shared.UserModels.MasterBill.FilterModel;
    using Hims.Shared.UserModels.Reports;
    using Hims.Shared.UserModels.Labs;
    using Hims.Shared.UserModels.Labs.Report;
    using System.Drawing;
    using System.Collections;
    using static System.Net.Mime.MediaTypeNames;
    using System.Collections;
    using System.ComponentModel.DataAnnotations;
    using Hims.Shared.DataFilters;
    using System.IO;

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

        /// <summary>
        /// The document helper.
        /// </summary>
        private readonly IAmazonS3Configuration amazonS3Configuration;

        /// <summary>
        /// Initializes a new instance of the <see cref="ReportServices"/> class.
        /// </summary>
        /// <param name="unitOfWork">
        /// The unit of work.
        /// </param>
        /// <param name="amazonS3Configuration">
        /// The amazon S3 configuration.
        /// </param>
        public ReportServices(IUnitOfWork unitOfWork, IAmazonS3Configuration amazonS3Configuration)
        {
            this.unitOfWork = unitOfWork;
            this.amazonS3Configuration = amazonS3Configuration;
        }

        /// <inheritdoc />
        public Task<IEnumerable<Report>> InPatientsAsync(PatientFilterModel model)
        {
            var paramsString = "";
            //var query = "";
            if (model.LocationId > 0)
            {
                paramsString += $@"  {model.LocationId}";
            }
            else
            {
                paramsString += $@"  null";
            }

            if (model.DepartmentId != null)
            {
                paramsString += $@" ,'{{{model.DepartmentId}}}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ProviderId != null)
            {
                paramsString += $@", '{{{model.ProviderId}}}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.FromDate != null)
            {
                paramsString += $@", '{model.FromDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }


            //if (model.PatientName != null)
            //{
            //    paramsString += $@", '{{{model.PatientName}}}'";
            //}
            //else
            //{
            //    paramsString += $@", null";
            //}
            if (model.PatientId != null)
            {
                paramsString += $@", '{model.PatientId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.UMRNo != null)
            {
                paramsString += $@",'{model.UMRNo}'";
            }
            else
            {
                paramsString += $@",null";
            }
            if (model.ReferredBy != null)
            {
                paramsString += $@",'{model.ReferredBy}'";
            }
            else
            {
                paramsString += $@",null";
            }
            if (model.ReferredByName != null)
            {
                paramsString += $@",'{model.ReferredByName}'";
            }
            else
            {
                paramsString += $@",null";
            }
            if (model.PatientMobile != null)
            {
                paramsString += $@",'{model.PatientMobile}'";
            }
            else
            {
                paramsString += $@",null";
            }
            if (model.DischargeStatusId != null)
            {
                paramsString += $@", '{model.DischargeStatusId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            //if (model.RoleId != null)
            //{
            //    paramsString += $@",'{model.RoleId}'";
            //}
            //else
            //{
            //    paramsString += $@",null";
            //}
            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }


            //var query = $@"Select * from ""udf_uiReport_fetch_Admissions""('{model.AdmissionNo}',{paramsString}, null,null)";
            var query = $@"Select * from ""udf_uiReport_fetch_Admissions_Locations""('{model.AdmissionNo}',{paramsString}, null,null)";
            //if (model.PageIndex <= 0)
            //{
            //    return this.unitOfWork.Current.QueryAsync<Report>(query);
            //}

            //model.PageIndex -= 1;
            //query += " LIMIT " + model.PageSize + " offset " + (model.PageIndex * model.PageSize);
            return this.unitOfWork.Current.QueryAsync<Report>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<PharamacyReport>> FetchInPharamctReportAsync(PharmacyReportFilterModel model)
        {
            var paramsString = "";

            if (model.FromDate != null)
            {
                paramsString += $@" '{model.FromDate}'::timestamp without time zone";
            }
            else
            {
                paramsString += $@" null";
            }

            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::timestamp without time zone";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.CreatedBy != null)
            {
                paramsString += $@", '{model.CreatedBy}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.PayTypeId != null)
            {
                paramsString += $@", '{model.PayTypeId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            paramsString += model.LocationId != null ? $@", '{model.LocationId}'" : $@", null";
            var query = $@"Select COUNT(*) OVER () AS ""TotalItems"",* from ""udf_PharmacySales_Report""({paramsString})";
            if (model.PageIndex <= 0)
            {
                return this.unitOfWork.Current.QueryAsync<PharamacyReport>(query);
            }

            model.PageIndex -= 1;
            query += " LIMIT " + model.PageSize + " offset " + (model.PageIndex * model.PageSize);
            return this.unitOfWork.Current.QueryAsync<PharamacyReport>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<DailySalesMedicationModel>> FetchDailySalesReportAsync(DailySalesMedicationFilterModel model)
        {
            var paramsString = "";

            if (model.ProductName != null)
            {
                paramsString += $@" '{model.ProductName}' ";
            }
            else
            {
                paramsString += $@" null";
            }

            if (model.GenericName != null)
            {
                paramsString += $@", '{model.GenericName}' ";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.CategoryName != null)
            {
                paramsString += $@", '{model.CategoryName}' ";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.CompanyName != null)
            {
                paramsString += $@", '{model.CompanyName}' ";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.SupplierName != null)
            {
                paramsString += $@", '{model.SupplierName}' ";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.PayTypeId != null)
            {
                paramsString += $@", '{model.PayTypeId}' ";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.FromDate != null)
            {
                paramsString += $@", '{model.FromDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.LocationId != null)
            {
                paramsString += $@",'{model.LocationId}'";
            }
            else
            {
                paramsString += $@", null";
            }


            var query = $@"Select COUNT(*) OVER () AS ""TotalItems"",* from ""udf_DailySalesReportByMedication""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<DailySalesMedicationModel>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<PharmacySaleBill>> FetchPatientPharmacyReportAsync(PharmacySaleBill model)
        {
            var paramsString = "";

            if (model.PatientId != null)
            {
                paramsString += $@" '{model.PatientId}' ";
            }
            else
            {
                paramsString += $@" null";
            }

            if (model.UMRNo != null)
            {
                paramsString += $@", '{model.UMRNo}' ";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.PatientMobile != null)
            {
                paramsString += $@", '{model.PatientMobile}' ";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.BillNumber != null)
            {
                paramsString += $@", '{model.BillNumber}' ";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.PayTypeId != null)
            {
                paramsString += $@", '{model.PayTypeId}' ";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.FromDate != null)
            {
                paramsString += $@", '{model.FromDate}'::timestamp without time zone";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::timestamp without time zone";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.LocationId != null)
            {
                paramsString += $@", '{model.LocationId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            var query = $@"Select COUNT(*) OVER () AS ""TotalItems"",* from ""udf_PatientMedicationReport""({paramsString})"; //
            return this.unitOfWork.Current.QueryAsync<PharmacySaleBill>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<PharmacyPurchaseReportBill>> FetchPharmacyPurchaseReportAsync(PharmacyPurchaseReportBill model)
        {
            var paramsString = "";

            paramsString += model.BillNumber != null ? $@" '{model.BillNumber}' " : $@" null";
            paramsString += model.BillType != null ? $@", '{model.BillType}' " : $@", null";
            paramsString += model.CreatedBy != null ? $@", '{model.CreatedBy}' " : $@", null";
            //paramsString += model.SupplierName != null ? $@", '{model.SupplierName}' " : $@", null";
            paramsString += model.SupplierId != null ? $@", {model.SupplierId} " : $@", null";
            paramsString += model.PaidVia != null ? $@", '{model.PaidVia}' " : $@", null";
            paramsString += model.DueDate != null ? $@", '{model.DueDate}'::date" : $@", null";
            paramsString += model.FromDate != null ? $@", '{model.FromDate}'::timestamp without time zone" : $@", null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";
            paramsString += model.pharmacyBillType != null ? $@", '{model.pharmacyBillType}'" : $@", null";
            paramsString += model.PharmacyWareHouseId != null ? $@",'{model.PharmacyWareHouseId}'" : $@", null";
            paramsString += model.LocationId != null ? $@",'{model.LocationId}'" : $@", null";


            var query = $@"Select COUNT(*) OVER () AS ""TotalItems"",* from ""udf_PharmacyPurchaseReport1""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<PharmacyPurchaseReportBill>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<PharmacyPurchaseReportBill>> FetchProductPurchaseReportAsync(PharmacyPurchaseReportBill model)
        {
            var paramsString = "";

            paramsString += model.BillNumber != null ? $@" '{model.BillNumber}' " : $@" null";
            paramsString += model.BillType != null ? $@", '{model.BillType}' " : $@", null";
            paramsString += model.CreatedBy != null ? $@", '{model.CreatedBy}' " : $@", null";
            paramsString += model.SupplierName != null ? $@", '{model.SupplierName}' " : $@", null";
            paramsString += model.ProductName != null ? $@", '{model.ProductName}' " : $@", null";
            paramsString += model.FromDate != null ? $@", '{model.FromDate}'::Date " : $@", null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::Date " : $@", null";
            paramsString += model.pharmacyBillType != null ? $@", '{model.pharmacyBillType}'" : $@", null";
            paramsString += model.LocationId != null ? $@", '{model.LocationId}'" : $@", null";

            var query = $@"Select COUNT(*) OVER () AS ""TotalItems"",* from ""udf_ProductPurchaseReport""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<PharmacyPurchaseReportBill>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<PharmacyPurchaseReportBill>> FetchProductSaleReportAsync(PharmacyPurchaseReportBill model)
        {
            var where = "where 1=1";
            if (!string.IsNullOrEmpty(model.BillNumber))
            {
                where += $@"and PH.""BillNumber"" ilike '%{model.BillNumber}%'";
            }
            if (model.AccountId != null)
            {
                where += $@"and A.""AccountId"" ='{model.AccountId}'";
            }

            if (!string.IsNullOrEmpty(model.ProductName))
            {
                where += $@"and PP.""ProductName"" = '{model.ProductName}'";
            }
            //if (!string.IsNullOrEmpty(model.PaidVia))
            //{
            //    where += $@"and lower(PH.""PaidVia"") = lower('{model.PaidVia}')";
            //}
            if (model.PayTypeId != null)
            {
                where += $@"and PT.""PayTypeId"" ='{model.PayTypeId}'";
            }

            if (model.CreatedBy != null)
            {
                where += $@"and ph.""CreatedBy"" = '{model.CreatedBy}'";
            }
            if (!string.IsNullOrEmpty(model.Tax))
            {
                where += $@"and L.""Name"" = '{model.Tax}'";
            }
            if (!string.IsNullOrEmpty(model.BillType))
            {
                where += $@"and PH.""BillType"" = '{model.BillType}'";
            }
            if (model.FromDate != null)
            {
                where += $@" and  PH.""CreatedDate""::date >= '{model.FromDate}' ";
            }
            if (model.ToDate != null)
            {
                where += $@" and  PH.""CreatedDate""::date <= '{model.ToDate}' ";
            }

            if (model.LocationId != null)
            {
                where += $@" and PH.""LocationId""={model.LocationId} ";
            }

            var query = $@"select COUNT(*) OVER() AS ""TotalItems"", PH.""BillNumber"",PP.""PharmacyProductId"",R.""RoleName"",A.""FullName"" as ""CreatedByName"",ci.""Name"" ""CategoryName"",PT.""PayTypeName"" as ""PaidVia"", PH.""PaymentNumber"" ,PP.""ProductName"",L.""Name"" as ""Tax"",PH.""CreatedDate"",PD.""TaxAmount"",PD.""NetAmount""   from ""PharmacyProduct"" PP
                            JOIN ""PharmacySaleDetail"" PD on PD.""PharmacyProductId"" = PP.""PharmacyProductId""
                            JOIN ""PharmacySaleHeader"" PH on PH.""PharmacySaleHeaderId"" = PD.""PharmacySaleHeaderId""
                            JOIN ""LookupValue"" L on  L.""LookupValueId"" = PD.""TaxId"" 
							join ""LookupValue"" ci on ci.""LookupValueId""=pp.""CategoryId""
                            JOIN ""Account"" A on A.""AccountId""= ph.""CreatedBy""
                            JOIN ""Role"" R on R.""RoleId"" =A.""RoleId""   
                           left join ""PayType"" PT on PT.""PayTypeId""=PH.""PayTypeId""
                            {where}
                             order by PH.""CreatedDate"" desc";
            if (model.PageIndex <= 0)
            {
                return this.unitOfWork.Current.QueryAsync<PharmacyPurchaseReportBill>(query);
            }

            model.PageIndex -= 1; //
            query += " LIMIT " + model.PageSize + " offset " + (model.PageIndex * model.PageSize);
            return this.unitOfWork.Current.QueryAsync<PharmacyPurchaseReportBill>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<Report>> FetchDashboardInPatientsAsync(PatientFilterModel model)
        {
            var paramsString = "";
            if (model.AdmissionDate != null)
            {
                paramsString += $@" '{model.AdmissionDate}'";
            }
            else
            {
                paramsString += $@" null";
            }
            if (model.FromDate != null)
            {
                paramsString += $@", '{model.FromDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.ProviderId != null)
            {
                paramsString += $@", '{{{model.ProviderId}}}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.PatientId != null)
            {
                paramsString += $@", '{{{model.PatientId}}}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.AdmissionNo != null)
            {
                paramsString += $@", '{model.AdmissionNo}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.LocationId > 0)
            {
                paramsString += $@", {model.LocationId}";
            }
            else
            {
                paramsString += $@", null";
            }
            model.PageIndex -= 1;
            // var query = $@"Select COUNT(*) OVER () AS ""TotalItems"",* from ""udf_dashBoard_fetch_Admissions""({paramsString},'{model.PatientType}', {model.PageIndex},{model.PageSize})";
            var query = $@"Select COUNT(*) OVER () AS ""TotalItems"",* from ""udf_dashBoard_fetch_Admissions_Location""({paramsString},'{model.PatientType}', {model.PageIndex},{model.PageSize})";
            if (model.PageIndex <= 0)
                if (model.PageIndex <= 0)
                {
                    return this.unitOfWork.Current.QueryAsync<Report>(query);
                }

            return this.unitOfWork.Current.QueryAsync<Report>(query);


        }

        /// <inheritdoc />
        public Task<IEnumerable<OutReport>> FetchOutDashboardPatientsAsync(OutPatientFilterModel model)
        {
            var paramsString = "";

            if (model.AppointmentDate != null)
            {
                paramsString += $@" '{model.AppointmentDate}'";
            }
            else
            {
                paramsString += $@" null";
            }
            if (model.FromDate != null)
            {
                paramsString += $@", '{model.FromDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.ProviderId != null)
            {
                paramsString += $@", '{{{model.ProviderId}}}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.PatientId != null)
            {
                paramsString += $@", '{{{model.PatientId}}}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.AppointmentNo != null)
            {
                paramsString += $@", '{model.AppointmentNo}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.LocationId > 0)
            {
                paramsString += $@", {model.LocationId}";
            }
            else
            {
                paramsString += $@", null";
            }

            model.PageIndex -= 1;
            var query = $@"Select COUNT(*) OVER () AS ""TotalItems"", * from ""udf_dashBoard_fetch_Appointments_Location""({paramsString},'{model.VisitType}',{model.PageIndex},{model.PageSize})";

            return this.unitOfWork.Current.QueryAsync<OutReport>(query);
        }
        public Task<IEnumerable<PatientDashboardReport>> FetchFollowUpDashboardPatientsAsync(OutPatientFilterModel model)
        {
            var paramsString = "";


            if (model.FromDate != null)
            {
                paramsString += $@"'{model.FromDate}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ProviderId != null)
            {
                paramsString += $@", {model.ProviderId}";
                // paramsString += $@", '298'";
            }
            else
            {
                paramsString += $@", null";
            }


            if (model.LocationId > 0)
            {
                paramsString += $@", {model.LocationId}";
            }
            else
            {
                paramsString += $@", null";
            }

            model.PageIndex -= 1;
            var query = $@"select * from ""widget_Table_FollowUpAppointmentDashboard""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<PatientDashboardReport>(query);
        }


        public Task<IEnumerable<PatientDashboardReport>> FetchOnlineDashboardPatientsAsync(OutPatientFilterModel model)
        {
            var paramsString = "";


            if (model.FromDate != null)
            {
                paramsString += $@" '{model.FromDate}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ProviderId != null)
            {
                paramsString += $@", {model.ProviderId}";
                //paramsString += $@", '298'";
            }
            else
            {
                paramsString += $@", null";
            }


            if (model.LocationId > 0)
            {
                paramsString += $@", {model.LocationId}";
            }
            else
            {
                paramsString += $@", null";
            }
            model.PageIndex -= 1;
            var query = $@"select * from ""widget_Table_OnlineAppointmentDashboard""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<PatientDashboardReport>(query);
        }
        public Task<IEnumerable<PatientDashboardReport>> FetchWalkInDashboardPatientsAsync(OutPatientFilterModel model)
        {
            var paramsString = "";


            if (model.FromDate != null)
            {
                paramsString += $@"'{model.FromDate}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ProviderId != null)
            {
                paramsString += $@", {model.ProviderId}";
                // paramsString += $@", '298'";
            }
            else
            {
                paramsString += $@", null";
            }


            if (model.LocationId > 0)
            {
                paramsString += $@", {model.LocationId}";
            }
            else
            {
                paramsString += $@", null";
            }
            model.PageIndex -= 1;
            var query = $@"select * from ""widget_Table_WalkinAppointmentDashboard""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<PatientDashboardReport>(query);
        }
        public Task<IEnumerable<PatientDashboardReport>> FetchNewPatientAppointmentDashboardPatientsAsync(OutPatientFilterModel model)
        {
            var paramsString = "";


            if (model.FromDate != null)
            {
                paramsString += $@"'{model.FromDate}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ProviderId != null)
            {
                paramsString += $@", {model.ProviderId}";
                // paramsString += $@", '298'";
            }
            else
            {
                paramsString += $@", null";
            }


            if (model.LocationId > 0)
            {
                paramsString += $@", {model.LocationId}";
            }
            else
            {
                paramsString += $@", null";
            }
            model.PageIndex -= 1;
            var query = $@"select * from ""widget_Table_NewPatientAppointmentDashboard""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<PatientDashboardReport>(query);
        }
        public Task<IEnumerable<PatientDashboardReport>> FetchNewApointmentDashboardPatientsAsync(OutPatientFilterModel model)
        {
            var paramsString = "";


            if (model.FromDate != null)
            {
                paramsString += $@"'{model.FromDate}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ProviderId != null)
            {
                paramsString += $@", {model.ProviderId}";
                // paramsString += $@", '298'";
            }
            else
            {
                paramsString += $@", null";
            }


            if (model.LocationId > 0)
            {
                paramsString += $@", {model.LocationId}";
            }
            else
            {
                paramsString += $@", null";
            }
            model.PageIndex -= 1;
            var query = $@"select * from ""widget_Table_NewAppointmentDashboard""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<PatientDashboardReport>(query);
        }

        public Task<IEnumerable<PatientDashboardReport>> FetchRemindersAsync(OutPatientFilterModel model)
        {
            var where = "where 1=1";
            if ((model.ProviderId != null) && (model.ProviderId != 0))
            {
                where += $@"  and opp.""ProviderId"" = {model.ProviderId}";
            }
            if (model.LocationId > 0)
            {
                where += $@" and opp.""LocationId"" = {model.LocationId}  ";
            }
            where += $@" and opp.""AppointmentDate""::Date = '{DateTime.Now.ToString("yyyy-MM-dd")}'  and";
            var qry = $@"select opp.""AppointmentId"",pat.""UMRNo"",pat.""FullName"",gyn.""Reminder"",gyn.""ModifiedDate"",s.""EncounterTypeId"",E.""EncounterName""
            from  ""Appointment"" opp 
            join ""Patient"" pat on pat.""PatientId""=opp.""PatientId""
            join ""Specialization"" s on s.""SpecializationId"" = opp.""SpecializationId""
             join ""EncounterType"" E on E.""EncounterTypeId""=s.""EncounterTypeId""
            join ""GynEncounter"" gyn on gyn.""AppointmentId""=opp.""AppointmentId"" {where} gyn.""Reminder"" IS NOT NULL 
            
            union all
            select opp.""AppointmentId"",pat.""UMRNo"",pat.""FullName"",ob.""Reminder"",ob.""ModifiedDate"", s.""EncounterTypeId"",E.""EncounterName"" from ""Appointment"" opp
            join ""Patient"" pat on pat.""PatientId""=opp.""PatientId""
            join ""Specialization"" s on s.""SpecializationId"" = opp.""SpecializationId""
             join ""EncounterType"" E on E.""EncounterTypeId""=s.""EncounterTypeId""
            join ""ObEncounter"" ob on ob.""AppointmentId""=opp.""AppointmentId"" {where} ob.""Reminder"" IS NOT NULL 
           
            union all
            select opp.""AppointmentId"",pat.""UMRNo"",pat.""FullName"",pe.""Reminder"",pe.""ModifiedDate"", s.""EncounterTypeId"",E.""EncounterName"" from ""Appointment"" opp
            join ""Patient"" pat on pat.""PatientId"" = opp.""PatientId""
            join ""Specialization"" s on s.""SpecializationId"" = opp.""SpecializationId""
             join ""EncounterType"" E on E.""EncounterTypeId"" = s.""EncounterTypeId""
            join ""PediatricEncounter"" pe on pe.""AppointmentId"" = opp.""AppointmentId"" {where}
            pe.""Reminder"" IS NOT NULL";

            return this.unitOfWork.Current.QueryAsync<PatientDashboardReport>(qry);
        }
        public Task<IEnumerable<PatientDashboardReport>> FetchAllAppointments(OutPatientFilterModel model)
        {
            var where = "where 1=1";
            if (model.FromDate != null)
            {
                where += $@" and apt.""AppointmentDate""::date = '{model.FromDate}'";
            }
            if ((model.ProviderId != null) && (model.ProviderId != 0))
            {
                where += $@"  and apt.""ProviderId"" = {model.ProviderId}";
            }
            if (model.LocationId > 0)
            {
                where += $@" and apt.""LocationId"" = {model.LocationId}";
            }
            var qry = $@"select Pa.""Salutation"", Pa.""FullName"" as ""PatientName"",Pa.""UMRNo"",Pa.""Mobile"",
                apt.""AppointmentNo"" ,--apt.""AppointmentTime""::text
                 TO_CHAR(apt.""AppointmentTime"", 'hh12:mi AM')  as ""AppointmentTime"",
                 apt.""AppointmentId"",s.""SpecializationName"",s.""EncounterTypeId"",E.""EncounterName"",apt.""IsHealthCard"",apt.""AppointmentDate"",apt.""VisitTypeId"",apt.""ConsultationTypeId""
                from ""Appointment"" apt
                --join ""AppointmentType"" AT on AT.""AppointmentTypeId"" = apt.""AppointmentTypeId""
                join ""Patient"" Pa on Pa.""PatientId"" = apt.""PatientId""
                join ""Provider"" Pr on Pr.""ProviderId"" = apt.""ProviderId""
                 join ""Specialization"" s on s.""SpecializationId"" = apt.""SpecializationId""

                 join ""EncounterType"" E on E.""EncounterTypeId""=s.""EncounterTypeId""     {where} ";
            return this.unitOfWork.Current.QueryAsync<PatientDashboardReport>(qry);
        }


        public Task<IEnumerable<PatientDashboardReport>> FetchAllAdmission(OutPatientFilterModel model)
        {
            var where = "where 1=1";
            if (model.FromDate != null)
            {
                where += $@" and apt.""IsDischarged"" <> false";

            }
            if (model.ProviderId != null)
            {
                where += $@"  and apt.""ProviderId"" = {model.ProviderId}";
            }
            if (model.LocationId > 0)
            {
                where += $@" and apt.""LocationId"" = {model.LocationId}";
            }
            var qry = $@"
       select Pa.""Salutation"", Pa.""FullName"" as ""PatientName"", Pa.""UMRNo"", Pa.""Mobile"", apt.""ProviderId"",
                apt.""AdmissionNo"" ,--apt.""AppointmentTime""::text
                 TO_CHAR(apt.""AdmissionTime"", 'hh12:mi AM')  as ""AdmissionTime"",
                 apt.""AdmissionId"",s.""DepartmentName"",apt.""AdmissionDate"",apt.""VisitTypeId""
                from ""Admission"" apt
                join ""Patient"" Pa on Pa.""PatientId"" = apt.""PatientId""
                join ""Provider"" Pr on Pr.""ProviderId"" = apt.""ProviderId""
                 join ""Department"" s on s.""DepartmentId"" =  apt.""DepartmentId""

               --  join ""EncounterType"" E on E.""EncounterTypeId""=s.""EncounterTypeId""  
				   {where} ";
            return this.unitOfWork.Current.QueryAsync<PatientDashboardReport>(qry);
        }
        public Task<IEnumerable<PatientDashboardReport>> FetchOTApointmentDashboardPatientsAsync(OutPatientFilterModel model)
        {
            var paramsString = "";


            if (model.FromDate != null)
            {
                paramsString += $@"'{model.FromDate}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ProviderId != null)
            {
                paramsString += $@", {model.ProviderId}";
                // paramsString += $@", '298'";
            }
            else
            {
                paramsString += $@", null";
            }


            if (model.LocationId > 0)
            {
                paramsString += $@", {model.LocationId}";
            }
            else
            {
                paramsString += $@", null";
            }
            model.PageIndex -= 1;
            var query = $@"select * from ""widget_Table_otAppointmentDashboard1""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<PatientDashboardReport>(query);
        }
        /// <inheritdoc />
        public async Task<IEnumerable<OutReport>> OutPatientsAsync(OutPatientFilterModel model)
        {
            var paramsString = "";

            if (model.LocationId > 0)
            {
                paramsString += $@" {model.LocationId}";
            }
            else
            {
                paramsString += $@"null";
            }

            if (model.AppointmentNo != null)
            {
                paramsString += $@", '{model.AppointmentNo}'";
            }
            else
            {
                paramsString += $@",null";
            }

            if (model.DepartmentId != null)
            {
                paramsString += $@", array[" + model.DepartmentId + "]";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.ProviderId != null)
            {
                int[] testVal = { 11566 };
                // array[42]
                paramsString += $@", array[" + model.ProviderId + "]";

            }
            else
            {
                paramsString += $@", null";
            }
            if (model.PatientId != null)
            {
                paramsString += $@", array[" + model.PatientId + "]";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.UMRNo != null)
            {
                paramsString += $@",'{model.UMRNo}'";
            }
            else
            {
                paramsString += $@",null";
            }
            if (model.PatientReferredById != null)
            {
                //paramsString += $@",{model.PatientReferredById}";
                paramsString += $@", array[" + model.PatientReferredById + "]";
            }
            else
            {
                paramsString += $@",null";
            }
            if (model.ReferredByName != null)
            {
                paramsString += $@",'{model.ReferredByName}'";
            }
            else
            {
                paramsString += $@",null";
            }
            if (model.Mobile != null)
            {
                paramsString += $@",'{model.Mobile}'";
            }
            else
            {
                paramsString += $@",null";
            }
            if (model.PayTypeId != null)
            {
                paramsString += $@",'{model.PayTypeId}'";
            }
            else
            {
                paramsString += $@",null";
            }
            if (model.FromDate != null)
            {
                paramsString += $@", '{model.FromDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.AppointmentTypeId != null)
            {
                paramsString += $@", array[" + model.AppointmentTypeId + "]";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.PaymentStatus != null)
            {
                paramsString += $@", {model.PaymentStatus}";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.Status != null)
            {

                paramsString += $@", '{{{model.Status}}}'::text[]";
            }
            else
            {
                paramsString += $@", null";
            }

            var query = $@"Select  COUNT(*) OVER () AS ""TotalItems"",* from ""udf_uiReport_fetch_Appointments_Location1""({paramsString}, {model.PageIndex},{model.PageSize})";
            if (model.PageIndex <= 0)
            {
                try
                {
                    var responses = await this.unitOfWork.Current.QueryAsync<OutReport>(query);
                    return responses;
                }
                catch (Exception e)
                {
                    return null;
                }
            }
            model.PageIndex -= 1;
            query += " LIMIT " + model.PageSize + " offset " + (model.PageIndex * model.PageSize);
            var response = await this.unitOfWork.Current.QueryAsync<OutReport>(query);
            return response;
        }

        /// <inheritdoc />
        public Task<IEnumerable<ReceiptReportsModel>> FetchReceptionistReportsAsync(ReceiptReportsFilterModel model)
        {
            var paramsString = "";
            var query = "";
            if (model.AccountId != null)
            {
                paramsString += $@" '{'{' + model.AccountId + '}'}'";
            }
            else
            {
                paramsString += $@" null";
            }
            if (model.ProviderId != null)
            {
                paramsString += $@", '{model.ProviderId}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.LocationId != null)
            {
                paramsString += $@", '{model.LocationId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.RoleId != null)
            {
                paramsString += $@", '{'{' + model.RoleId + '}'}'";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.Type == "In Patient")
            {
                if (model.AdmissionNo != null)
                {
                    paramsString += $@", '{model.AdmissionNo}'";
                }
                else
                {
                    paramsString += $@", null";
                }
            }
            else
            {
                if (model.AppointmentNo != null)
                {
                    paramsString += $@", '{model.AppointmentNo}'";
                }
                else
                {
                    paramsString += $@", null";
                }
            }


            if (model.PatientId != null)
            {
                paramsString += $@", '{model.PatientId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.UMRNo != null)
            {
                paramsString += $@", '{model.UMRNo}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.PatientMobile != null)
            {
                paramsString += $@", '{model.PatientMobile}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.ReceiptId != null)
            {
                paramsString += $@", '{model.ReceiptId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.CreatedBy != null)
            {
                paramsString += $@", '{model.CreatedBy}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.PayTypeId != null)
            {
                paramsString += $@",'{model.PayTypeId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.FromDate != null)
            {
                paramsString += $@", '{model.FromDate}'::timestamp without time zone";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::timestamp without time zone";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.Type == "In Patient")
            {
                query = $@"Select * from ""udf_uiReport_Receipts_Admissions_Location""({paramsString})";
            }
            if (model.Type == "Out Patient")
            {
                query = $@"Select * from ""udf_uiReport_Receipts_Appointments_Location1""({paramsString})";
            }

            if (model.PageIndex <= 0)
            {
                return this.unitOfWork.Current.QueryAsync<ReceiptReportsModel>(query);
            }

            //model.PageIndex -= 1;
            //query += " LIMIT " + model.PageSize + " offset " + (model.PageIndex * model.PageSize);


            return this.unitOfWork.Current.QueryAsync<ReceiptReportsModel>(query);

        }

        /// <inheritdoc />
        public Task<IEnumerable<EmployeeRevenueReportsModel>> FetchEmployeeRevenueReportsAsync(EmployeeRevenueReportsFilterModel model)
        {
            var paramsString = "";

            paramsString += model.AccountId != null ? $@" '{model.AccountId}'" : $@" null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            paramsString += model.RoleId != null ? $@", '{model.RoleId}'" : $@", null";
            paramsString += model.FromDate != null ? $@", '{model.FromDate}'::timestamp without time zone" : $@", null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";

            //var query = $@"Select * from ""udf_Employee_Revenue""({paramsString})";
            var query = $@"Select * from ""udf_Employee_Revenue_Location""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<EmployeeRevenueReportsModel>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<InventoryPurchaseBillReportsModel>> FetchInventoryPurchaseRegisterReportsAsync(InventoryPurchaseRegisteryFilterModel model)
        {
            var where = "";

            //    if(!string.IsNullOrEmpty(model.FromDate) && !string.IsNullOrEmpty(model.ToDate))
            //    {
            //        where += $@" and '{model.FromDate}'::date <=IPH.""CreatedDate""::date and IPH.""CreatedDate""::date <='{model.ToDate}'::date ";
            //    }
            //    else if (string.IsNullOrEmpty(model.FromDate) && !string.IsNullOrEmpty(model.ToDate))
            //    {
            //        where += $@" and IPH.""CreatedDate""::Date <='{model.ToDate}'::date ";
            //    }
            //    else if(!string.IsNullOrEmpty(model.FromDate) && string.IsNullOrEmpty(model.ToDate))
            //    {
            //         where += $@" and '{model.FromDate}'::date <=IPH.""CreatedDate""::date ";
            //    }

            //    if (!string.IsNullOrEmpty(model.BillType))
            //    {
            //        where += $@" and IPH.""BillType"" ilike '%{model.BillType}%'";
            //    }

            //    if (model.SupplierId != null)
            //    {
            //        where += $@" and IPH.""SupplierId"" = '{model.SupplierId}'";
            //    }

            //    if (!string.IsNullOrEmpty(model.PurchaseBillNo))
            //    {
            //        where += $@" and IPH.""BillNumber"" ilike '%{model.PurchaseBillNo}%'";
            //    }

            //    var query = $@"Select IPH.""BillDate"" , IPH.""BillNumber"" as  ""PurchaseBillNo"" , IPH.""BillType"" , IPH.""BillAmount"",
            //                    IPH.""Taxes"", IPH.""NetAmount"",IPH.""Discount"",
            //                    S.""Name"" as ""SupplierName"" 
            //                    from ""InventoryPurchaseHeader"" IPH
            //                    join ""Supplier"" S on S.""SupplierId"" = IPH.""SupplierId"" 
            //                       {where} order by IPH.""CreatedDate"" desc ";

            //    return this.unitOfWork.Current.QueryAsync<InventoryPurchaseBillReportsModel>(query);
            if (model.SupplierId != null)
            {
                where += $@"'{model.SupplierId}'";
            }
            else
            {
                where += $@" null";
            }
            if (model.PurchaseBillNo != null)
            {
                where += $@", '{model.PurchaseBillNo}'";
            }
            else
            {
                where += $@", null";
            }
            if (model.BillType != null)
            {
                where += $@", '{model.BillType}'";
            }
            else
            {
                where += $@", null";
            }
            if (model.WareHouseId != null)
            {
                where += $@", '{model.WareHouseId}'";
            }
            else
            {
                where += $@", null";
            }
            if (model.DueDate != null)
            {
                where += $@", '{model.DueDate}'";
            }
            else
            {
                where += $@", null";
            }
            if (model.CreatedBy != null)
            {
                where += $@",'{model.CreatedBy}'";
            }
            else
            {
                where += $@", null";
            }
            if (model.FromDate != null)//
            {
                where += $@", '{model.FromDate}'::timestamp without time zone";
            }
            else
            {
                where += $@", null";
            }

            if (model.ToDate != null)
            {
                where += $@", '{model.ToDate}'::timestamp without time zone";
            }
            else
            {
                where += $@", null";
            }
            if (model.pharmacyBillType != null)
            {
                where += $@", '{model.pharmacyBillType}'";
            }
            else
            {
                where += $@", null";
            }
            if (model.LocationId != null)
            {
                where += $@", {model.LocationId}";
            }
            else
            {
                where += $@", null";
            }



            //if (model.PurchaseBillNo != null)
            //{
            //    where += $@"'{model.PurchaseBillNo}'";
            //}
            //else
            //{
            //    where += $@", null";
            //}
            var query = $@"SELECT * from ""udf_InventoryPurchase_Report""({where})";
            return this.unitOfWork.Current.QueryAsync<InventoryPurchaseBillReportsModel>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<InventoryStockReportModel>> FetchInventoryStockReportsAsync(InventoryStockReportFilterModel model)
        {
            var paramsString = "";
            if (model.CategoryId != null)
            {
                paramsString += $@"'{model.CategoryId}'";
            }
            else
            {
                paramsString += $@"null";
            }

            if (model.InventoryProductId != null)
            {
                paramsString += $@",'{model.InventoryProductId}'";
            }
            else
            {
                paramsString += $@", null";
            }

            var query = $@"SELECT * from ""udf_InventoryStockReport""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<InventoryStockReportModel>(query);
        }

        public Task<IEnumerable<IndentInventoryModel>> FetchIndentInventoryReportsAsync(IndentInventoryFilterModel model)
        {
            var where = "where 1=1";

            if (model.FromDate != null)
            {
                where += $@" and  sh.""ApprovedDate""::date  >= '{model.FromDate}' ";
            }

            if (model.ToDate != null)
            {
                where += $@" and  sh.""ApprovedDate""::date  <= '{model.ToDate}' ";
            }
            //if (model.ProductId != null)
            //{
            //    where += $@" and InD.""ProductId"" = '{model.ProductId}'";
            //}

            if (model.RequestedBy != null)
            {
                where += $@" and  IH.""CreatedBy"" = '{model.RequestedBy}' ";
            }
            if (model.ApprovedBy != null)
            {
                where += $@" and   IH.""ApprovedBy"" = '{model.ApprovedBy}' ";
            }
            if (!string.IsNullOrEmpty(model.Type))
            {
                if (model.Type == "approved")
                {
                    where += $@" and IH.""ApprovedBy"" is not null";
                }
            }
            if (model.IndentTo == "I")
            {
                if (model.ProductId != null)
                {
                    where += $@" and InD.""ProductId"" = '{model.ProductId}'";
                }
            }
            if (model.IndentTo != null)
            {
                where += $@" and IH.""IndentTo"" = '{model.IndentTo}'";
            }
            //var query = $@"SELECT distinct IH.""IndentHeaderId"",sh.""ApprovedDate"", IH.""DepartmentId"", IH.""RequiredDate"", IH.""ReasonForRequirement"", IH.""IndentTo"", 
            //                    IH.""ApprovedBy"", IH.""CreatedBy"", IH.""CreatedDate"",InD.""IndentDetailId"", InD.""ProductId"", InD.""Quantity"",sd.""Quantity"" ""IssuedQuantity"",
            //                    (case when IH.""IndentTo"" = 'I' then(Select ""ProductName"" from ""InventoryProduct"" where ""InventoryProductId"" = InD.""ProductId"") else (Select ""ProductName"" from ""PharmacyProduct"" where ""PharmacyProductId"" = InD.""ProductId"") end) as ""ProductName"",
            //                    A.""FullName"" as ""CreatedByName"", AR.""RoleName"" as ""CreatedByRoleName"",AA.""FullName"" as ""ApprovedByName"",AAR.""RoleName"" as ""ApprovedByRoleName"",
            //                    D.""DepartmentName"",RP.""RetailName""
            //                        FROM ""IndentHeader"" IH join ""IndentDetail"" InD on Ind.""IndentHeaderId"" = IH.""IndentHeaderId""
            //                        join ""Account"" A on A.""AccountId"" = IH.""CreatedBy""
            //                        join ""Department"" D on D.""DepartmentId"" = IH.""DepartmentId""
            //                        join ""Account"" AA on AA.""AccountId"" = IH.""ApprovedBy""
            //                        join ""Role"" AR on A.""RoleId"" = AR.""RoleId""
            //                        join ""Role"" AAR on AA.""RoleId"" = AAR.""RoleId""
            //                        join ""IssueHeader"" sh on sh.""IndentHeaderId"" = ih.""IndentHeaderId""
            //                        join ""IssueDetail"" sd on sd.""IssueHeaderId"" = sh.""IssueHeaderId""
            //                        left join ""RetailPharmacy"" RP on RP.""RetailPharmacyId"" = IH.""RetailPharmacyId""
            //                        {where} 
            //                        order by IH.""CreatedDate"" desc ";

            var query = $@" SELECT distinct IH.""IndentHeaderId"",sh.""ApprovedDate"", IH.""DepartmentId"", IH.""RequiredDate"", IH.""ReasonForRequirement"", IH.""IndentTo"", 
                                IH.""ApprovedBy"", IH.""CreatedBy"", IH.""CreatedDate"",InD.""IndentDetailId"", InD.""ProductId"", InD.""Quantity"",
								sd.""Quantity"" ""IssuedQuantity"",
                                (case when IH.""IndentTo"" = 'I' then(Select ""ProductName"" from ""InventoryProduct"" where ""InventoryProductId"" = InD.""ProductId"") else (Select ""ProductName"" from ""PharmacyProduct"" where ""PharmacyProductId"" = InD.""ProductId"") end) as ""ProductName"",
                                A.""FullName"" as ""CreatedByName"", AR.""RoleName"" as ""CreatedByRoleName"",AA.""FullName"" as ""ApprovedByName"",AAR.""RoleName"" as ""ApprovedByRoleName"",
                                D.""DepartmentName"",RP.""RetailName""
                                    FROM ""IndentHeader"" IH
                                    join ""IndentDetail"" InD on Ind.""IndentHeaderId"" = IH.""IndentHeaderId""
                                    join ""Account"" A on A.""AccountId"" = IH.""CreatedBy""
                                    join ""Department"" D on D.""DepartmentId"" = IH.""DepartmentId""
                                    join ""Account"" AA on AA.""AccountId"" = IH.""ApprovedBy""
                                    join ""Role"" AR on A.""RoleId"" = AR.""RoleId""
                                    join ""Role"" AAR on AA.""RoleId"" = AAR.""RoleId""
                                    join ""IssueHeader"" sh on sh.""IndentHeaderId"" = ih.""IndentHeaderId""
                                    join ""IssueDetail"" sd on sd.""IssueHeaderId"" = sh.""IssueHeaderId"" and sd.""ProductId"" = InD.""ProductId""
                                    left join ""RetailPharmacy"" RP on RP.""RetailPharmacyId"" = IH.""RetailPharmacyId""
                                        {where} 
                                   order by IH.""CreatedDate"" desc ";
            return this.unitOfWork.Current.QueryAsync<IndentInventoryModel>(query);
        }

        public Task<IEnumerable<PharmacyBillReportModel>> FetchPharmacyBillReportsAsync(IndentInventoryFilterModel model)
        {
            var paramsString = "";
            if (model.PharmacyBillNumber != null)
            {
                paramsString += $@"'{model.PharmacyBillNumber}',";
            }
            else
            {
                paramsString += $@"null,";
            }
            if (model.isFinalReport == true)
            {
                if (model.AccountId != null)
                {
                    paramsString += $@"'{model.AccountId}',";
                }
                else
                {
                    paramsString += $@"null,";
                }
            }
            if (model.PatientId != null)
            {
                paramsString += $@"'{model.PatientId}',";
            }
            else
            {
                paramsString += $@"null,";
            }
            if (model.PatientMobile != null)
            {
                paramsString += $@"'{model.PatientMobile}',";
            }
            else
            {
                paramsString += $@"null,";
            }
            if (model.UMRNo != null)
            {
                paramsString += $@"'{model.UMRNo}',";
            }
            else
            {
                paramsString += $@"null,";
            }
            if (model.PaidVia != null)
            {
                paramsString += $@"'{model.PaidVia}',";
            }
            else
            {
                paramsString += $@"null,";
            }
            if (model.ProviderId != null)
            {
                paramsString += $@"{model.ProviderId},";
            }
            else
            {
                paramsString += $@"null,";
            }
            if (model.CreatedBy != null)
            {
                paramsString += $@"'{model.CreatedBy}',";
            }
            else
            {
                paramsString += $@"null,";
            }
            if (model.FromDate != null)
            {
                paramsString += $@"'{model.FromDate}'::timestamp without time zone";
            }
            else
            {
                paramsString += $@"null";
            }

            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::timestamp without time zone";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.RetailName != null)
            {
                paramsString += $@",'{model.RetailName}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.RetailPharmacyId != null)
            {
                paramsString += $@",'{model.RetailPharmacyId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.LocationId != null)
            {
                paramsString += $@",'{model.LocationId}'";
            }
            else
            {
                paramsString += $@", null";
            }


            var query = "";
            if (model.isFinalReport == true)
            {
                if (model.pharmacyBillType != null)
                {
                    paramsString += $@", {model.pharmacyBillType}";
                }
                else
                {
                    paramsString += $@", null";
                }

                query = $@"SELECT COUNT(*) OVER () AS ""TotalItems"",* from ""udf_pharmacypatientbills_finalreport""({paramsString})";
            }
            else
            {
                query = $@"SELECT COUNT(*) OVER () AS ""TotalItems"",* from ""udf_PharmacyBills_Report""({paramsString})";
            }
            return this.unitOfWork.Current.QueryAsync<PharmacyBillReportModel>(query);
        }

        public Task<IEnumerable<PharmacyBillReportModel>> FetchPharamcyStockReportAsync(IndentInventoryFilterModel model)
        {
            var paramsString = "";

            if (model.ProductName != null)
            {
                paramsString += $@" '{model.ProductName}'";
            }
            else
            {
                paramsString += $@" null";
            }
            if (model.CategoryId != null)
            {
                paramsString += $@", '{model.CategoryId}'";
            }
            else
            {
                paramsString += $@", null";
            }
            if (model.BatchNumber != null)
            {
                paramsString += $@", '{model.BatchNumber}'";
            }
            else
            {
                paramsString += $@" ,null";
            }
            if (model.FromDate != null)
            {
                paramsString += $@", '{model.FromDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }

            if (model.ToDate != null)
            {
                paramsString += $@", '{model.ToDate}'::Date";
            }
            else
            {
                paramsString += $@", null";
            }
            model.PageIndex -= 1;
            //var query = $@"select * from ""udf_fetch_PharmacyStock_Report""({paramsString},{model.PageIndex},{model.PageSize})";

            //var result = this.unitOfWork.Current.QueryAsync<PharmacyBillReportModel>(query);

            //return result;
            var query = $@"select * from ""udf_fetch_PharmacyStock_Report""({paramsString}, {model.PageIndex},{model.PageSize})";


            //query += " LIMIT " + model.PageSize + " offset " + (model.PageIndex * model.PageSize);
            return this.unitOfWork.Current.QueryAsync<PharmacyBillReportModel>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<PharmacyStockModel>> FetchPharmacyRetailStockReportAsync(PharmacyStockModel model)
        {
            var where = $@"where 1=1 and (PS.""QuantityIn"" - PS.""QuantityOut"") > 0";

            if (!string.IsNullOrEmpty(model.CategoryName))
            {
                where += $@" and Cat.""Name"" ilike '%{model.CategoryName}%'";
            }

            if (!string.IsNullOrEmpty(model.ProductName))
            {
                where += $@" and  PP.""ProductName"" ilike '%{model.ProductName}%'";
            }

            if (!string.IsNullOrEmpty(model.GenericName))
            {
                where += $@" and  PP.""GenericName"" ilike '%{model.GenericName}%'";
            }

            if (!string.IsNullOrEmpty(model.BatchNumber))
            {
                where += $@" and  PS.""BatchNumber"" ilike '%{model.BatchNumber}%'";
            }

            if (model.PharmacyProductId > 0)
            {
                where += $@" and PS.""PharmacyProductId"" = {model.PharmacyProductId}";
            }

            if (model.RetailPharmacyId > 0)
            {
                where += $@" and RP.""RetailPharmacyId"" = {model.RetailPharmacyId}";
            }

            if (model.LocationId != null)
            {
                where += $@" and L.""LocationId"" = {model.LocationId}";
            }

            var query =
                $@"SELECT count(PS.*) over() as ""TotalItems"", PS.""PharmacyRetailStockId"",PS.""PharmacyStockId"", PS.""PharmacyProductId"", PS.""TaxId"", PS.""QuantityIn"", PS.""QuantityOut"", PS.""BatchNumber"", PS.""ExpiryDate"",
                                    PS.""PurchaseRate"", PS.""Mrp"", PS.""Barcode"", PP.""ProductName"",PP.""GenericName"",PS.""CreatedDate"",
                                    (PS.""QuantityIn"" - PS.""QuantityOut"") as ""AvailableQuantity"",Cat.""Name"" as ""CategoryName"",Tax.""Name""::int as ""TaxPercentage"",
	                                 ((PS.""QuantityIn"" - PS.""QuantityOut"")* PS.""Mrp"") as ""CurrentMrpAvailability"", 
									 ((PS.""QuantityIn"" - PS.""QuantityOut"")* PS.""PurchaseRate"") as ""CurrentPurchaseAvailability""
                                       ,RP.""RetailName"",L.""Name"" as ""LocationName"",PWH.""WareHouseName""
										FROM ""PharmacyRetailStock"" PS  
	                                    join ""PharmacyProduct"" PP on PP.""PharmacyProductId"" = PS.""PharmacyProductId""
	                                    join ""LookupValue"" Cat on Cat.""LookupValueId"" = PP.""CategoryId""
	                                    join ""LookupValue"" Tax on Tax.""LookupValueId"" = PS.""TaxId"" 
                                    join ""RetailWareHouseLink"" RWL on RWL.""RetailWareHouseLinkId"" = PS.""RetailWareHouseLinkId""
                                    join ""RetailPharmacy"" RP on RP.""RetailPharmacyId"" = RWL.""RetailPharmacyId""
                                    join ""PharmacyWareHouse"" PWH on PWH.""PharmacyWareHouseId"" = RWL.""PharmacyWareHouseId""
                  
                                    join ""Location"" L on L.""LocationId"" = PWH.""LocationId""
										{where}
										order by PS.""CreatedDate"" desc ";

            if (model.PageIndex != null && model.PageSize != null)
            {
                model.PageIndex = model.PageIndex > 0 ? model.PageIndex - 1 : model.PageIndex;

                query += $@" limit {model.PageSize} offset {model.PageSize * model.PageIndex}";
            }

            return await this.unitOfWork.Current.QueryAsync<PharmacyStockModel>(query);
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<PharmacyStockModel>> FetchPharmacyStockReportAsync(PharmacyStockModel model)
        {
            var where = $@"where 1=1 and (PS.""QuantityIn"" - PS.""QuantityOut"") > 0";

            if (!string.IsNullOrEmpty(model.CategoryName))
            {
                where += $@" and Cat.""Name"" ilike '%{model.CategoryName}%'";
            }

            if (!string.IsNullOrEmpty(model.ProductName))
            {
                where += $@" and  PP.""ProductName"" ilike '%{model.ProductName}%'";
            }

            if (!string.IsNullOrEmpty(model.GenericName))
            {
                where += $@" and  PP.""GenericName"" ilike '%{model.GenericName}%'";
            }

            if (model.PharmacyProductId > 0)
            {
                where += $@" and PS.""PharmacyProductId"" = {model.PharmacyProductId}";
            }

            if (model.PharmacyStockId > 0)
            {
                where += $@" and PS.""PharmacyStockId"" = {model.PharmacyStockId}";
            }

            if (!string.IsNullOrEmpty(model.BatchNumber))
            {
                where += $@" and  PS.""BatchNumber"" ilike '%{model.BatchNumber}%'";
            }

            if (model.PharmacyWareHouseId > 0)
            {
                where += $@" and PS.""PharmacyWareHouseId"" = {model.PharmacyWareHouseId}";
            }

            if (model.LocationId != null)
            {
                where += $@" and L.""LocationId"" = {model.LocationId}";
            }

            var query =
                $@"SELECT count(PS.*) over() as ""TotalItems"", PS.""PharmacyStockId"", PS.""PharmacyProductId"", PS.""TaxId"", PS.""QuantityIn"", PS.""QuantityOut"", PS.""BatchNumber"", PS.""ExpiryDate"",
                                    PS.""PurchaseRate"", PS.""Mrp"", PS.""Barcode"", PS.""MrpChangeReason"", PP.""ProductName"",PP.""GenericName"",PS.""CreatedDate"",
                                    (PS.""QuantityIn"" - PS.""QuantityOut"") as ""AvailableQuantity"",Cat.""Name"" as ""CategoryName"",Tax.""Name""::int as ""TaxPercentage"",
	                                    ((PS.""QuantityIn"" - PS.""QuantityOut"")* PS.""Mrp"") as ""CurrentMrpAvailability"", 
									 ((PS.""QuantityIn"" - PS.""QuantityOut"")* PS.""PurchaseRate"") as ""CurrentPurchaseAvailability""
                                         ,PW.""WareHouseName"",L.""Name"" as ""LocationName""    
										FROM ""PharmacyStock"" PS  
	                                    join ""PharmacyProduct"" PP on PP.""PharmacyProductId"" = PS.""PharmacyProductId""
	                                    join ""LookupValue"" Cat on Cat.""LookupValueId"" = PP.""CategoryId""
	                                    join ""LookupValue"" Tax on Tax.""LookupValueId"" = PS.""TaxId"" 
                                        join ""PharmacyWareHouse"" PW on PW.""PharmacyWareHouseId""=PS.""PharmacyWareHouseId""
                                        join ""Location"" L on L.""LocationId"" = PW.""LocationId""
										{where}
										order by PP.""ProductName"" desc";

            if (model.PageIndex != null && model.PageSize != null)
            {
                model.PageIndex = model.PageIndex > 0 ? model.PageIndex - 1 : model.PageIndex;

                query += $@" limit {model.PageSize} offset {model.PageSize * model.PageIndex}";
            }

            return await this.unitOfWork.Current.QueryAsync<PharmacyStockModel>(query);
        }

        /// <inheritdoc/>
        public Task<IEnumerable<EmployeeRevenueReportsModel>> FetchDoctorRevenueReportsAsync(EmployeeRevenueReportsFilterModel model)
        {
            var paramsString = "";
            paramsString += model.ProviderId != null ? $@" '{model.ProviderId}'" : $@" null";
            paramsString += model.LocationId > 0 ? $@", {model.LocationId}" : $@" null";
            //paramsString += model.FromDate != null ? $@", '{model.FromDate}'::Date" : $@", null";
            //paramsString += model.ToDate != null ? $@", '{model.ToDate}'::Date" : $@", null";
            paramsString += model.FromDate != null ? $@", '{model.FromDate}'::timestamp without time zone" : $@", null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";
            //var query = $@"Select * from ""udf_Doctor_Revenue1""({paramsString})";
            var query = $@"Select * from ""udf_Doctor_Revenue_location""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<EmployeeRevenueReportsModel>(query);
        }

        //public async Task<IEnumerable<PharmacyIndentHeaderModel>> FetchPharmacyIndentIssueReportsAsync(PharmacyIndentHeaderModel model)
        //{
        //    var where = "where 1 = 1";
        //    //if (model.RequestDate != null)
        //    //{
        //    //    where += $@" and PIH.""CreatedDate""::date = '{model.RequestDate?.ToString("yyyy-MM-dd")}'";
        //    //}
        //    if (model.FromDate != null)
        //    {
        //        where += $@" and  PIH.""CreatedDate""::date  >= '{model.FromDate?.ToString("yyyy-MM-dd")}' ";
        //    }

        //    if (model.ToDate != null)
        //    {
        //        where += $@" and  PIH.""CreatedDate""::date  <= '{model.ToDate?.ToString("yyyy-MM-dd")}' ";
        //    }
        //    if (model.PatientId != null)
        //    {
        //        where += $@" and P.""PatientId"" = '{model.PatientId}'";
        //    }
        //    if (model.UMRNo != null)
        //    {
        //        where += $@" and  P.""UMRNo"" ilike '%{model.UMRNo}%'";
        //    }
        //    if (model.Mobile != null)
        //    {
        //        where += $@" and  P.""Mobile"" ilike '%{model.Mobile}%'";
        //    }
        //    if (model.ProviderId != null)
        //    {
        //        where += $@" and  Pr.""ProviderId"" = '{model.ProviderId}'";
        //    }
        //    if (model.ApprovedBy != null)
        //    {
        //        where += $@" and  PIH.""ApprovedBy"" = '{model.ApprovedBy}'";
        //    }
        //    if (model.RequestedBy != null)
        //    {
        //        where += $@" and  PIH.""CreatedBy"" = '{model.RequestedBy}'";
        //    }
        //    if (model.Quantity != null)
        //    {
        //        where += $@" and PII.""Quantity"" = '{model.Quantity}'";
        //    }
        //    if (model.OverallTotal != null)
        //    {
        //        where += $@" and PHIH.""OverallTotal"" = '{model.OverallTotal}'";
        //    }
        //    if (model.ProductName != null)
        //    {
        //        where += $@" and PII.""ProductName"" = '{model.ProductName}'";
        //    }
        //    var query =
        //        $@"SELECT distinct PIH.""PharmacyIndentHeaderId"",count(PIH.*) over () as ""TotalItems"",P.""FullName"" AS ""PatientName"",P.""Age"",
        //                            P.""Mobile"",P.""Gender"",P.""UMRNo"",Pr.""ProviderId"",Pr.""FullName"",PIH.""IndentDate"", PIH.""DepartmentId"",D.""DepartmentName"", PIH.""RequiredDate"", PIH.""Reason"",
        //                            PIH.""AdmissionId"",PII.""Quantity"",PHIH.""OverallTotal"", PII.""PharmacyProductId"", PP.""ProductName"",PIH.""ApprovedBy"",AA.""FullName"" as ""ApprovedByName"", PIH.""CreatedBy"", 
        //                            PIH.""CreatedDate"",PIH.""Status"",A.""FullName"" as ""CreatedByName"",
        //                             count(PID.*) over() as ""NumRequestedItems""
        //		FROM ""PharmacyIndentHeader"" PIH	
        //		join ""Admission"" Ad on Ad.""AdmissionId"" = PIH.""AdmissionId""
        //		join ""Patient"" P on P.""PatientId"" = Ad.""PatientId""
        //                             join ""Account"" A on A.""AccountId"" = PIH.""CreatedBy""
        //                             left join ""Account"" AA on AA.""AccountId"" = PIH.""ApprovedBy""
        //                             left join ""Department"" D on D.""DepartmentId"" = PIH.""DepartmentId""
        //		left join ""Provider"" Pr on Pr.""DepartmentId"" = D.""DepartmentId""
        //                                left join ""PharmacyIndentDetail"" PII on PII.""PharmacyIndentHeaderId"" = PIH.""PharmacyIndentHeaderId""
        //                                left join ""PharmacyIssueHeader"" PHIH on PHIH.""PharmacyIndentHeaderId"" = PIH.""PharmacyIndentHeaderId""

        //                                join ""PharmacyIndentDetail"" PID on PID.""PharmacyIndentHeaderId"" = PIH.""PharmacyIndentHeaderId""
        //                                join ""PharmacyProduct"" pp on pp.""PharmacyProductId"" = PID.""PharmacyProductId""

        //                                { where}
        //                             Order by PIH.""CreatedDate"" desc";

        //    return await this.unitOfWork.Current.QueryAsync<PharmacyIndentHeaderModel>(query);
        //}

        /// <inheritdoc />
        public async Task<IEnumerable<PharmacyIndentHeaderModel>> FetchPharmacyIndentIssueReportsAsync(PharmacyIndentHeaderModel model)
        {
            var where = "where 1 = 1";

            //if (model.RequestDate != null)
            //{
            //    where += $@" and PIH.""CreatedDate""::date = '{model.RequestDate?.ToString("yyyy-MM-dd")}'";
            //}
            if (model.FromDate != null)
            {
                where += $@" and  PIH.""CreatedDate""::date  >= '{model.FromDate?.ToString("yyyy-MM-dd")}' ";
            }

            if (model.ToDate != null)
            {
                where += $@" and  PIH.""CreatedDate""::date  <= '{model.ToDate?.ToString("yyyy-MM-dd")}' ";
            }
            if (model.PatientId != null)
            {
                where += $@" and P.""PatientId"" = '{model.PatientId}'";
            }
            if (model.UMRNo != null)
            {
                where += $@" and  P.""UMRNo"" ilike '%{model.UMRNo}%'";
            }
            if (model.Mobile != null)
            {
                where += $@" and  P.""Mobile"" ilike '%{model.Mobile}%'";
            }
            if (model.ProviderId != null)
            {
                where += $@" and  Pr.""ProviderId"" = '{model.ProviderId}'";
            }
            if (model.ApprovedBy != null)
            {
                where += $@" and  PIH.""ApprovedBy"" = '{model.ApprovedBy}'";
            }
            if (model.RequestedBy != null)
            {
                where += $@" and  PIH.""CreatedBy"" = '{model.RequestedBy}'";
            }
            if (model.LocationId != null)
            {
                where += $@" and PIH.""LocationId""={model.LocationId} ";
            }
            //if (model.Quantity != null)
            //{
            //    where += $@" and PII.""Quantity"" = '{model.Quantity}'";
            //}
            //if (model.OverallTotal != null)
            //{
            //    where += $@" and PHIH.""OverallTotal"" = '{model.OverallTotal}'";
            //}
            //if (model.ProductName != null)
            //{
            //    where += $@" and PPID.""ProductName"" = '{model.ProductName}'";
            //}
            var query =
                $@"SELECT distinct PIH.""PharmacyIndentHeaderId"",count(PIH.*) over () as ""TotalItems"",P.""FullName"" AS ""PatientName"",P.""Age"",
                                    P.""Mobile"",P.""Gender"",P.""UMRNo"",Pr.""ProviderId"",Pr.""FullName"",PIH.""IndentDate"", PIH.""DepartmentId"",D.""DepartmentName"", PIH.""RequiredDate"", PIH.""Reason"",
                                    PIH.""AdmissionId"", PIH.""ApprovedBy"", PIH.""ApprovedDate"", AA.""FullName"" as ""ApprovedByName"", PIH.""CreatedBy"", PIH.""CreatedDate"",PIH.""Status"",A.""FullName"" as ""CreatedByName"",
                                    count(PID.*) over() as ""NumRequestedItems"",PPID.""ProductName"" as ""IssueProductName"", PII.""Quantity"" as ""IssueQuantity"",
                                    PII.""NetAmount"" as ""IssueNetAmount"", PII.""DiscountAmount"" as ""IssueDiscountAmount"",
                                    Cate.""Name"" as ""IssueCategoryName""
                                    FROM ""PharmacyIndentHeader"" PIH	
                                    join ""Admission"" Ad on Ad.""AdmissionId"" = PIH.""AdmissionId""
                                    join ""Patient"" P on P.""PatientId"" = Ad.""PatientId""
                                    join ""Account"" A on A.""AccountId"" = PIH.""CreatedBy""	                                    
                                    join ""PharmacyIndentDetail"" PID on PID.""PharmacyIndentHeaderId"" = PIH.""PharmacyIndentHeaderId""
                                    join ""PharmacyProduct"" pp on pp.""PharmacyProductId"" = PID.""PharmacyProductId""
                                    left join ""Account"" AA on AA.""AccountId"" = PIH.""ApprovedBy""
                                    left join ""Department"" D on D.""DepartmentId"" = PIH.""DepartmentId""
                                    left join ""Provider"" Pr on Pr.""ProviderId"" = Ad.""ProviderId""
                                    left join ""PharmacyIssueHeader"" PHIH on PHIH.""PharmacyIndentHeaderId"" = PIH.""PharmacyIndentHeaderId""
                                    left join ""PharmacyIssueDetail"" PII on PII.""PharmacyIssueHeaderId"" = PHIH.""PharmacyIssueHeaderId""
                                    left join ""PharmacyProduct"" PPID on PPID.""PharmacyProductId"" = PII.""PharmacyProductId""
                                    left join ""LookupValue"" Cate on Cate.""LookupValueId"" = PPID.""CategoryId"" 


	
										{where}  and PIH.""ApprovedBy"" is not null
	                                    Order by PIH.""CreatedDate"" desc";

            return await this.unitOfWork.Current.QueryAsync<PharmacyIndentHeaderModel>(query);
        }

        /// <inheritdoc />
        public async Task<IndentInventoryFilterModel> FetchFromDateAsync()
        {
            var query = $@"select ""SaleDate"" from ""PharmacySaleHeader"" order by 1 asc limit 1";
            return this.unitOfWork.Current.QueryFirstOrDefault<IndentInventoryFilterModel>(query);
        }

        /// <inheritdoc />
        public async Task<IndentInventoryFilterModel> FetchToDateAsync()
        {
            var query = $@"select ""SaleDate"" from ""PharmacySaleHeader"" order by 1 desc limit 1";
            return this.unitOfWork.Current.QueryFirstOrDefault<IndentInventoryFilterModel>(query);
        }


        /// <inheritdoc />
        //public async Task<IEnumerable<PharmacyProductProfit>> FetchProductProfitReportAsync(PharmacyProductProfit model)
        //{
        //    var where = "where 1 = 1";

        //    if (model.PharmacyProductId > 0)
        //    {
        //        where += $@" and PP.""PharmacyProductId"" = {model.PharmacyProductId}";
        //    }
        //    if (model.RetailPharmacyId > 0)
        //    {
        //        where += $@" and PRS.""RetailPharmacyId"" = {model.RetailPharmacyId}";
        //    }
        //    //if (model.UserBasedStore > 0)
        //    //{
        //    //    //var id = Convert.ToInt32(model.AllowedAccountId);
        //    //    where += $@" and  pd.""AllowedAccountId""= {model.UserBasedStore}";
        //    //}
        //    var query =
        //        $@"SELECT  --S.""Name"" as ""SupplierName"",
        //                    R.""RetailName"",PP.""ProductName"",
        //                 PRS.""BatchNumber"" ,PRS.""QuantityIn"", PRS.""QuantityOut"", PRS.""PurchaseRate"", PRS.""Mrp"", PRS.""CreatedDate""
        //            -- ,PPH.""SupplierId""
        //                , PRS.""PharmacyProductId"",PRS.""RetailPharmacyId""
        //                from ""PharmacyRetailStock"" PRS
        //          --  join ""PharmacyPurchaseDetail"" PPD ON PRS.""PharmacyProductId"" = PPD.""PharmacyProductId""
        //          --  join ""PharmacyPurchaseHeader"" PPH ON PPD.""PharmacyPurchaseHeaderId"" = PPH.""PharmacyPurchaseHeaderId""
        //          --  join ""Supplier"" S ON PPH.""SupplierId"" = S.""SupplierId""
        //            Join ""RetailPharmacy"" R ON PRS.""RetailPharmacyId"" = R.""RetailPharmacyId""
        //            Join ""PharmacyProduct"" PP ON PP.""PharmacyProductId"" = PRS.""PharmacyProductId""
        //            {where} and PRS.""QuantityOut"" > 0
        //            Order by PRS.""CreatedDate"" desc";

        //    return await this.unitOfWork.Current.QueryAsync<PharmacyProductProfit>(query);
        //}


        /// <inheritdoc />
        public async Task<IEnumerable<RegistrationBillModel>> FetchPatientRegistrationCount(RegistrationBillModel model)
        {
            var where = $@"where R.""ReceiptAreaTypeId""='{(int)ReceiptAreaType.PatientRegistration}'";
            if (model.FromDate != null)
            {
                where += $@" and  R.""CreatedDate""::date  >= '{model.FromDate?.ToString("yyyy-MM-dd")}' ";
            }

            if (model.ToDate != null)
            {
                where += $@" and  R.""CreatedDate""::date  <= '{model.ToDate?.ToString("yyyy-MM-dd")}' ";
            }

            if (model.LocationId != null)
            {
                where += $@" and  P.""LocationId"" = {model.LocationId} ";
            }
            if (model.UMRNo != null)
            {
                where += $@" and  P.""UMRNo"" = 'UMR{model.UMRNo}'";
            }
            if (model.PayTypeId != null)
            {
                where += $@" and  R.""PayTypeId"" = {model.PayTypeId}";
            }
            if (model.Mobile != null)
            {
                where += $@" and  P.""Mobile"" = '{model.Mobile}'";
            }
            if (model.PatientId != null)
            {
                where += $@" and  P.""PatientId"" = '{model.PatientId}'";
            }
            if (model.CreatedBy != null && model.CreatedBy != 0)
            {
                where += $@" and  A.""AccountId"" = '{model.CreatedBy}'";
            }
            if (model.AccountId != null && model.AccountId != 0)
            {
                where += $@" and  A.""AccountId"" = '{model.AccountId}'";
            }

            //        var query = $@"SELECT PRD.*,A.""FullName"" as ""CreatedByName"", P.""FullName"" as ""PatientName"", R.""ReceiptId"",
            //P.""Age"",P.""Gender"",P.""UMRNo"",P.""Mobile"",PT.""PayTypeName""	                           
            //                         FROM ""PatientRegistrationDetail"" PRD
            //                         join ""Patient"" P on P.""PatientId"" = PRD.""PatientId""
            //                         join ""Account"" A on A.""AccountId"" = PRD.""CreatedBy""
            //                         join ""PayType"" PT on PT.""PayTypeId"" = PRD.""PayTypeId""
            //                            left join ""Receipt"" R on R.""PatientRegistrationDetailId""=PRD.""PatientRegistrationDetailId""    
            //                            {where} order by 1 desc";

            var query = $@"SELECT 
                                R.*, R.""Cost"" as ""Charge"",
                                A.""FullName"" as ""CreatedByName"",
                                P.""FullName"" as ""PatientName"",P.""FirstName"",P.""MiddleName"",P.""LastName"",
                                P.""Age"",P.""Gender"",P.""UMRNo"",P.""Mobile"",P.""DateOfBirth"",
                                R.""ReceiptId"",
				                PT.""PayTypeName""	

	                            FROM ""Receipt"" R
	                            join ""Patient"" P on P.""PatientId"" = R.""RespectiveId""  
	                            join ""Account"" A on A.""AccountId"" = R.""CreatedBy""
	                            join ""PayType"" PT on PT.""PayTypeId"" = R.""PayTypeId""
                               -- left join ""Receipt"" R on R.""PatientRegistrationDetailId""=PRD.""PatientRegistrationDetailId""    
                                {where} order by 1 desc";
            return await this.unitOfWork.Current.QueryAsync<RegistrationBillModel>(query);
        }

        public Task<IEnumerable<EmployeeRevenueReportsModel>> FetchDoctorNewRevenueReportsAsync(EmployeeRevenueReportsFilterModel model)
        {
            var paramsString = "";
            paramsString += model.ProviderId != null ? $@" '{model.ProviderId}'" : $@" null";
            paramsString += model.LocationId > 0 ? $@", {model.LocationId}" : $@", null";
            paramsString += model.FromDate != null ? $@", '{model.FromDate}'::Date" : $@", null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::Date" : $@", null";
            //    paramsString += model.FromDate != null ? $@", '{model.FromDate}'::timestamp without time zone" : $@", null";
            //    paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";
            //var query = $@"Select * from ""udf_Doctor_Revenue1""({paramsString})";
            // var query = $@"Select * from ""udf_Doctor_Revenue_location""({paramsString})";
            //var query = $@"Select * from ""udf_doctor_new_revenue""({paramsString})";
            var query = $@"Select * from ""udf_Doctor_New_Revenue""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<EmployeeRevenueReportsModel>(query);
        }
        /// <inheritdoc />
        public Task<IEnumerable<EmployeeRevenueReportsModel>> FetchEmployeeNewRevenueReportsAsync(EmployeeRevenueReportsFilterModel model)
        {
            var paramsString = "";

            //  paramsString += model.AccountId != null ? $@" '{model.AccountId}'" : $@" null";
            paramsString += model.AccountId != null ? $@" null" : $@" null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            paramsString += model.RoleId != null ? $@", '{model.RoleId}'" : $@", null";
            paramsString += model.FromDate != null ? $@", '{model.FromDate}'::Date" : $@", null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::Date" : $@", null";

            //var query = $@"Select * from ""udf_Employee_Revenue""({paramsString})";
            //var query = $@"Select * from ""udf_emloyee_new_revenue""({paramsString})";
            var query = $@"Select * from ""udf_Emloyee_New_Revenue""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<EmployeeRevenueReportsModel>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<CancelAppointmentReport>> FetchCancelledAppointmentReportsAsync(OutPatientFilterModel model)
        {
            var where = "where 1=1";

            if (model.FromDate != null)
            {
                where += $@" and  A.""ModifiedDate""::date  >= '{model.FromDate}' ";
            }


            if (model.ToDate != null)
            {
                where += $@" and  A.""ModifiedDate""::date  <= '{model.ToDate}' ";
            }

            if (model.PatientId != null)
            {
                where += $@" and  A.""PatientId"" = '{model.PatientId}'";
            }
            var query = $@"select A.*,
                        P.""Salutation"",P.""FullName"" as ""PatientName"",P.""FirstName"",P.""MiddleName"",P.""LastName"",
                        P.""DateOfBirth"",P.""Age"" as ""PatientAge"",P.""Gender"" as ""PatientGender"",P.""UMRNo"",P.""Mobile"",
                        DR.""FullName"" as ""ProviderName"",A.""ModifiedDate"" as ""FromDate"",A.""ModifiedDate"" as ""ToDate"", 
                        R.""ReceiptId"", R.""Cost"" as ""TotalAmount"",R.""ReceiptTypeId"",
                    RA.""FullName"" as ""ReceiptCreatedByName"",R.""CreatedDate"" as ""ReceiptDate"",PT.""PayTypeName"" as ""PaymentType""
                    from ""Appointment"" A
                    left join ""Patient"" P on P.""PatientId""=A.""PatientId""
                    left join ""Provider"" DR on DR.""ProviderId""=A.""ProviderId""
                    left join ""Receipt"" R on R.""RespectiveId""=A.""AppointmentId""   and R.""ReceiptAreaTypeId""=5
                    left join ""Account"" RA on RA.""AccountId""=R.""CreatedBy""
                    left join ""PayType"" PT on PT.""PayTypeId""=R.""PayTypeId""
               {where} and A.""Status""='C' and A.""LocationId""={model.LocationId}  ";

            return this.unitOfWork.Current.QueryAsync<CancelAppointmentReport>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<CancelAppointmentReport>> FetchPatientAppointmentReportsAsync(OutPatientFilterModel model)
        {
            var where = "where 1=1";
            if (model.PatientId != null)
            {
                where += $@" and  P.""PatientId"" = '{model.PatientId}'";
            }
            //       var query = $@"select A.*,
            //                   P.""Salutation"",l.""Name"" as ""LocationName"",d.""DepartmentName"",ap.""Name"" as ""AppointmentTypeName"",P.""FullName"" as ""PatientName"",P.""Age"" as ""PatientAge"",P.""Gender"" as ""PatientGender"",P.""UMRNo"",P.""Mobile"",
            //                   DR.""FullName"" as ""ProviderName"",
            //                   R.""ReceiptId"", R.""Cost"" as ""TotalAmount"",R.""ReceiptTypeId"",
            //               RA.""FullName"" as ""ReceiptCreatedByName"",R.""CreatedDate"" as ""ReceiptDate"",PT.""PayTypeName"" as ""PaymentType""
            //               from ""Appointment"" A
            //               left join ""Patient"" P on P.""PatientId""=A.""PatientId""
            //left join ""AppointmentType"" ap on ap.""AppointmentTypeId"" = A.""AppointmentTypeId""
            //               left join ""Provider"" DR on DR.""ProviderId""=A.""ProviderId""
            //left join ""Department"" d on DR.""DepartmentId"" = d.""DepartmentId""                   

            //     left join ""Receipt"" R on R.""AppointmentId""=A.""AppointmentId"" 
            //               join ""Account"" RA on RA.""AccountId""=R.""CreatedBy""
            //               join ""PayType"" PT on PT.""PayTypeId""=R.""PayTypeId""
            //left join ""Location"" l on l.""LocationId"" = A.""LocationId""
            //           {where} order by A.""AppointmentDate"" desc";

            //       var query = $@"

            //               select A.*,
            //                   P.""Salutation"",
            //	l.""Name"" as ""LocationName"",
            //	d.""DepartmentName"",
            //	V.""VisitorName"" as ""AppointmentTypeName"",
            //	P.""FullName"" as ""PatientName"",P.""Age"" as ""PatientAge"",P.""Gender"" as ""PatientGender"",P.""UMRNo"",P.""Mobile"",
            //                 DR.""FullName"" as ""ProviderName"",
            //               R.""ReceiptId"", R.""Cost"" as ""TotalAmount"",R.""ReceiptTypeId"",
            //               RA.""FullName"" as ""ReceiptCreatedByName"",
            //R.""CreatedDate"" as ""ReceiptDate"",
            //PT.""PayTypeName"" as ""PaymentType"",
            //               (PA.""FreeFollowUpDaysLimit"" - (select Count(""FollowUpForAppointmentId"")  from ""Appointment""   where ""PatientId""={model.PatientId} and ""FollowUpForAppointmentId"" is not null)) as ""FreeFollowUpDaysLimit"",
            //                A.""AppointmentDate""+ pa.""FreeFollowUpDays""::int as ""FreeFollowUpValidityDate""
            //               from ""Appointment"" A
            //               left join ""Patient"" P on P.""PatientId""=A.""PatientId""
            //left join ""AppointmentType"" ap on ap.""AppointmentTypeId"" = A.""AppointmentTypeId""
            //                join ""Provider"" DR on DR.""ProviderId""=A.""ProviderId""
            //left join ""Department"" d on DR.""DepartmentId"" = d.""DepartmentId""
            //             left join ""Receipt"" R on R.""RespectiveId""=A.""AppointmentId""  and ""ReceiptAreaMainId""=4
            //          join ""Account"" RA on RA.""AccountId""=A.""CreatedBy""
            //            left join ""PayType"" PT on PT.""PayTypeId""=A.""PayTypeId""
            //left join ""Location"" l on l.""LocationId"" = A.""LocationId""
            //              join ""VisitType"" V on V.""VisitTypeId""=A.""VisitTypeId""
            //            join ""ProviderAvailability"" PA on PA.""ProviderAvailabilityId""=A.""ProviderAvailabilityId"" 

            //           {where}  order by A.""AppointmentDate"" desc";

            var query = $@" select A.*,
                        P.""Salutation"",
						l.""Name"" as ""LocationName"",
						d.""DepartmentName"",
						V.""VisitorName"" as ""AppointmentTypeName"",
						P.""FullName"" as ""PatientName"",P.""Age"" as ""PatientAge"",P.""Gender"" as ""PatientGender"",P.""UMRNo"",P.""Mobile"",
                      DR.""FullName"" as ""ProviderName"",
                    R.""ReceiptId"", R.""Cost"" as ""TotalAmount"",R.""ReceiptTypeId"",
                    RA.""FullName"" as ""ReceiptCreatedByName"",
					R.""CreatedDate"" as ""ReceiptDate"",
					PT.""PayTypeName"" as ""PaymentType"",
                    (DSM.""FollowUpDaysLimit"" - (select Count(ap.""FollowUpForAppointmentId"")  
                                                   from ""Appointment"" ap
                                                   join ""DoctorSpecializationChargeModuleDetails"" pl on pl.""DoctorSpecializationChargeModuleDetailsId""= ap.""DoctorSpecializationChargeModuleDetailsId""
                                                    Join ""DoctorSpecializationChargeModuleCategory"" DSC on DSC.""DoctorSpecializationChargeModuleCategoryId"" = pl.""DoctorSpecializationChargeModuleCategoryId"" and DSC.""Active"" is true
                                                    JOIN ""ChargeModuleTemplate"" CMT ON CMT.""ChargeModuleTemplateId"" = DSC.""ChargeModuleTemplateId"" and CMT.""IsInUse"" is true
                              
                                                   where ""PatientId""={model.PatientId} and ""Status"" <> 'C'
                                                   and  (ap.""AppointmentDate""::date >= CMT.""StartDate""::date AND ap.""AppointmentDate""::date <= CMT.""EndDate""::date)
                                                   and ""FollowUpForAppointmentId"" is not null)) as ""FreeFollowUpDaysLimit"",
                     A.""AppointmentDate""+ DSM.""FollowUpDays""::int as ""FreeFollowUpValidityDate""
                    from ""Appointment"" A
                    left join ""Patient"" P on P.""PatientId""=A.""PatientId""
					left join ""AppointmentType"" ap on ap.""AppointmentTypeId"" = A.""AppointmentTypeId""
                     join ""Provider"" DR on DR.""ProviderId""=A.""ProviderId""
					left join ""Department"" d on DR.""DepartmentId"" = d.""DepartmentId""
                  left join ""Receipt"" R on R.""RespectiveId""=A.""AppointmentId""  and ""ReceiptAreaMainId""=4
               join ""Account"" RA on RA.""AccountId""=A.""CreatedBy""
                 left join ""PayType"" PT on PT.""PayTypeId""=A.""PayTypeId""
					left join ""Location"" l on l.""LocationId"" = A.""LocationId""
                   join ""VisitType"" V on V.""VisitTypeId""=A.""VisitTypeId""
                 --join ""ProviderAvailability"" PA on PA.""ProviderAvailabilityId""=A.""ProviderAvailabilityId""
                left join ""DoctorSpecializationChargeModuleDetails"" PA on PA.""DoctorSpecializationChargeModuleDetailsId"" = A.""DoctorSpecializationChargeModuleDetailsId"" 
                left Join ""DoctorSpecializationMap"" DSM on DSM.""DoctorSpecializationMapId"" = PA.""ReferenceId""

                 {where} order by A.""AppointmentDate"" desc";

            return this.unitOfWork.Current.QueryAsync<CancelAppointmentReport>(query);
        }

        /// <inheritdoc />
        public Task<IEnumerable<TransactionModel>> FetchTransactionReportsAsync(TransactionReportsFilterModel model)
        {

            //var where = "where 1=1";

            //if (model.FromDate != null)
            //{
            //    where += $@" and  T.""CreatedDate""::date  >= '{model.FromDate}'::timestamp without time zone ";
            //}

            //if (model.ToDate != null)
            //{
            //    where += $@" and  T.""CreatedDate""::date  <= '{model.ToDate}'::timestamp without time zone ";
            //}

            //if (model.LocationId != null)
            //{
            //    where += $@" and  T.""LocationId""= '{model.LocationId}'";

            //}
            //if (model.ReceiptAreaTypeId != null)
            //{
            //    where += $@" and  RA.""ReceiptAreaTypeId""= '{model.ReceiptAreaTypeId}'";

            //}


            //var query = $@" with appDiscountData as (
            //                    SELECT A.""Amount"",A.""Discount"",A.""Total"", R.""Cost"",AT.""AppointmentTransactionId""
            //                from ""Receipt"" R
            //                join ""Appointment"" A on A.""AppointmentId"" = R.""RespectiveId""
            //                join ""AppointmentTransaction"" AT on AT.""AppointmentTransactionId"" = R.""TransactionId""
            //                where R.""ReceiptAreaTypeId"" = 4 and A.""Discount"" > 0
            //                )  

            //            select  COUNT(*) OVER () AS ""TotalItems"" ,T.*
            //                ,RT.""ReceiptTypeName"",RA.""Name"" as ""ReceiptAreaType"",RA.""ReceiptAreaTypeId"" as ""AreaId"",PM.""PaymentType"",R.""Cost"",R.""ReceiptId""
            //    ,AD.""Amount""  as ""AppAmount"",AD.""Discount"" as ""AppDiscount"",AD.""Total"" as ""AppTotal"" 
            //        from ""AppointmentTransaction""  T
            //                left Join ""ReceiptType"" RT on RT.""ReceiptTypeId""=T.""ReceiptTypeId"" --............cash/refund..........
            //                left Join ""ReceiptAreaType"" RA on   RA.""ReceiptAreaTypeId""=T.""ReceiptAreaTypeId""
            //                left join ""PaymentMode"" PM on PM.""PaymentModeId""=T.""PaymentModeId""
            //                Join ""Receipt"" R on R.""TransactionId""=T.""AppointmentTransactionId""

            //            left join appDiscountData  AD on AD.""AppointmentTransactionId""=T.""AppointmentTransactionId""
            //                {where}
            //                order by T.""TransactionDate"" desc ";


            var paramsString = "";

            paramsString += model.FromDate != null ? $@"'{model.FromDate}'::timestamp without time zone" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            paramsString += model.ReceiptAreaTypeId > 0 ? $@", '{model.ReceiptAreaTypeId}'" : $@", null";


            var query = $@"Select * from ""udf_report_TransactionTallyExcel""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<TransactionModel>(query);

        }

        public Task<IEnumerable<PatienSaleBill1>> FetchPatientPharmacyReportAndroidAsync(PatienSaleBill1 model)
        {

            var where = "1=1";
            if (model.PatientId != null)
            {
                where += $@" and PH.""PatientId""='{model.PatientId}'";
            }

            var query = $@"select Count(*) OVER() AS ""TotalItems"" ,PH.""PharmacySaleHeaderId"" ,PH.""LocationId"",PH.""BillNumber"",PT.""PayTypeName"" as ""PaidVia"",PH.""PaymentNumber"",PH.""CreatedDate"" ""SaleDate"",
	                    PH.""PatientName"",PH.""Mobile"" ,Pa.""UMRNo"" ,Pa.""PatientId"",PH.""ProviderName"",A.""FullName""
                        ""CreatedByName"",R.""RoleName"" ""Role"" , A.""AccountId"", A.""FullName"" as ""CreatedBy"",
	                    PH.""OverallNetAmount"" as ""TotalAmount"",true ""PharmacyBillType"",null ""SaleReturnHeaderId"",PH.""OverallTaxes"" as ""TotalGST"",
	                    RP.""RetailName""
                        from ""PharmacySaleHeader"" PH
                        join ""Account"" A on A.""AccountId"" = PH.""CreatedBy""
                        join ""Role"" R on R.""RoleId"" = A.""RoleId""
                        join ""PharmacySaleDetail"" PSD on PSD.""PharmacySaleHeaderId"" = PH.""PharmacySaleHeaderId""
                        join ""PharmacyRetailStock"" PRS on PRS.""PharmacyRetailStockId"" = PSD.""PharmacyRetailStockId""
                        join ""RetailWareHouseLink"" RWL on RWL.""RetailWareHouseLinkId"" = PRS.""RetailWareHouseLinkId""
                        join ""RetailPharmacy"" RP on RP.""RetailPharmacyId"" = RWL.""RetailPharmacyId""
                        left join ""Patient"" Pa on Pa.""PatientId""::text = PH.""PatientId""::text
                        left join ""PayType"" PT on PT.""PayTypeId"" = PH.""PayTypeId""
                         where {where} group by PH.""PharmacySaleHeaderId"" ,PH.""BillNumber"",
	                    PT.""PayTypeName"", PH.""PaymentNumber"",
	                    PH.""SaleDate"", PH.""OverallNetAmount"",
	                    PH.""PatientName"",PH.""ProviderName"",Pa.""UMRNo"",A.""FullName""
                        ,R.""RoleName"",RP.""RetailName"",Pa.""PatientId"",A.""AccountId"" order by PH.""SaleDate"" desc";
            if (model.PageIndex != null && model.PageSize != null)
            {
                model.PageIndex = model.PageIndex > 0 ? model.PageIndex - 1 : model.PageIndex;
                query += $@" limit {model.PageSize} offset {model.PageSize * model.PageIndex}";
            }
            return this.unitOfWork.Current.QueryAsync<PatienSaleBill1>(query);


        }

        public async Task<IEnumerable<OutReport>> FetchNewPatientAsync(OutPatientFilterModel model)
        {
            try
            {


                var where = $@" where 1=1 and p.""IsNewPatient"" = true";
                if (model.PatientId != null)
                {
                    where += $@" and p.""PatientId"" = {model.PatientId}";
                }
                if (model.ProviderId != null)
                {
                    where += $@" and a.""ProviderId"" = {model.ProviderId}";
                }
                if (model.ResultType == "Turn On")
                {
                    where += $@" and a.""IsEncounter"" is false";
                }
                if (model.ResultType == "Turn Off")
                {
                    where += $@" and a.""IsEncounter"" is True and a.""QueueStatusId"" = 5";
                }
                var query = $@"select Count(*) OVER() AS ""TotalItems"" ,p.""FullName"" as ""PatientName"",p.""UMRNo"",p.""Mobile"" as ""Mobile"",p.""Gender"" as ""PatientGender"",p.""Age"",
                    pr.""FullName"" as ""ProviderName"",a.""AppointmentNo"",a.""AppointmentDate"",a.""AppointmentTime""::text as ""AppointmentTimes"",d.""DepartmentName"",s.""SpecializationName"" from ""Patient"" p 
                left join ""Appointment"" a on a.""PatientId"" = p.""PatientId""
                left join ""Provider"" pr on pr.""ProviderId"" = a.""ProviderId""
                left join ""Department"" d on d.""DepartmentId"" = a.""DepartmentId""
				left join ""Specialization"" s on s.""SpecializationId"" = a.""SpecializationId"" {where} ";
                if (model.PageIndex != null && model.PageSize != null)
                {
                    model.PageIndex = model.PageIndex > 0 ? model.PageIndex - 1 : model.PageIndex;
                    query += $@" limit {model.PageSize} offset {model.PageSize * model.PageIndex}";
                }
                return await this.unitOfWork.Current.QueryAsync<OutReport>(query);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public Task<IEnumerable<ReceiptReportsModel>> FetchDetailEmployeeRevenueAsync(ReceiptReportsFilterModel model)
        {

            var paramsString = "";
            paramsString += model.FromDate != null ? $@"'{model.FromDate}'::Date" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::Date" : $@", null";
            paramsString += model.LoginAccountId != null ? $@", '{Convert.ToInt32(model.LoginAccountId)}'" : $@", null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            // var query = $@"Select * from ""revenue_EmployeeDetail""({paramsString})";
            var query = $@"Select * from ""revenue_EmployeeDetailTransactionWise1""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<ReceiptReportsModel>(query);
        }

        public Task<IEnumerable<ReceiptReportsModel>> FetchCancelRefundReportAsync(ReceiptReportsFilterModel model)
        {
            var paramsString = "";
            paramsString += model.FromDate != null ? $@"'{model.FromDate}'::Date" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::Date" : $@", null";
            paramsString += model.AccountId != null ? $@", '{model.AccountId}'" : $@", null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            var query = $@"Select * from ""allModule_CancelReport""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<ReceiptReportsModel>(query);
        }

        public Task<IEnumerable<GrossReportsModel>> FetchOPDailyGrossReportAsync(ReceiptReportsFilterModel model)
        {
            var paramsString = "";
            //paramsString += model.FromDate != null ? $@"'{model.FromDate}'::Date" : $@" null";
            //paramsString += model.ToDate != null ? $@", '{model.ToDate}'::Date" : $@", null";
            //paramsString += model.AccountId != null ? $@", '{model.AccountId}'" : $@", null";
            paramsString += model.LocationId > 0 ? $@" '{model.LocationId}'" : $@", null";
            // var query = $@" SELECT * from ""OPGross_Reports""()";
            var query = $@" SELECT * from ""udf_report_PatientDailyGross""({paramsString})";


            return this.unitOfWork.Current.QueryAsync<GrossReportsModel>(query);
        }

        public Task<IEnumerable<ReceiptReportsModel>> FetchLoginUserCollectionReportAsync(ReceiptReportsFilterModel model)
        {
            var paramsString = "";

            paramsString += model.FromDate != null ? $@"'{model.FromDate}'::timestamp without time zone" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";
            paramsString += model.LoginAccountId != null ? $@", '{model.LoginAccountId}'" : $@", null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            var query = $@"Select * from ""collection_userLogin""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<ReceiptReportsModel>(query);
        }

        public Task<IEnumerable<BillDailyReport>> FetchBillDailyReportAsync(ReceiptReportsFilterModel model)
        {
            var paramsString = "";
            paramsString += model.FromDate != null ? $@"'{model.FromDate}T00:00'::timestamp without time zone" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}T23:59'::timestamp without time zone" : $@", null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            var query = $@"Select * from ""udf_BillDailyReport""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<BillDailyReport>(query);
        }

        public Task<IEnumerable<ReceiptReportsModel>> FetchUserCollectionReportAsync(ReceiptReportsFilterModel model)
        {
            var paramsString = "";

            paramsString += model.FromDate != null ? $@"'{model.FromDate}'::timestamp without time zone" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";
            paramsString += model.LoginAccountId != null ? $@", '{model.LoginAccountId}'" : $@", null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            var query = $@"Select * from ""udf_report_collection_userLogin_WO_Pharmacy""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<ReceiptReportsModel>(query);
        }

        public Task<IEnumerable<ReceiptReportsModel>> FetchScheduleAppointmentReportAsync(ReceiptReportsFilterModel model)
        {

            var where = $@"where Ad.""Status"" <> 'C' ";

            if (model.FromDate != null)
            {
                where += $@" and  Ad.""AppointmentDate""::date  >= '{model.FromDate}'::date ";
            }
            if (model.ToDate != null)
            {
                where += $@" and Ad.""AppointmentDate""::date  <= '{model.ToDate}'::date ";
            }
            if (model.LocationId != null)
            {
                where += $@" and  Ad.""LocationId""= '{model.LocationId}'";
            }
            if (model.ProviderId != null)
            {
                where += $@" and  Ad.""ProviderId""= '{model.ProviderId}'";
            }
            var query = $@"select COUNT(Ad.*) OVER () AS ""TotalItems"",

                        Ad.""AppointmentDate"",Ad.""AppointmentNo"", TO_CHAR(Ad.""AppointmentTime"", 'hh12:mi AM') ""AppointmentTime"" ,--Ad.""AppointmentTime"",
                            Ad.""LocationId"",Ad.""ProviderId"",
                        pa.""FullName"" ""PatientName"",Pa.""UMRNo"",pa.""Mobile"",pr.""FullName"" as ""ProviderName"",Ad.""PaymentType"",
                        OB.""ANCCardGeneration"",Ad.""CreatedDate"",A.""FullName"" as ""CreatedByName""

                    from ""Appointment"" Ad
                    join ""Provider"" pr on pr.""ProviderId"" = ad.""ProviderId""
                    join ""Patient"" pa on Ad.""PatientId"" = pa.""PatientId""
                     join ""Account"" A on A.""AccountId"" = Ad.""CreatedBy""
                    left join ""ObEncounter"" OB on OB.""AppointmentId"" = Ad.""AppointmentId""

                    {where}";

            return this.unitOfWork.Current.QueryAsync<ReceiptReportsModel>(query);
        }

        public Task<AdmissionReportModel> FetchAdmissionFormReportAsync(PatientFilterModel model)
        {
            var where = $@" where  AD.""AdmissionNo"" ilike '%{model.AdmissionNo}%' and AD.""LocationId""={model.LocationId}";
            var query = $@"                        
                                select 
                AD.""AdmissionNo"",AD.""AdmissionDate""
                ,BD.""BedNumber"",RM.""RoomName"",WD.""WardName"",FR.""FloorName"",CT.""CaseTypeName"",DR.""FullName"" as ""ProviderName"",
                PAT.""UMRNo"",PAT.""Salutation"",PAT.""FullName"" as ""PatientName"",PAT.""DateOfBirth"",PAT.""Age"" as ""PatientAge"",PAT.""Gender"" as ""PatientGender"",PAT.""Mobile"" as ""PatientMobile""
                ,PAT.""Religion"",PAT.""Nationality"",PAT.""Zipcode"",PAT.""City"",PAT.""StreetAddress"" as ""Address"",PAT.""AddressLine2"" as ""Area"",PAT.""Occupation"" as ""Entitlement"",
                PAT.""ReferredByName"" as ""ReferBy"",
                IC.""FullName"" as ""InsuranceCompanyName"",
                PF.""Relation"",PF.""FullName"" as ""RelationName"",PF.""DOB"" as ""RelativeDOB"",PF.""ContactNo"" as ""RelationMobile""
                from ""Admission"" AD
                join ""Patient"" PAT on PAT.""PatientId"" = AD.""PatientId""
                join ""Bed"" BD on BD.""BedId"" = AD.""BedId""
                join ""Room"" RM on RM.""RoomId"" = BD.""RoomId""
                join ""Ward"" WD on WD.""WardId"" = RM.""WardId""
                join ""Floor"" FR on FR.""FloorId"" = WD.""FloorId""
                left join ""InsuranceCompany"" IC on IC.""InsuranceCompanyId"" = AD.""InsuranceCompanyId""
                left join ""PatientFamily"" PF on PF.""PatientId"" = PAT.""PatientId""
                left join ""CaseType"" CT on CT.""CaseTypeId"" = AD.""CaseTypeId""
                join ""Provider"" DR on DR.""ProviderId"" = AD.""ProviderId"" 

                    {where}";

            return this.unitOfWork.Current.QuerySingleAsync<AdmissionReportModel>(query);
        }

        public Task<IEnumerable<FetchBookScanAppointment>> FetchScheduleScanReportAsync(ReceiptReportsFilterModel model)
        {

            var where = $@"where SA.""Status"" <> 'C' ";

            if (model.FromDate != null)
            {
                where += $@" and  SA.""AppointmentDate""::date  >= '{model.FromDate}'::date ";
            }
            if (model.ToDate != null)
            {
                where += $@" and SA.""AppointmentDate""::date  <= '{model.ToDate}'::date ";
            }
            if (model.LocationId != null)
            {
                where += $@" and  SA.""LocationId""= '{model.LocationId}'";
            }
            if (model.Id != null)
            {
                where += $@" and  SA.""ScanMachineMasterId""= {Convert.ToInt32(model.Id)}";
            }
            var query = $@"select COUNT(SA.*) OVER () AS ""TotalItems"", P.""FullName"" as ""PatientName"",P.""Mobile"" ,P.""UMRNo"" , SA.""AppointmentDate""   ,                    
                           TO_CHAR(SA.""AppointmentTime"", 'hh12:mi AM') as ""AppointmentTime"",                
                           TO_CHAR(SA.""AppointmentEndTime"", 'hh12:mi AM') as ""AppointmentEndTime"",SA.""RequisitionNumber"",
                            TM.""ScanTestName"",MM.""MachineName"",CG.""ANCNo"",
                            SA.""CreatedDate"",A.""FullName"" as ""CreatedByName""
                            from ""BookScanAppointment"" SA
                            join ""Patient"" P on P.""PatientId"" = SA.""PatientId""
                            join ""ScanMachineMaster"" MM on MM.""ScanMachineMasterId"" = SA.""ScanMachineMasterId""
                            join ""ScanTestMaster"" TM on TM.""ScanTestMasterId"" = SA.""ScanTestMasterId""
                            left Join ""ANCCardGeneration"" CG on CG.""PatientId"" = SA.""PatientId""
                            join ""Account"" A on A.""AccountId"" = SA.""CreatedBy""

                    {where}";

            return this.unitOfWork.Current.QueryAsync<FetchBookScanAppointment>(query);
        }

        public Task<IEnumerable<MisReportFetchModel>> FetchMISReportAsync(FilterModel model)
        {
            var paramsString = "";


            paramsString += model.LocationId > 0 ? $@"'{model.LocationId}'" : $@" null";
            //paramsString += model.ToDate != null ? $@", '{model.ToDate}'::Date" : $@", null";
            //paramsString += model.AccountId != null ? $@", '{model.LoginAccountId}'" : $@", null";
            paramsString += model.FromDate != null ? $@",'{model.FromDate}'::Date" : $@", null";
            // var query = $@"Select * from ""MIS_Reports""({paramsString})";
            //var query = $@"Select * from ""Test_MISReport""({paramsString})";
            var query = $@"Select * from ""udf_report_MIS""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<MisReportFetchModel>(query);
        }

        public Task<IEnumerable<DoctorDetailReportModel>> FetchNewDoctorDetailRevenueReportAsync(ReceiptReportsFilterModel model)
        {
            var paramsString = "";

            paramsString += model.FromDate != null ? $@"'{model.FromDate}'::timestamp without time zone" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";
            //paramsString += model.LoginAccountId != null ? $@", '{model.LoginAccountId}'" : $@", null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            var query = $@"select * from ""udf_report_DoctorDetailRevenue""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<DoctorDetailReportModel>(query);
        }


        public Task<IEnumerable<MedicationCountModel>> FetchProductSaleCountReport(MedicineRankFilterModel model)
        {

            var where = $@"where 1=1 ";

            if (model.FromDate != null)
            {
                where += $@" and Pmh.""CreatedDate""::date  >= '{model.FromDate}'::date ";
            }
            if (model.ToDate != null)
            {
                where += $@" and Pmh.""CreatedDate""::date  <= '{model.ToDate}'::date ";
            }
            if (model.PharmacyProductId != null)
            {
                where += $@" and Pmd.""PharmacyProductId""= {model.PharmacyProductId}";
            }

            var qry = "";
            if (model.MedicationType == "excludingSale")
            {
                if (model.LocationId != null)
                {
                    where += $@" and apt.""LocationId""= {model.LocationId}";
                }
                qry = $@"select A.*,DENSE_RANK() OVER(
                        ORDER BY A.""MedicineCount""
                    ) RankNumber
                from(
                    select

                    distinct(Pmd.""PharmacyProductId""), PP.""ProductName"",
                    sum(Pmd.""Dosage"") as ""MedicineCount""
                from

                    ""PatientMedicationDetail"" Pmd

                    join ""PatientMedicationHeader"" Pmh on Pmh.""PatientMedicationHeaderId"" = Pmd.""PatientMedicationHeaderId""
                    join ""Appointment"" apt on apt.""AppointmentId""=Pmh.""AppointmentId""
                    join ""PharmacyProduct"" PP on PP.""PharmacyProductId"" = Pmd.""PharmacyProductId""
               -- where Pmh.""CreatedDate""::Date >= '2023-08-31'
                {where}
                group by Pmd.""PharmacyProductId"", PP.""ProductName""
                )A";
            }
            else
            {
                if (model.LocationId != null)
                {
                    where += $@" and Pmh.""LocationId""= {model.LocationId}";
                }
                qry = $@"select A.*,DENSE_RANK() OVER (
		                                ORDER BY A.""MedicineCount""
	                                ) RankNumber
                                from(
                    select distinct(Pmd.""PharmacyProductId"") ,PP.""ProductName"",
                    sum(Pmd.""Quantity"") as ""MedicineCount""
                    from ""PharmacySaleDetail"" Pmd
                    join ""PharmacySaleHeader"" Pmh on Pmh.""PharmacySaleHeaderId""=Pmd.""PharmacySaleHeaderId""
                    join ""PharmacyProduct"" PP on PP.""PharmacyProductId""=Pmd.""PharmacyProductId""
                    --where Pmh.""CreatedDate""::Date>= '2023-08-31'
                    {where}
                    group by Pmd.""PharmacyProductId"",PP.""ProductName"")A";
            }
            //var paramsString = "";

            //if (model.PharmacyProductId != null)
            //{
            //    paramsString += $@" '{model.PharmacyProductId}'";
            //}
            //else
            //{
            //    paramsString += $@" null";
            //}

            //if (model.LocationId != null)
            //{
            //    paramsString += $@" , '{model.LocationId}'";
            //}
            //else
            //{
            //    paramsString += $@" ,null";
            //}
            //if (model.FromDate != null)
            //{
            //    paramsString += $@" ,'{model.FromDate}'";
            //}
            //else
            //{
            //    paramsString += $@" ,null";
            //}
            //if (model.ToDate != null)
            //{
            //    paramsString += $@" ,'{model.ToDate}'";
            //}
            //else
            //{
            //    paramsString += $@" ,null";
            //}


            //if (model.LocationId != null)
            //{
            //    paramsString += $@" ,'{model.LocationId}'";
            //}
            //else
            //{
            //    paramsString += $@" ,null";
            //}
            //var query = $@"Select COUNT(*) OVER () AS ""TotalItems"",* from ""udf_fetch_LabOrderDetails""({paramsString})";
            //model.PageIndex -= 1;
            //query += " LIMIT " + model.PageSize + " offset " + (model.PageIndex * model.PageSize);
            //return this.unitOfWork.Current.QueryAsync<MedicationCountModel>(query);
            return this.unitOfWork.Current.QueryAsync<MedicationCountModel>(qry);
        }
        public Task<IEnumerable<LabTATNewReportModel>> FetchLabNewTATReportAsync(LabTATNewReportModel model)
        {
            var paramsString = "";

            paramsString += model.FromDate != null ? $@"'{model.FromDate}'" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'" : $@", null";
            //paramsString += model.LoginAccountId != null ? $@", '{model.LoginAccountId}'" : $@", null";
            paramsString += model.LocationId > 0 ? $@", '{model.LocationId}'" : $@", null";
            paramsString += model.LabMainDetailId > 0 ? $@", '{model.LabMainDetailId}'" : $@", null";
            var query = $@"select * from public.""udf_lab_TAT_Count_report""({paramsString});";
            return this.unitOfWork.Current.QueryAsync<LabTATNewReportModel>(query);
        }

        public Task<IEnumerable<LabMothlyCountModel>> FetchLabMonthlyCountReportAsync(LabMothlyCountModel model)
        {

            var paramsString = "";
            paramsString += model.LocationId > 0 ? $@" '{model.LocationId}'" : $@" null";
            paramsString += model.FromDate != null ? $@", '{model.FromDate}'" : $@", null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'" : $@", null";
            paramsString += model.LabMainDetailId > 0 ? $@", '{model.LabMainDetailId}'" : $@", null";

            var query = $@"select * from public.""udf_lab_mothly_report""({paramsString})";

            return this.unitOfWork.Current.QueryAsync<LabMothlyCountModel>(query);
        }


        public Task<IEnumerable<ConsultantWiseRevenueModel>> ConsultantWiseRevenue(ConsultantWiseRevenueModel model)
        {
            //var paramsString = $@"where 1=1";


            var query = $@"select  A.""StartDate""::date,A.""TestName"",Avg(""Minuts"") ""Avg Minuts""
                        from(
                        select lbtl.""NewLabBookingHeaderId"",nlbd.""NewLabBookingDetailId"",lmd.""TestName"",lbtl.""CreatedDate"" ""StartDate"",
                        lbt.""CreatedDate"" ""EndDate""
                        --, EXTRACT(EPOCH FROM (lbt.""CreatedDate""::timestamp - lbtl.""CreatedDate::timestamp ))/ 60
                        ,(age(lbt.""CreatedDate"" ,lbtl.""CreatedDate"" ))/60 ""Minuts""
                        From ""LabMainDetail"" lmd
                        join ""NewLabBookingDetail"" nlbd on nlbd.""LabMainDetailId""=lmd.""LabMainDetailId""
                        join ""LabBookingTimeLine"" lbtl on lbtl.""NewLabBookingHeaderId""=nlbd.""NewLabBookingHeaderId"" and lbtl.""LabBookingStatusId""=1
                        join ""LabBookingTimeLine"" lbt on lbt.""NewLabBookingDetailId""=nlbd.""NewLabBookingDetailId"" 
                        and lbtl.""NewLabBookingHeaderId""=lbt.""NewLabBookingHeaderId""
                        and lbt.""LabBookingStatusId""=7) A
                        group by A.""TestName"",A.""StartDate"" order by ""StartDate"";";

            return this.unitOfWork.Current.QueryAsync<ConsultantWiseRevenueModel>(query);
        }



        public async Task<IEnumerable<AdmissionDepartmentModel>> FetchAdmissionDepartmentAsync()
        {
            var query = $@"select ad.""DepartmentId"",d.""DepartmentName"",count(*) from ""Admission"" ad 
                        left join ""Department"" d on d.""DepartmentId"" = ad.""DepartmentId"" where ad.""Active""=true
                        GROUP by ad.""DepartmentId"",d.""DepartmentName""";
            return await this.unitOfWork.Current.QueryAsync<AdmissionDepartmentModel>(query);

        }

        public Task<IEnumerable<EmployeeRevenueReportsModel>> FetchConsultationCountAsync(EmployeeRevenueReportsFilterModel model)
        {
            var paramsString = "";
            paramsString += model.ProviderId != null ? $@" '{model.ProviderId}'" : $@" null";
            paramsString += model.LocationId > 0 ? $@", {model.LocationId}" : $@" null";
            paramsString += model.FromDate != null ? $@", '{model.FromDate}'::timestamp without time zone" : $@", null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";
            var query = $@"Select * from ""udf_consultation_statistics""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<EmployeeRevenueReportsModel>(query);
        }

        public Task<IEnumerable<LabBookingModel>> FetchLabDetailReports(LabBookingModel model)
        {
            var paramsString = "";

            if (model.PatientId != null)
            {
                paramsString += $@" '{model.PatientId}'";
            }
            else
            {
                paramsString += $@" null";
            }

            if (model.UMRNo != null)
            {
                paramsString += $@" , '{model.UMRNo}'";
            }
            else
            {
                paramsString += $@" ,null";
            }
            if (model.FromDate != null)
            {
                paramsString += $@" ,'{model.FromDate}'";
            }
            else
            {
                paramsString += $@" ,null";
            }
            if (model.ToDate != null)
            {
                paramsString += $@" ,'{model.ToDate}'";
            }
            else
            {
                paramsString += $@" ,null";
            }

            if (model.DoctorId != null)
            {
                paramsString += $@" ,'{model.DoctorId}'";
            }
            else
            {
                paramsString += $@" ,null";
            }
            if (model.LocationId != null)
            {
                paramsString += $@" ,'{model.LocationId}'";
            }
            else
            {
                paramsString += $@" ,null";
            }
            if (model.LabMainDetailId != null)
            {
                paramsString += $@" ,'{model.LabMainDetailId}'";
            }
            else
            {
                paramsString += $@" ,null";
            }

            var query = $@"Select COUNT(*) OVER () AS ""TotalItems"",* from ""udf_fetch_LabOrderDetails""({paramsString})";

            model.PageIndex -= 1;
            query += " LIMIT " + model.PageSize + " offset " + (model.PageIndex * model.PageSize);
            return this.unitOfWork.Current.QueryAsync<LabBookingModel>(query);
        }



        public Task<IEnumerable<BillDiscountModel>> FetchBillDiscountAsync(BillDiscountModel model)
        {

            var paramsString = "";
            paramsString += model.FromDate != null ? $@" '{model.FromDate}'::timestamp without time zone" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::timestamp without time zone" : $@", null";
            paramsString += model.LocationId != null ? $@",'{model.LocationId}'" : $@", null";
            // paramsString += model.ModuleId != null ? $@", '{model.ModuleId}'" : $@", null";
            paramsString += model.ReceiptAreaTypeId != null ? $@", '{model.ReceiptAreaTypeId}'" : $@", null";
            var query = $@"Select * from ""udf_report_BillDiscount""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<BillDiscountModel>(query);
        }

        public Task FetchLabNewTATReportAsync()
        {
            throw new NotImplementedException();
        }

        public Task<IEnumerable<PharmacyRetailStockReportModel>> FetchExpiredStockAsync(PharmacyRetailStockReportModel model)
        {
            {



                var paramsString = model.LocationId != null ? $@"'{model.LocationId}'" : $@", null";
                paramsString += model.PharmacyWareHouseId != null ? $@", '{model.PharmacyWareHouseId}'" : $@", null";
                paramsString += model.RetailPharmacyId != null ? $@", '{model.RetailPharmacyId}'" : $@", null";
                paramsString += model.FromDate != null ? $@", '{model.FromDate}'::date" : $@", null";
                paramsString += model.ToDate != null ? $@", '{model.ToDate}'::date" : $@", null";
                var query = $@"Select * from ""UDF_Expiry""({paramsString})";
                return this.unitOfWork.Current.QueryAsync<PharmacyRetailStockReportModel>(query);
            }

        }
        public Task<IEnumerable<AdmissionCountsFilterModel>> FetchAdmissionCountDeptWiseAsync(AdmissionCountsFilterModel model)
        {
            var paramsString = "";
            paramsString += model.FromDate != null ? $@" '{model.FromDate}'::date" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::date" : $@", null";
            paramsString += model.LocationId != null ? $@",{model.LocationId}" : $@", null";
            paramsString += model.DepartmentId != null ? $@", {model.DepartmentId}" : $@", null";
            var query = $@"Select * from ""udf_DeptWise_AdmissionCount""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<AdmissionCountsFilterModel>(query);
        }




        public Task<IEnumerable<RetailIndentIssueModel>> FetchRetailIndentIssue(RetailIndentIssueModel model)
        {
            var paramsString = model.FromDate != null ? $@" '{model.FromDate}'" : $@", null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'" : $@", null";
            paramsString += model.LocationId != null ? $@",'{model.LocationId}'" : $@", null";
            paramsString += model.DepartmentId != null ? $@", '{model.DepartmentId}'" : $@", null";
            paramsString += model.RetailPharmacyId != null ? $@", '{model.RetailPharmacyId}'" : $@", null";
            paramsString += model.ProductId != null ? $@", '{model.ProductId}'" : $@", null";
            paramsString += model.Status != null ? $@", '{model.Status}'" : $@", null";
            var query = $@"Select * from ""udf_Indent_Issue_Report1""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<RetailIndentIssueModel>(query);
        }

        public Task<IEnumerable<AdmissionCountsFilterModel>> FetchAvarageStayWardWiseReportAsync(AdmissionCountsFilterModel model)
        {
            var paramsString = "";
            paramsString += model.FromDate != null ? $@" '{model.FromDate}'::date" : $@" null";
            paramsString += model.ToDate != null ? $@", '{model.ToDate}'::date" : $@", null";
            paramsString += model.LocationId != null ? $@",{model.LocationId}" : $@", null";
            paramsString += model.WardId != null ? $@", {model.WardId}" : $@", null";
            var query = $@"Select * from ""udf_Avarage_Stay_Ward_Wise_Report""({paramsString})";
            return this.unitOfWork.Current.QueryAsync<AdmissionCountsFilterModel>(query);
        }
        public async Task<IEnumerable<Call_HistoryModel>> CallHistoryAsync(Call_HistoryModel model)
        {
            var query = "";
            var where = $@"where CH.""ConvertedAsPatient"" IS TRUE";

            if (model.FromDate != null)
            {
                where += $@" and CH.""CreatedDate""::date  >= '{model.FromDate}'::date ";
            }
            if (model.ToDate != null)
            {
                where += $@" and CH.""CreatedDate""::date  <= '{model.ToDate}'::date ";

            }
            if (model.CreatedBy != null)
            {
                where += $@" and CH.""CreatedBy"" ={model.CreatedBy}";
            }
            query = $@"Select Acc.""FullName"",CH.""MobileNumber"", CH.""FirstName"", CH.""ConvertedDate"", CH.""Comments"",CH.""LastName"", CH.""Type""
                        From ""CallHistory"" CH
                        Join ""Account"" Acc On CH.""CreatedBy"" = Acc.""AccountId"" 
                        {where}
                        order by CH.""Id"" desc";

            var response = await this.unitOfWork.Current.QueryAsync<Call_HistoryModel>(query);
            return response;
        }

    }
}

















