namespace Hims.Infrastructure.Services
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Dapper;
    using Domain.Entities;
    using Domain.Repositories.UnitOfWork;
    using Domain.Services;
    using Shared.EntityModels;
    using Shared.UserModels;
    using Hims.Shared.DataFilters;
    using Hims.Domain.Helpers;
    using System.Linq;
    using System.Security.Cryptography.X509Certificates;
    using Hims.Shared.UserModels.Vendors;
    using Hims.Domain.Entities.Vendors;
    using Hims.Domain.Configurations;

    /// <inheritdoc />
    public class SupplierServices : ISupplierService
    {

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

        /// <summary>
        /// The sha helper.
        /// </summary>
        private readonly IShaHelper shaHelper;

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

        /// <summary>
        /// Initializes a new instance of the <see cref="SupplierServices"/> class.
        /// </summary>
        /// <param name="unitOfWork">
        /// The unit of work.
        /// </param>
        public SupplierServices(IUnitOfWork unitOfWork, IShaHelper shaHelper, IRunningEnvironment runningEnvironment)
        {
            this.unitOfWork = unitOfWork;
            this.shaHelper = shaHelper;
            this.runningEnvironment = runningEnvironment;
        }

        /// <inheritdoc/>
        public async Task<int> InsertSupplierAsync(SupplierModel model)
        {
            var checkIfQuery = $@"Select count(*) from ""Supplier"" where lower(""GSTNo"") = '{model.GSTNo.ToLower()}' and ""SupplierOf"" = '{model.SupplierOf}' ";
            var checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>(checkIfQuery);

            if (checkIf > 0)
            {
                return -1;
            }

            if (!string.IsNullOrEmpty(model.Email))
            {
                var checkIfEmail = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""UserId"") FROM ""User"" WHERE UPPER(""Email"") = '{model.Email.ToUpper()}'");
                if (checkIfEmail > 0)
                {
                    return -2;
                }
            }

            if (!string.IsNullOrEmpty(model.Mobile))
            {
                var checkIfMobile = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""UserId"") FROM ""User"" WHERE ""Mobile"" = '{model.Mobile}'");
                if (checkIfMobile > 0)
                {
                    return -2;
                }
            }

            var supplier = new Supplier
            {
                Name = model.Name,
                CreatedDate = DateTime.Now,
                City = model.City,
                Mobile = model.Mobile,
                PinCode = model.PinCode,
                SupplierOf = model.SupplierOf,
                Address = model.Address,
                Email = model.Email,
                BankName = model.BankName,
                AccountHolderName = model.AccountHolderName,
                IfscCode = model.IfscCode,
                AccountNumber = model.AccountNumber,
                CreatedBy = model.CreatedBy,
                DueDays = model.DueDays,
                DrugLicense = model.DrugLicense,
                GSTNo = model.GSTNo,
                ContactPersonName = model.ContactPersonName,
                Pan = model.Pan,
                DeliverDays = model.DeliverDays
            };
            return await this.unitOfWork.Supplier.InsertAsync(supplier);
        }

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

            if (!string.IsNullOrEmpty(model.SupplierOf))
            {
                where += $@" and S.""SupplierOf"" = '{model.SupplierOf}'";
            }

            if (!string.IsNullOrEmpty(model.FromDate))
            {
                where += $@" AND (S.""CreatedDate"" at time zone 'UTC' at time zone 'Asia/Kolkata')::DATE >= '{model.FromDate}'::DATE";
            }

            if (!string.IsNullOrEmpty(model.ToDate))
            {
                where += $@" AND (S.""CreatedDate"" at time zone 'UTC' at time zone 'Asia/Kolkata')::DATE <= '{model.ToDate}'::DATE";
            }

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

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

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

            if (!string.IsNullOrEmpty(model.SupplierIds))
            {
                where += $@" and S.""SupplierId"" in ({model.SupplierIds})";
            }

            var query = $@"SELECT count(*) over() as ""TotalItems"", S.*
                                    , A.""FullName"" as ""CreatedByName"",M.""FullName"" as ""ModifiedByName""
	                                FROM ""Supplier""  S
                                    left join ""Account"" A on A.""AccountId"" = S.""CreatedBy""
                                    left join ""Account"" M on M.""AccountId"" = S.""ModifiedBy""
                            {where} order by S.""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<SupplierModel>(query);
        }

        /// <inheritdoc/>
        public async Task<int> UpdateSupplierAsync(SupplierModel model)
        {

            var checkIfQuery = $@"Select count(*) from ""Supplier"" where lower(""GSTNo"") = '{model.GSTNo.ToLower()}' and ""SupplierOf"" = '{model.SupplierOf}' and ""SupplierId"" <>{model.SupplierId} ";
            var checkIf = await this.unitOfWork.Current.QuerySingleOrDefaultAsync<int>(checkIfQuery);

            if (checkIf > 0)
            {
                return -1;
            }

            var record = await this.unitOfWork.Supplier.FindAsync(m => m.SupplierId == model.SupplierId);
            record.Name = model.Name;
            record.City = model.City;
            record.Mobile = model.Mobile;
            record.PinCode = model.PinCode;
            record.Address = model.Address;
            record.Email = model.Email;
            record.BankName = model.BankName;
            record.AccountHolderName = model.AccountHolderName;
            record.IfscCode = model.IfscCode;
            record.AccountNumber = model.AccountNumber;
            record.ModifiedBy = model.ModifiedBy;
            record.ModifiedDate = DateTime.UtcNow.AddMinutes(330);
            record.DueDays = model.DueDays;
            record.ContactPersonName = model.ContactPersonName;
            record.GSTNo = model.GSTNo;
            record.DrugLicense = model.DrugLicense;
            record.Pan = model.Pan;
            record.DeliverDays = model.DeliverDays;

            return await this.unitOfWork.Supplier.UpdateAsync(record);
        }

        /// <inheritdoc/>
        public async Task<int> DeleteSupplierAsync(int supplierId)
        {
            var query = $@"Delete FROM ""Supplier"" where ""SupplierId"" = {supplierId}";
            return await this.unitOfWork.Current.ExecuteAsync(query);
        }

        /// <inheritdoc/>
        public async Task<SupplierModel> FetchAsync(SupplierModel model)
        {
            var where = "where 1=1";
            if (!string.IsNullOrEmpty(model.SupplierOf))
            {
                where += $@" and ""SupplierOf"" = '{model.SupplierOf}'";
            }

            if (!string.IsNullOrEmpty(model.Name))
            {
                where += $@" and Lower(""Name"") = '{model.Name.ToLower()}' ";
            }

            var query = $@"SELECT ""SupplierId"", ""Mobile"", ""PinCode"",""Pan"",""Email"" ""City"", ""ContactPersonName"" ,""DrugLicense"" ,""GSTNo"", ""SupplierOf"", ""CreatedDate"", ""Name"", ""Address"", ""DueDays"",""DeliverDays""
	                                FROM ""Supplier"" {where} limit 1";
            return await this.unitOfWork.Current.QueryFirstOrDefaultAsync<SupplierModel>(query);
        }

        /// <inheritdoc/>
        public async Task<int> AddSupplierProductAsync(SupplierProductModel model)
        {
            var products = model.Products.Where(x => x.SupplierProductId == null).Select(x => new SupplierProduct
            {
                CreatedBy = model.CreatedBy,
                CreatedDate = DateTime.Now,
                PharmacyProductId = x.PharmacyProductId,
                PurchaseRate = x.PurchaseRate,
                Mrp = x.Mrp,
                SupplierId = model.SupplierId
            });

            var response = products.Any() ? await this.unitOfWork.SupplierProducts.BulkInsertAsync(products) : 0;

            var productsToUpdate = model.Products.Where(x => x.SupplierProductId != null).Select(x => new SupplierProduct
            {
                PharmacyProductId = x.PharmacyProductId,
                PurchaseRate = x.PurchaseRate,
                Mrp = x.Mrp,
                SupplierId = model.SupplierId,
                SupplierProductId = (int)x.SupplierProductId
            });

            foreach (var update in productsToUpdate)
            {
                response += await this.unitOfWork.SupplierProducts.UpdateAsync(update);
            }

            return response;
        }

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

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

            var query = $@"SELECT  SP.""SupplierProductId"",SP.""SupplierId"",PP.""PharmacyProductId"", PP.""ProductName"", PP.""GenericName"", 
                                    PP.""Barcode"",PP.""PurchaseUnitQty"", PP.""SaleUnitQty"", PP.""CategoryId"", PP.""CompanyId"", PP.""SupplierId"", PP.""PurchaseUnit"",
                                    PP.""SaleUnit"", PP.""TaxId"",PP.""IsProductExpire"", PP.""Active"", PP.""CreatedBy"", PP.""CreatedDate"",
                                    C.""Name"" as ""CompanyName"",Cat.""Name"" as ""CategoryName"",Tax.""Name"" as ""Tax"",
                                    PurchaseUnit.""Name"" as ""PurchaseUnitName"", SaleUnit.""Name"" as ""SaleUnitName"",
                                    A.""FullName"" as ""CreatedByName"",SP.""PurchaseRate"",SP.""Mrp""
	                                    FROM ""SupplierProduct"" SP 
										join ""PharmacyProduct"" PP on PP.""PharmacyProductId"" = SP.""PharmacyProductId""
										join ""Company"" C on C.""CompanyId"" = PP.""CompanyId""
	                                    join ""LookupValue"" Cat on Cat.""LookupValueId"" = PP.""CategoryId""
	                                    join ""LookupValue"" Tax on Tax.""LookupValueId"" = PP.""TaxId""	                                    
	                                    join ""LookupValue"" PurchaseUnit on PurchaseUnit.""LookupValueId"" = PP.""PurchaseUnit""
	                                    join ""LookupValue"" SaleUnit on SaleUnit.""LookupValueId"" = PP.""SaleUnit""
	                                    left join ""Account"" A on A.""AccountId"" = SP.""CreatedBy""
                                        {where}   order by SP.""CreatedDate"" desc";

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

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

            var query = $@"SELECT count(*) over() as ""TotalItems"", ""ContactPersonName"" ,""DrugLicense"" ,""GSTNo"",""SupplierId"", ""Mobile"", ""Email"",""Pan"",""PinCode"", ""City"", ""SupplierOf"", ""CreatedDate"", ""Name"", ""Address"", ""DueDays""
	                                FROM ""Supplier"" {where} and ""Email"" is not null order by ""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<SupplierModel>(query);
        }

        /// <inheritdoc/>
        public async Task<int> AddSuplierAccountAsync(SupplierModel model)
        {
            var getDetail = await this.unitOfWork.Supplier.FindAsync(x => x.SupplierId == model.SupplierId);
            if (getDetail == null)
            {
                return -1;
            }

            if (getDetail.UserId != null)
            {
                return -5;
            }

            if (!string.IsNullOrEmpty(getDetail.Email))
            {
                var checkIfEmail = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""UserId"") FROM ""User"" WHERE UPPER(""Email"") = '{getDetail.Email.ToUpper()}'");
                if (checkIfEmail > 0)
                {
                    return -2;
                }
            }

            if (!string.IsNullOrEmpty(getDetail.Mobile))
            {
                var checkIfMobile = await this.unitOfWork.Current.QueryFirstOrDefaultAsync<int>($@"SELECT COUNT(""UserId"") FROM ""User"" WHERE ""Mobile"" = '{getDetail.Mobile}'");
                if (checkIfMobile > 0)
                {
                    return -2;
                }
            }

            var checkRole = await this.unitOfWork.Roles.FindAsync(r => r.RoleName == "Vendor");
            var roleId = 0;
            if (checkRole == null)
            {
                var roleModel = new Role
                {
                    RoleName = "Vendor",
                    Active = true,
                    CreatedBy = (int)model.CreatedBy,
                    CreatedDate = DateTime.Now
                };
                roleId = await this.unitOfWork.Roles.InsertAsync(roleModel);
            }
            else
            {
                roleId = checkRole.RoleId;
            }

            var country = await this.unitOfWork.Countries.FindAsync(x => x.CountryName == "India");

            var transaction = this.unitOfWork.BeginTransaction();

            var user = new User
            {
                Active = true,
                RoleId = roleId,
                CreatedBy = model.CreatedBy,
                CreatedDate = DateTime.Now,
                Email = getDetail.Email,
                FirstName = (getDetail.Name.Split(" ")).Length > 0 ? getDetail.Name.Split(" ")[0] : getDetail.Name,
                LastName = (getDetail.Name.Split(" ")).Length == 1 ? getDetail.Name.Split(" ")[1] : string.Empty,
                FullName = getDetail.Name,
                MiddleName = null,
                Mobile = getDetail.Mobile,
                CountryId = country.CountryId,
                DateOfBirth = null,
                Gender = null,
                ModifiedBy = null,
                ModifiedDate = null,
                Guid = Guid.NewGuid()
            };

            user.UserId = await this.unitOfWork.Users.InsertAsync(user, transaction);

            if (user.UserId == 0)
            {
                transaction.Rollback();
                return 0;
            }

            getDetail.UserId = user.UserId;
            var supplierUpdate = await this.unitOfWork.Supplier.UpdateAsync(getDetail, transaction);
            if (supplierUpdate == 0)
            {
                transaction.Rollback();
                return 0;
            }

            var passwordKey = CoreFilter.Random(10);

            var account = new Account
            {
                RoleId = roleId,
                ReferenceId = user.UserId,
                SaltKey = passwordKey,
                CreatedDate = DateTime.Now,
                FullName = user.FullName,
                CountryId = user.CountryId,
                Email = user.Email,
                Mobile = user.Mobile,
                Active = true,
                Guid = user.Guid,
                CreatedBy = model.CreatedBy,
                FailedLoginAttempts = 0,
                IsAgreed = null,
                IsLocked = false,
                LastFailedLoginDate = null,
                LastLoginDate = null,
                ModifiedBy = null,
                ModifiedDate = null,
                UserName = null
            };
            account.AccountId = await this.unitOfWork.Accounts.InsertAsync(account, transaction);
            if (account.AccountId == 0)
            {
                transaction.Rollback();
                return 0;
            }

            var location = new LocationAccountMap
            {
                AccountId = account.AccountId,
                LocationId = (int)model.LocationId
            };
            var locationInsertId = await this.unitOfWork.LocationAccountMap.InsertAsync(location, transaction);
            if (locationInsertId == 0)
            {
                transaction.Rollback();
                return 0;
            }

            var passwordHash = this.shaHelper.GenerateHash("123456", account.SaltKey);
            var query = new AccountsCredential(account, passwordHash).Query;

            var inserted = await this.unitOfWork.Current.ExecuteAsync(query, transaction);
            if (inserted == 0)
            {
                transaction.Rollback();
                return 0;
            }

            transaction.Commit();
            return user.UserId;
        }

        /// <inheritdoc/>
        public async Task<int> AddProductRateListAsync(SupplierNewProductModel model)
        {
            using var transaction = this.unitOfWork.BeginTransaction();
            var headerProduct = new SupplierProductHeader
            {
                CreatedBy = model.CreatedBy,
                CreatedDate = DateTime.Now,
                EndDate = model.EndDate,
                StartDate = model.StartDate,
                SupplierId = model.SupplierId,
                SupplierProductHeaderId = model.SupplierProductHeaderId,
                RateCardUrl = model.RateCardUrl
            };

            if (headerProduct.SupplierProductHeaderId > 0)
            {
                var oldHeaderRecord = await this.unitOfWork.SupplierProductHeaders.FindAsync(h => h.SupplierProductHeaderId == headerProduct.SupplierProductHeaderId);
                if (oldHeaderRecord == null)
                {
                    transaction.Rollback();
                    return -1;
                }

                oldHeaderRecord.ModifiedBy = model.CreatedBy;
                oldHeaderRecord.ModifiedDate = DateTime.Now;
                oldHeaderRecord.StartDate = model.StartDate;
                oldHeaderRecord.EndDate = model.EndDate;
                oldHeaderRecord.RateCardUrl = model.RateCardUrl;

                var updateHeaderRes = await this.unitOfWork.SupplierProductHeaders.UpdateAsync(oldHeaderRecord, transaction);
                if (updateHeaderRes == 0)
                {
                    transaction.Rollback();
                    return -1;
                }
            }
            else
            {
                headerProduct.SupplierProductHeaderId = await this.unitOfWork.SupplierProductHeaders.InsertAsync(headerProduct, transaction);
                if (headerProduct.SupplierProductHeaderId == 0)
                {
                    transaction.Rollback();
                    return -1;
                }
            }

            foreach (var prod in model.Products)
            {
                if (prod.SupplierProductDetailId > 0)
                {
                    var findDetail = await this.unitOfWork.SupplierProductDetails.FindAsync(d => d.SupplierProductDetailId == prod.SupplierProductDetailId);
                    if (findDetail == null)
                    {
                        transaction.Rollback();
                        return -1;
                    }

                    findDetail.Mrp = Math.Round(prod.Mrp, 2);
                    findDetail.PurchaseRate = Math.Round(prod.PurchaseRate, 2);
                    var updateDetail = await this.unitOfWork.SupplierProductDetails.UpdateAsync(findDetail, transaction);
                    if (updateDetail == 0)
                    {
                        transaction.Rollback();
                        return -1;
                    }

                    var deleteFormQuery = $@"delete from vendors.""SupplierProductFormulation"" where ""SupplierProductDetailId"" = {prod.SupplierProductDetailId}";
                    await this.unitOfWork.Current.ExecuteAsync(deleteFormQuery, transaction);
                }
                else
                {
                    var detail = new SupplierProductDetail
                    {
                        Mrp = Math.Round(prod.Mrp, 2),
                        PurchaseRate = Math.Round(prod.PurchaseRate, 2),
                        PharmacyProductId = prod.PharmacyProductId,
                        SupplierProductHeaderId = headerProduct.SupplierProductHeaderId
                    };

                    detail.SupplierProductDetailId = await this.unitOfWork.SupplierProductDetails.InsertAsync(detail, transaction);
                    prod.SupplierProductDetailId = detail.SupplierProductDetailId;
                    if (detail.SupplierProductDetailId == 0)
                    {
                        transaction.Rollback();
                        return -1;
                    }
                }

                foreach (var formula in prod.Formulations)
                {
                    var formulation = new SupplierProductFormulation
                    {
                        Condition = formula.Condition,
                        FOCQuantity = formula.FOCQuantity,
                        Operator = formula.Operator,
                        SupplierProductDetailId = prod.SupplierProductDetailId
                    };

                    formulation.SupplierProductFormulationId = await this.unitOfWork.SupplierProductFormulations.InsertAsync(formulation, transaction);
                    if (formulation.SupplierProductFormulationId == 0)
                    {
                        transaction.Rollback();
                        return -1;
                    }
                }
            }
            transaction.Commit();

            return headerProduct.SupplierProductHeaderId;
        }

        /// <inheritdoc/>
        public async Task<IEnumerable<SupplierNewProductModel>> FetchRateCardsAsync(int supplierId)
        {
            var headerQuery = $@"SELECT sph.""SupplierProductHeaderId"", sph.""SupplierId"", sph.""StartDate""::date, sph.""EndDate""::date, sph.""CreatedBy"", sph.""CreatedDate"", 
	                                       sph.""ModifiedBy"", sph.""ModifiedDate"", c.""FullName"" as ""CreatedByName"", m.""FullName"" as ""ModifiedByName"", sph.""RateCardUrl""
                                         FROM vendors.""SupplierProductHeader""  sph
                                         left join ""Account"" c on c.""AccountId""  = sph.""CreatedBy""
                                         left join ""Account"" m on m.""AccountId""  = sph.""ModifiedBy""
                                         where sph.""SupplierId""  = {supplierId}
                                         order by sph.""CreatedDate"" desc";
            var headerResponse = await this.unitOfWork.Current.QueryAsync<SupplierNewProductModel>(headerQuery);
            foreach (var header in headerResponse)
            {
                header.Products = new List<SupplierProductDetailModel>();
                if (!string.IsNullOrEmpty(header.RateCardUrl))
                {
                    var formedUrl = $@"{this.runningEnvironment.CurrentEnvironment}/SupplierRateDocument/{header.SupplierId}/{header.RateCardUrl}";
                    header.RateCardUrl = formedUrl;
                }
                var prodQuery = $@"SELECT spd.""SupplierProductDetailId"", spd.""SupplierProductHeaderId"", spd.""PharmacyProductId"", spd.""PurchaseRate"", spd.""Mrp"",
	                                pp.""ProductName"" ,pp.""GenericName"", pp.""InventoryItem"" , pr.""Name"" as ""PurchaseUnitName""
	                                FROM vendors.""SupplierProductDetail"" spd
	                                join public.""PharmacyProduct"" pp on pp.""PharmacyProductId"" = spd.""PharmacyProductId"" 
                                    left join public.""LookupValue"" pr on pr.""LookupValueId"" = pp.""PurchaseUnit""
	                                where spd.""SupplierProductHeaderId"" = {header.SupplierProductHeaderId}";
                header.Products = (await this.unitOfWork.Current.QueryAsync<SupplierProductDetailModel>(prodQuery)).ToList();

                foreach (var product in header.Products)
                {
                    product.Formulations = new List<SupplierProductFormulationModel>();
                    var formulationQuery = $@"SELECT ""SupplierProductFormulationId"", ""SupplierProductDetailId"", ""Operator"", ""Condition"", ""FOCQuantity""
	                                    FROM vendors.""SupplierProductFormulation""
	                                    where ""SupplierProductDetailId"" = {product.SupplierProductDetailId}";
                    product.Formulations = (await this.unitOfWork.Current.QueryAsync<SupplierProductFormulationModel>(formulationQuery)).ToList();

                }
                if (DateTime.Now.Date >= header.StartDate)
                {
                    header.IsStarted = true;
                    header.DaysToExpire = (header.EndDate - DateTime.Now.Date).Days;
                }
            }

            return headerResponse;
        }

        /// <inheritdoc/>
        public async Task<int> CheckIfDateRangeAlreadyExists(SupplierNewProductModel product)
        {
            var query = $@"SELECT sph.* 
	                         FROM vendors.""SupplierProductHeader"" sph	
                             where sph.""SupplierId"" = {product.SupplierId} ";
            if (product.SupplierProductHeaderId > 0)
            {
                query += $@" and sph.""SupplierProductHeaderId"" <> {product.SupplierProductHeaderId}";
            }

            var response = await this.unitOfWork.Current.QueryAsync<SupplierNewProductModel>(query);
            var count = 0;
            foreach (var item in response)
            {

                var startDate = item.StartDate.Date;
                var endDate = item.EndDate.Date;
                var compareStartDate = product.StartDate.Date;
                var compareEndDate = product.EndDate.Date;
                int compare1 = DateTime.Compare(startDate, compareEndDate);
                if (compare1 > 0) { count++; }
                int compare2 = DateTime.Compare(endDate, compareStartDate);
                if (compare2 > 0)
                {
                    count++;
                }
            }
            return count;
        }


    }
}