using Bp.Sync.BackEnd.Infrastructure.Repositories.FcBusinesses;
using Bp.Sync.Domain.Elastics.FcBusinesses.Products;
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;

namespace Bp.Sync.BackEnd.Application.Commands.FcBusinesses.Products.ProductSummaries
{
    public class SyncFcProductSummaryHandler : MediatR.IRequestHandler<SyncFcProductSummaryCommand, BaseResult>
    {
        private readonly IDbConnection _dbConnection;
        private readonly IFcProductSummaryRepository _FcProductSummaryRepository;
        private readonly IBus _bus;

        public SyncFcProductSummaryHandler(IConfiguration configuration, IFcProductSummaryRepository FcProductSummaryRepository, IBus bus)
        {
            var connectionString = configuration.GetConnectionString("FcBusinessConnection");
            _dbConnection = new SqlConnection(connectionString);
            _FcProductSummaryRepository = FcProductSummaryRepository;
            _bus = bus;
        }

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

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

            try
            {
                var p = new Dto.DapperTypes.IdsParam(request.Ids);
                var items = await _dbConnection.QueryAsync<FcProductSummaryElastic>("Sync_ProductSummary_Get_By_List_Id", p, commandType: CommandType.StoredProcedure);
                if (items.Any())
                {
                    foreach (var item in items)
                    {
                        if (item.BillType == Domain.Entities.FcBusinesses.Bills.BillType.RetailReceiptBill)
                        {
                            item.OutboundPrice = item.RetailPrice;
                            item.OutboundQuantity = item.RetailQuantity;
                        }
                        if (item.BillType == Domain.Entities.FcBusinesses.Bills.BillType.CustomerReturnBill)
                        {
                            item.InboundPrice = item.RetailPrice;
                            item.InboundQuantity = item.RetailQuantity;
                        }
                    }

                    var rs2 = await _FcProductSummaryRepository.AddManyAsync(items);
                    if (rs2.Result == Result.Success)
                    {
                        await _dbConnection.ExecuteAsync("Synced_ProductSummary_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;
        }
    }
}