using Bp.Sync.BackEnd.Infrastructure.Repositories;
using Bp.Sync.Domain.Elastics.Inventories.Customers;
using Bp.Sync.Domain.Entities.Inventories.Customers;
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.Customers
{
    public class SyncCustomerHandler : IRequestHandler<SyncCustomerCommand, BaseResult>
    {
        private readonly IDbConnection _dbConnection;
        private readonly ICustomerRepository _CustomerRepository;
        private readonly IBillRepository _billRepository;
        private readonly IBus _bus;

        public SyncCustomerHandler(IConfiguration configuration, ICustomerRepository CustomerRepository, IBus bus, IBillRepository billRepository)
        {
            var connectionString = configuration.GetConnectionString("InventoryConnection");
            _dbConnection = new SqlConnection(connectionString);
            _CustomerRepository = CustomerRepository;
            _bus = bus;
            _billRepository = billRepository;
        }

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

            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 Customers = await _dbConnection.QueryAsync<Customer>("Sync_Customer_Get_By_List_Id", p, commandType: CommandType.StoredProcedure);
                if (Customers.Any())
                {
                    var CustomerRs = Customers.ToCustomers();

                    var customerelastics = await _CustomerRepository.GetByIds(request.Ids);
                    var changeManagers = new List<CustomerElastic>();
                    foreach (var item in CustomerRs)
                    {
                        var c = customerelastics.Items.FirstOrDefault(x => x.Id == item.Id);
                        if (c != null)
                        {
                            if (item.ManagerId != c.ManagerId)
                            {
                                changeManagers.Add(item);
                            }
                        }
                    }

                    var rs2 = await _CustomerRepository.AddManyAsync(CustomerRs);
                    if (rs2.Result == Result.Success)
                    {
                        await _dbConnection.ExecuteAsync("Synced_Customer_By_List_Id", p, commandType: CommandType.StoredProcedure);
                        rs.Message = $"{CustomerRs.Count()} synced";
                        rs.Result = Result.Success;
                        //đồng bộ lại người quản lý trong bill
                        try
                        {
                            if (changeManagers.Any())
                            {
                                foreach (var item in changeManagers)
                                {
                                    var billids = await _billRepository.GetByCustomerIds(new List<long> { item.Id });

                                    if (billids.Count > 0)
                                    {
                                        var step = 100;
                                        billids.ToList().Sort();
                                        int length = billids.Count();
                                        for (int i = 0; i <= length / step; i++)
                                        {
                                            if (length > i * step)
                                            {
                                                var timeIds = billids.Skip(i * step).Take(step).ToList();
                                                if (timeIds.Count() > 0)
                                                {
                                                    await _bus.SendAsync($"SyncToElasticBill", timeIds.ConvertListLongToString());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch { }
                    }
                    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;
        }
    }
}