using Bp.Sync.BackEnd.Infrastructure.Repositories;
using Bp.Sync.Domain.Elastics.Inventories.Products;
using Bp.Sync.Domain.Entities.Inventories.Products;
using Bp.Sync.Dto.Results;
using CommonLibrary;
using Dapper;
using EasyNetQ;
using MediatR;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Vina.Search.Infrastructure.Mappings;

namespace Bp.Sync.BackEnd.Application.Commands.Inventories.Products.ProductBills
{
    public class SyncProductBillHandler : IRequestHandler<SyncProductBillCommand, BaseResult>
    {
        private readonly IDbConnection _dbConnection;
        private readonly IProductBillRepository _ProductBillRepository;
        private readonly IProductInventoryRepository _productInventoryRepository;
        private readonly IBus _bus;

        public SyncProductBillHandler(IConfiguration configuration, IProductBillRepository ProductBillRepository, IBus bus, IProductInventoryRepository productInventoryRepository)
        {
            var connectionString = configuration.GetConnectionString("InventoryConnection");
            _dbConnection = new SqlConnection(connectionString);
            _ProductBillRepository = ProductBillRepository;
            _bus = bus;
            _productInventoryRepository = productInventoryRepository;
        }

        public async Task<BaseResult> Handle(SyncProductBillCommand request, CancellationToken cancellationToken)
        {
            var rs = new BaseResult();

            if (request.Ids.Count() > 1000)
            {
                var length = request.Ids.Count();
                if (length > 0)
                {
                    for (int i = 0; i <= length / 1000; i++)
                    {
                        if (length > i * 1000)
                        {
                            var ids = request.Ids.Skip(i * 1000).Take(1000).ToList();
                            if (ids.Count() > 0)
                            {
                                await _bus.SendAsync($"SyncToElasticProductBill", ids.ConvertListLongToString());
                            }
                        }
                    }
                }
                return new BaseResult { Result = Result.Success, Message = $"sent {length} ProductBills" };
            }
            if (!request.Ids.Any())
            {
                rs.Message = $"no data to update";
                rs.Result = Dto.Results.Result.Success;
                return rs;
            }

            try
            {
                var p = new Dto.DapperTypes.IdsParam(request.Ids);
                var ProductBills = await _dbConnection.QueryAsync<ProductBill>("Sync_ProductBill_Get_By_List_Id", p, commandType: CommandType.StoredProcedure);
                if (ProductBills.Any())
                {
                    var ProductBillRs = ProductBills.ToProductBills();
                    var rs2 = await _ProductBillRepository.AddManyAsync(ProductBillRs);
                    if (rs2.Result == Result.Success)
                    {
                        await _dbConnection.ExecuteAsync("Synced_ProductBill_By_List_Id", p, commandType: CommandType.StoredProcedure);
                        rs.Message = $"{ProductBillRs.Count()} synced";
                        rs.Result = Result.Success;

                        //lấy ra tất cả productinventory để đồng bộ lại
                        var productIds = ProductBillRs.Select(x => x.ProductId).Distinct().ToList();
                        var query = new Nest.BoolQueryDescriptor<ProductInventoryElastic>();
                        var aggs = new Nest.AggregationContainerDescriptor<ProductInventoryElastic>();

                        var productIdQ = new Nest.QueryContainerDescriptor<ProductInventoryElastic>();
                        productIdQ.Terms(t => t.Field(f => f.ProductId).Terms(productIds));
                        var notDelete1Q = new Nest.QueryContainerDescriptor<ProductInventoryElastic>();
                        notDelete1Q.Terms(t => t.Field(f => f.IsDeleted).Terms(false));
                        var quantityQ = new Nest.QueryContainerDescriptor<ProductInventoryElastic>();
                        quantityQ.Range(r => r.Field(f => f.Quantity).GreaterThan(0));
                        query.Filter(f => productIdQ && notDelete1Q && quantityQ);
                        aggs.Terms("id", s2 => s2.Field(f2 => f2.Id).Size(10000));
                        var rsagg = await _productInventoryRepository.SearchAgg(query, aggs);

                        var listpiIds = new List<long>();
                        if (rsagg != null)
                        {
                            var r = rsagg.Aggregations.Terms("id");
                            foreach (var item in r.Buckets)
                            {
                                listpiIds.Add(long.Parse(item.Key.ToString()));
                            }
                        }
                        if (listpiIds.Any())
                            await _bus.SendAsync($"UpdateToElasticProductInventoryEx", listpiIds.ConvertListLongToString());
                    }
                    else
                    {
                        rs.Message = $"can not insert db";
                        rs.Result = Result.Success;
                    }
                }
                else
                {
                    rs.Message = $"no data to update";
                    rs.Result = Result.Success;
                }
            }
            catch (Exception ex)
            {
                rs.Message = ex.Message.ToString();
                rs.Result = Result.SystemError;
            }
            return rs;
        }
    }
}