using Bp.Sync.BackEnd.Infrastructure.Repositories;
using Bp.Sync.Domain.Entities.Inventories.Units;
using Bp.Sync.Dto.Results;
using CommonLibrary;
using Dapper;
using EasyNetQ;
using Microsoft.Extensions.Configuration;
using System;
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.Units
{
    public class SyncProductUnitHandler : MediatR.IRequestHandler<SyncProductUnitCommand, BaseResult>
    {
        private readonly IDbConnection _dbConnection;
        private readonly IProductUnitRepository _ProductUnitRepository;
        private readonly IBus _bus;

        public SyncProductUnitHandler(IConfiguration configuration, IProductUnitRepository ProductUnitRepository, IBus bus)
        {
            var connectionString = configuration.GetConnectionString("InventoryConnection");
            _dbConnection = new SqlConnection(connectionString);
            _ProductUnitRepository = ProductUnitRepository;
            _bus = bus;
        }

        public async Task<BaseResult> Handle(SyncProductUnitCommand 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($"SyncToElasticProductUnit", ids.ConvertListLongToString());
                            }
                        }
                    }
                }
                return new BaseResult { Result = Result.Success, Message = $"sent {length} Product Units" };
            }
            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 Units = await _dbConnection.QueryAsync<ProductUnit>("Sync_ProductUnit_Get_By_List_Id", p, commandType: CommandType.StoredProcedure);
                if (Units.Any())
                {
                    var UnitRs = Units.ToProductUnits();

                    var unitids = UnitRs.Select(x => (long)x.UnitId).Distinct().ToList();
                    var pu = new Dto.DapperTypes.IdsParam(unitids);
                    var UnitAlls = await _dbConnection.QueryAsync<Unit>("Sync_Unit_Get_By_List_Id", pu, commandType: CommandType.StoredProcedure);

                    if (UnitAlls.Any())
                    {
                        foreach (var item in UnitRs)
                        {
                            item.UnitName = UnitAlls.FirstOrDefault(x => x.Id == item.UnitId)?.Name;
                        }
                    }

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