using Bp.Sync.BackEnd.Infrastructure.ElasticDbContext;
using Bp.Sync.Domain.Elastics.Inventories;
using Bp.Sync.Dto.Results;
using Bp.Sync.Dto.SmartTable;
using Microsoft.Extensions.Options;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Bp.Sync.BackEnd.Infrastructure.Repositories
{
    public interface IBillRepository
    {
        Task<BaseResult> Add(BillElastic bill);

        Task<BaseResult> AddManyAsync(IEnumerable<BillElastic> bills);

        Task<BulkResponse> DeleteBills(IEnumerable<BillElastic> bills);

        Task<DeleteByQueryResponse> DeleteBillsByQuery(IEnumerable<long> ids);

        Task<SmartTableResult<BillElastic>> SearchForExcel(BoolQueryDescriptor<BillElastic> query);

        Task<SmartTableResult<BillElastic>> Search(BoolQueryDescriptor<BillElastic> query, int cout);

        Task<SmartTableResult<BillElastic>> GetByIds(List<long> ids);

        Task<List<long>> GetByCustomerIds(List<long> ids);
    }

    public class BillRepository : IBillRepository
    {
        private readonly ElasticIndex<BillElastic> _dbContext;

        public BillRepository(IOptions<ElasticConnectionSettings> settings)
        {
            _dbContext = new ElasticIndex<BillElastic>(settings.Value.ClusterUrl, "inventorybill");
        }

        #region search

        public async Task<SmartTableResult<BillElastic>> SearchForExcel(BoolQueryDescriptor<BillElastic> query)
        {
            return await _dbContext.Search(query);
        }

        #endregion search

        #region Add order

        public async Task<BaseResult> Add(BillElastic bill)
        {
            var result = new BaseResult() { Result = Dto.Results.Result.Success };
            var rs = await _dbContext.Insert(bill);
            if (rs.IsValid)
            {
                result.Result = Dto.Results.Result.Success;
            }
            else
            {
                result.Result = Dto.Results.Result.SystemError;
                result.Message = "Không tạo được bản ghi";
            }
            return result;
        }

        public async Task<BaseResult> AddManyAsync(IEnumerable<BillElastic> bills)
        {
            var result = new BaseResult { Result = Dto.Results.Result.Success };
            try
            {
                var rs = await _dbContext.InsertMany(bills);
                if (rs.IsValid) return result;
                else
                {
                    result.Result = Dto.Results.Result.Failed;
                    result.Message = rs.Errors.ToString();
                    return result;
                }
            }
            catch (Exception exx)
            {
                result.Result = Dto.Results.Result.Failed;
                result.Message = exx.Message.ToString();
                return result;
            }
        }

        public async Task<BulkResponse> DeleteBills(IEnumerable<BillElastic> bills)
        {
            return await _dbContext.DeleteMany(bills);
        }

        public async Task<DeleteByQueryResponse> DeleteBillsByQuery(IEnumerable<long> ids)
        {
            return await _dbContext.DeleteByIds(ids);
        }

        public async Task<SmartTableResult<BillElastic>> GetByIds(List<long> ids)
        {
            var query = new BoolQueryDescriptor<BillElastic>();
            var idsQ = new QueryContainerDescriptor<BillElastic>();
            idsQ.Terms(t => t.Field(f => f.Id).Terms(ids));
            query.Filter(fl => idsQ);
            return await _dbContext.Search(query);
        }

        public async Task<SmartTableResult<BillElastic>> Search(BoolQueryDescriptor<BillElastic> query, int cout)
        {
            return await _dbContext.Search(query, cout);
        }

        public async Task<List<long>> GetByCustomerIds(List<long> ids)
        {
            var query = new BoolQueryDescriptor<BillElastic>();
            var idsQ = new QueryContainerDescriptor<BillElastic>();
            idsQ.Terms(t => t.Field(f => f.CustomerId).Terms(ids));
            query.Filter(fl => idsQ);
            var rs = await _dbContext.Search(query);
            return rs.Items.Select(x => x.Id).Distinct().ToList();
        }

        #endregion Add order
    }
}