using Bp.Sync.BackEnd.Infrastructure.Repositories;
using Bp.Sync.Domain.Elastics.Inventories.Configurations;
using Bp.Sync.Dto.Results;
using CommonLibrary;
using Dapper;
using EasyNetQ;
using MediatR;
using Microsoft.Extensions.Configuration;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Bp.Sync.BackEnd.Application.Commands.Inventories.Configurations
{
    public class SyncDiscountBranchDetailConfigHandler : IRequestHandler<SyncDiscountBranchDetailConfigCommand, BaseResult>
    {
        private readonly IDbConnection _dbConnection;
        private readonly IDiscountBranchDetailConfigRepository _DiscountBranchDetailConfigRepository;
        private readonly IProductUnitRepository _productUnitRepository;
        private readonly IBus _bus;
        private readonly IUnitRepository _unitRepository;

        public SyncDiscountBranchDetailConfigHandler(IConfiguration configuration,
            IDiscountBranchDetailConfigRepository DiscountBranchDetailConfigRepository,
            IBus bus,
            IProductUnitRepository productUnitRepository,
            IUnitRepository unitRepository)
        {
            var connectionString = configuration.GetConnectionString("InventoryConnection");
            _dbConnection = new SqlConnection(connectionString);
            _DiscountBranchDetailConfigRepository = DiscountBranchDetailConfigRepository;
            _bus = bus;
            _productUnitRepository = productUnitRepository;
            _unitRepository = unitRepository;
        }

        public async Task<BaseResult> Handle(SyncDiscountBranchDetailConfigCommand 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($"SyncToElasticDiscountBranchDetailConfig", ids.ConvertListLongToString());
                            }
                        }
                    }
                }
                return new BaseResult { Result = Result.Success, Message = $"sent {length} DiscountBranchDetailConfigs" };
            }

            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 items = await _dbConnection.QueryAsync<DiscountBranchDetailConfigElastic>("Sync_DiscountBranchDetailConfig_Get_By_List_Id", p, commandType: CommandType.StoredProcedure);
                if (items.Any())
                {
                    var productIds = items.Select(x => x.ProductId).Distinct().ToList();
                    var productUnits = await _productUnitRepository.GetMinUnitByProductIds(productIds);
                    var productUnitAlls = await _productUnitRepository.GetByProductIds(productIds);
                    var units = await _unitRepository.GetAll();
                    foreach (var item in items)
                    {
                        var productunit = productUnits.Items.FirstOrDefault(x => x.ProductId == item.ProductId);
                        if (productunit != null)
                        {
                            item.BaseUnitId = productunit.UnitId;
                            if (item.BaseUnitId > 0)
                                item.BaseUnitName = units.Items.FirstOrDefault(x => x.Id == item.BaseUnitId)?.Name;
                            if (item.UnitId > 0)
                                item.UnitName = units.Items.FirstOrDefault(x => x.Id == item.UnitId)?.Name;
                        }
                        var unitexchange = productUnitAlls.Items.FirstOrDefault(x => x.UnitId == item.UnitId && x.ProductId == item.ProductId);
                        if (unitexchange != null)
                            item.Exchange = unitexchange.Exchange;
                        else item.Exchange = 1;
                    }

                    var rs2 = await _DiscountBranchDetailConfigRepository.AddManyAsync(items);
                    if (rs2.Result == Result.Success)
                    {
                        await _dbConnection.ExecuteAsync("Synced_DiscountBranchDetailConfig_By_List_Id", p, commandType: CommandType.StoredProcedure);
                        rs.Message = $"{items.Count()} synced";
                        rs.Result = Result.Success;
                    }
                    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;
        }
    }
}