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 Bp.Sync.BackEnd.Infrastructure.Repositories.FcBusinesses;
using Vina.Search.Infrastructure.Mappings;

namespace Bp.Sync.BackEnd.Application.Commands.FcBusinesses.Bills
{
    public class SyncFcOutboundBillHandler : MediatR.IRequestHandler<SyncFcOutboundBillCommand, BaseResult>
    {
        private readonly IDbConnection _dbConnection;
        private readonly IFcOutboundBillRepository _FcOutboundBillRepository;
        private readonly IBus _bus;

        public SyncFcOutboundBillHandler(IConfiguration configuration, IFcOutboundBillRepository FcOutboundBillRepository, IBus bus)
        {
            var connectionString = configuration.GetConnectionString("FcBusinessConnection");
            _dbConnection = new SqlConnection(connectionString);
            _FcOutboundBillRepository = FcOutboundBillRepository;
            _bus = bus;
        }

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

            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 FcOutboundBills = await _dbConnection.QueryAsync<Domain.Entities.FcBusinesses.Bills.OutboundBill>("Sync_OutboundBill_Get_By_List_Id", p, commandType: CommandType.StoredProcedure);
                if (FcOutboundBills.Any())
                {
                    var FcOutboundBillRs = FcOutboundBills.ToFcOutboundBills();
                    var rs2 = await _FcOutboundBillRepository.AddManyAsync(FcOutboundBillRs);
                    if (rs2.Result == Result.Success)
                    {
                        await _dbConnection.ExecuteAsync("Synced_OutboundBill_By_List_Id", p, commandType: CommandType.StoredProcedure);
                        rs.Message = $"{FcOutboundBillRs.Count()} synced";
                        rs.Result = Result.Success;

                        var bids = FcOutboundBillRs.Select(x => x.Id).ToList();
                        await _bus.SendAsync($"UpdateFcChildBillByBill", bids.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;
        }
    }
}