using Dapper;
using EasyNetQ;
using System.Data;
using System;
using System.Threading.Tasks;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System.Linq;
using CommonLibrary;

namespace Bp.Sync.BackEnd.Factories
{
    public interface ISyncDavTaskFactory
    {
        Task Retail_AutoSyncInboundBillDav();

        Task Retail_AutoSyncOutboundBillDav();

        Task Retail_AutoSyncInvoiceBillDav();

        Task SyncProductStorageDav();
    }

    public class SyncDavTaskFactory : ISyncDavTaskFactory
    {
        private readonly IBus _bus;
        private readonly IDbConnection _dbSyncDavConnection;

        public SyncDavTaskFactory(IConfiguration configuration, IBus bus)
        {
            _bus = bus;

            var syncDavConnectionString = configuration.GetConnectionString("FcSyncDavConnection");
            _dbSyncDavConnection = new SqlConnection(syncDavConnectionString);
        }

        public async Task Retail_AutoSyncInboundBillDav()
        {
            await _bus.SendAsync($"RetailAutoSyncInboundBillDav", "Retail_AutoSyncInboundBillDav");
        }

        public async Task Retail_AutoSyncOutboundBillDav()
        {
            await _bus.SendAsync($"RetailAutoSyncOutboundBillDav", "Retail_AutoSyncOutboundBillDav");
        }

        public async Task Retail_AutoSyncInvoiceBillDav()
        {
            await _bus.SendAsync($"RetailAutoSyncInvoiceBillDav", "Retail_AutoSyncInvoiceBillDav");
        }

        public async Task SyncProductStorageDav()
        {
            try
            {
                var count = 10000;
                var step = 1000;
                var p = new DynamicParameters();
                p.Add("@Count", count, DbType.Int32);
                var productIds = await _dbSyncDavConnection.QueryAsync<long>("Sync_ProductStorageDav_Get_Ids", p, commandType: CommandType.StoredProcedure);
                productIds.ToList().Sort();
                int length = productIds.Count();
                if (length > 0)
                {
                    for (int i = 0; i <= length / step; i++)
                    {
                        if (length > i * step)
                        {
                            var timeIds = productIds.Skip(i * step).Take(step).ToList();
                            if (timeIds.Count() > 0)
                            {
                                await _bus.SendAsync<string>($"SyncToElasticProductStorageDav", timeIds.ConvertListLongToString());
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //throw
            }
        }
    }
}